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.persistence.dataobject.FireDeviceDO;
import com.zcloud.fire.check.persistence.repository.FireCheckListItemRepository;
import com.zcloud.fire.check.persistence.repository.FireDeviceRepository;
import lombok.AllArgsConstructor;
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 FireDeviceRemoveExe {
    private final FireDeviceGateway fireDeviceGateway;
    private final FireDeviceRepository fireDeviceRepository;
    private final FireCheckListItemRepository fireCheckListItemRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        FireDeviceDO fireDeviceDO = fireDeviceRepository.getById( id);
        if (fireDeviceDO == null) {
            throw new BizException("设备不存在");
        }

        Long count = fireCheckListItemRepository.countByDeviceId(fireDeviceDO.getFireDeviceId());
        if(count>0){
            throw new BizException("请先删除关联的检查表记录");
        }
        boolean res = fireDeviceGateway.deletedFireDeviceById(id);
        if (!res) {
            throw new BizException("删除失败");
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        for (Long id : ids) {
            FireDeviceDO fireDeviceDO = fireDeviceRepository.getById( id);
            if (fireDeviceDO == null) {
                throw new BizException("设备不存在");
            }

            Long count = fireCheckListItemRepository.countByDeviceId(fireDeviceDO.getFireDeviceId());
            if(count>0){
                throw new BizException(fireDeviceDO.getFireDeviceCode()+"请先删除关联的检查表记录");
            }
        }
        boolean res = fireDeviceGateway.deletedFireDeviceByIds(ids);
        if (!res) {
            throw new BizException("删除失败");
        }

        return true;
    }
}

