package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.dto.AlarmRuleUpdateCmd;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class AlarmRuleUpdateExe {
    private final AlarmRuleRepository alarmRuleRepository;
    private final AlarmRuleConfigPersistence alarmRuleConfigPersistence;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public void execute(AlarmRuleUpdateCmd cmd) {
        if (cmd.getId() == null) {
            throw new BizException("规则ID不能为空");
        }
        AlarmRuleDO alarmRuleDO = alarmRuleRepository.getById(cmd.getId());
        if (alarmRuleDO == null) {
            throw new BizException("告警配置不存在");
        }
        BeanUtils.copyProperties(cmd, alarmRuleDO, getNullPropertyNames(cmd));
        alarmRuleConfigPersistence.normalizeRule(alarmRuleDO);
        alarmRuleDO.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        alarmRuleDO.setSyncToken(FindsSyncToken.next());
        boolean res = alarmRuleRepository.updateById(alarmRuleDO);
        if (!res) {
            throw new BizException("修改失败");
        }
        if (cmd.getFenceRelList() != null || AlarmRuleConfigPersistence.ATTR_COMPANY_AREA.equals(alarmRuleDO.getAlarmAttr())) {
            alarmRuleConfigPersistence.rebuildFenceRelations(alarmRuleDO, cmd.getFenceRelList());
        }
        if (cmd.getRuleItemList() != null) {
            alarmRuleConfigPersistence.rebuildRuleItems(alarmRuleDO, cmd.getRuleItemList(), true);
        }
        findsPendingSyncService.scheduleRule(alarmRuleDO.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(Long id, boolean enabled) {
        AlarmRuleDO alarmRuleDO = alarmRuleRepository.getById(id);
        if (alarmRuleDO == null) {
            throw new BizException("告警配置不存在");
        }
        alarmRuleDO.setEnable(enabled ? 1 : 0);
        alarmRuleDO.setRuleStatus(enabled ? AlarmRuleConfigPersistence.STATUS_ENABLED : AlarmRuleConfigPersistence.STATUS_DISABLED);
        alarmRuleDO.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        alarmRuleDO.setSyncToken(FindsSyncToken.next());
        boolean res = alarmRuleRepository.updateById(alarmRuleDO);
        if (!res) {
            throw new BizException("状态修改失败");
        }
        alarmRuleConfigPersistence.syncRuleItemEnable(id, alarmRuleDO.getEnable());
        findsPendingSyncService.scheduleRule(alarmRuleDO.getId());
    }

    private String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        return emptyNames.toArray(new String[0]);
    }
}
