package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleFenceRelDO;
import com.zcloud.personnel.positioning.persistence.dataobject.FenceDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleFenceRelRepository;
import com.zcloud.personnel.positioning.persistence.repository.FenceRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@AllArgsConstructor
public class FenceRemoveExe {
    private final FenceRepository fenceRepository;
    private final AlarmRuleFenceRelRepository alarmRuleFenceRelRepository;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        FenceDO fenceDO = fenceRepository.getById(id);
        if (fenceDO == null) {
            return true;
        }
        QueryWrapper<AlarmRuleFenceRelDO> relWrapper = new QueryWrapper<>();
        relWrapper.eq("fence_id", id);
        relWrapper.and(value -> value.isNull("delete_enum").or().eq("delete_enum", "FALSE"));
        if (alarmRuleFenceRelRepository.count(relWrapper) > 0) {
            throw new BizException("围栏已关联告警配置，请先删除关联告警配置");
        }
        fenceDO.setSyncStatus(FindsPendingSyncService.STATUS_DELETE_WAIT);
        fenceDO.setSyncToken(FindsSyncToken.next());
        if (!fenceRepository.updateById(fenceDO)) {
            throw new BizException("Fence delete failed");
        }
        findsPendingSyncService.scheduleFence(id);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return true;
        }
        for (Long id : ids) {
            execute(id);
        }
        return true;
    }
}
