package com.zcloud.zcGbsServicer.command;

import com.zcloud.zcGbsServicer.command.convertor.ResourceDeviceCoConvertor;
import com.zcloud.zcGbsServicer.command.convertor.ResourcePersonCoConvertor;
import com.zcloud.zcGbsServicer.domain.gateway.ControlRoomGateway;
import com.zcloud.zcGbsServicer.domain.gateway.ResourceDeviceGateway;
import com.zcloud.zcGbsServicer.domain.gateway.ResourcePersonGateway;
import com.zcloud.zcGbsServicer.domain.model.ControlRoomE;
import com.zcloud.zcGbsServicer.domain.model.ResourceDeviceE;
import com.zcloud.zcGbsServicer.domain.model.ResourcePersonE;
import com.zcloud.zcGbsServicer.dto.ControlRoomAddCmd;
import com.alibaba.cola.exception.BizException;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
* web-app
* @Author makejava
* @Date 2026-01-21 17:21:47
*/
@Component
@AllArgsConstructor
public class ControlRoomAddExe {
    private final ControlRoomGateway controlRoomGateway;

    private final ResourcePersonGateway resourcePersonGateway;
    private final ResourcePersonCoConvertor resourcePersonCoConvertor;
    private final ResourceDeviceGateway resourceDeviceGateway;
    private final ResourceDeviceCoConvertor resourceDeviceCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(ControlRoomAddCmd cmd) {
        ControlRoomE controlRoomE = new ControlRoomE();
        BeanUtils.copyProperties(cmd, controlRoomE);
        List<ResourcePersonE> persons = resourcePersonCoConvertor.converAddToEOs(cmd.getPersons());
        List<ResourceDeviceE> devices = resourceDeviceCoConvertor.converAddToE(cmd.getDevices());
        controlRoomE.addInit(persons,  devices);
        boolean res = false;
        boolean addPerRes = false;
        boolean addDeviceRes = false;
        try {
            res = controlRoomGateway.add(controlRoomE);
            addPerRes = resourcePersonGateway.addBatch(controlRoomE.getPersons());
            addDeviceRes = resourceDeviceGateway.addBatch(controlRoomE.getDevices());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res || !addPerRes || !addDeviceRes) {
            throw new BizException("保存失败");
        }
        return true;
    }
}

