package com.zcloud.fire.check.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.fire.check.domain.gateway.FireDeviceGateway;
import com.zcloud.fire.check.domain.model.FireDeviceE;
import com.zcloud.fire.check.dto.FireDeviceAddCmd;
import com.zcloud.fire.check.persistence.repository.FireDeviceRepository;
import com.zcloud.fire.check.persistence.repository.FireRegionRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-26 10:12:34
 */
@Component
@AllArgsConstructor
public class FireDeviceAddExe {
    private final FireDeviceGateway fireDeviceGateway;
    private final FireDeviceRepository fireDeviceRepository;
    private final FireRegionRepository fireRegionRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(FireDeviceAddCmd cmd) {
        // 校验消防器材编码是否重复
        if (fireDeviceRepository.existsByDeviceCode(cmd.getFireDeviceCode())) {
            throw new BizException("消防器材编码已存在");
        }
        //校验区域
        fireRegionRepository.checkRegion(cmd.getFireRegionId());

        FireDeviceE fireDeviceE = new FireDeviceE();
        BeanUtils.copyProperties(cmd, fireDeviceE);
        boolean res = false;
        try {
            res = fireDeviceGateway.add(fireDeviceE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }
}

