package com.zcloud.zcGbsServicer.command;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.zcloud.zcGbsServicer.command.convertor.ResourceDeviceCoConvertor;
import com.zcloud.zcGbsServicer.domain.enums.DeviceTypeEnum;
import com.zcloud.zcGbsServicer.domain.gateway.PumpRoomGateway;
import com.zcloud.zcGbsServicer.domain.gateway.ResourceDeviceGateway;
import com.zcloud.zcGbsServicer.domain.model.PumpRoomE;
import com.zcloud.zcGbsServicer.domain.model.ResourceDeviceE;
import com.zcloud.zcGbsServicer.dto.PumpRoomUpdateCmd;
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:22:16
*/
@Component
@AllArgsConstructor
public class PumpRoomUpdateExe {
    private final PumpRoomGateway pumpRoomGateway;
    private final ResourceDeviceGateway resourceDeviceGateway;
    private final ResourceDeviceCoConvertor resourceDeviceCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public void execute(PumpRoomUpdateCmd pumpRoomUpdateCmd) {
        PumpRoomE pumpRoomE = new PumpRoomE();
        BeanUtils.copyProperties(pumpRoomUpdateCmd, pumpRoomE);
        boolean res = pumpRoomGateway.update(pumpRoomE);
        boolean resDev = executePersonAndDevice(pumpRoomUpdateCmd);
        if (!res || !resDev) {
            throw new BizException("修改失败");
        }
    }

    /**
     * 处理设备修改
     */
    private boolean executePersonAndDevice(PumpRoomUpdateCmd pumpRoomUpdateCmd) {
        Integer bizType = DeviceTypeEnum.PUMP_ROOM.getCode();
        resourceDeviceGateway.deletedResourceDeviceByBizId(pumpRoomUpdateCmd.getPumpRoomId(), bizType);
        if (CollUtil.isEmpty(pumpRoomUpdateCmd.getDevices())) {
            return true;
        }
        List<ResourceDeviceE> devices = resourceDeviceCoConvertor.converAddToE(pumpRoomUpdateCmd.getDevices());
        devices.forEach(d -> {
            d.relInfo(pumpRoomUpdateCmd.getPumpRoomId(), bizType);
        });
        return resourceDeviceGateway.addBatch(devices);
    }
}

