package com.yeejoin.amos.supervision.business.service.impl;

import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.supervision.business.dto.PlanRo;
import com.yeejoin.amos.supervision.business.feign.JCSFeignClient;
import com.yeejoin.amos.supervision.business.util.DateUtil;
import com.yeejoin.amos.supervision.dao.entity.Plan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.Date;
import java.util.List;

/**
 * @Author: xl
 * @Description: 防火监督触发规则
 * @Date: 2021/11/10 9:50
 */
@Service
public class RulePlanService {

    private final String packageId = "消息/addPlanRule";
    private final String msgType = "supervision";

    private final String APP = "APP";
    private final String WEB = "WEB";
    private final String APP_WEB = "APP/WEB";

    @Autowired
    private RuleTrigger ruleTrigger;

    @Autowired
    private JCSFeignClient jcsFeignClient;

    public Boolean addPlanRule(Plan plan, List<String> userIds, String ruleType) throws Exception {
        PlanRo planRo = buildPlanRo(plan, userIds, ruleType);
        //触发规则
        ruleTrigger.publish(planRo, packageId, new String[0]);
        return true;
    }

    public Boolean addPlanAuditRule(Plan plan, List<String> userIds, String ruleType, String excuteStateName) throws Exception {
        PlanRo planRo = buildPlanRo(plan, userIds, ruleType);
        planRo.setExcuteStateName(excuteStateName);

        //触发规则
        ruleTrigger.publish(planRo, packageId, new String[0]);
        return true;
    }

    private PlanRo buildPlanRo(Plan plan, List<String> userIds, String ruleType) {
        PlanRo planRo = new PlanRo();
        BeanUtils.copyProperties(plan, planRo);
        planRo.setMsgType(msgType);
        planRo.setRuleType(ruleType);
        planRo.setRelationId(String.valueOf(plan.getId()));

        if (ValidationUtil.isEmpty(userIds)) {
            String leadPeopleIds = plan.getLeadPeopleIds();
            if (!ValidationUtil.isEmpty(plan.getUserId()) && !leadPeopleIds.contains(plan.getUserId())) {
                leadPeopleIds += "," + plan.getUserId();
            }
            userIds = (List<String>) jcsFeignClient.getAmosIdListByUserIds(leadPeopleIds).getResult();
            planRo.setIsSendApp(true);
            planRo.setTerminal(WEB);
        } else {
            planRo.setIsSendWeb(true);
            planRo.setIsSendApp(false);
            planRo.setTerminal(APP_WEB);
        }
        planRo.setSendTime(DateUtil.date2LongStr(new Date()));
        planRo.setRecivers(userIds);
        return planRo;
    }
}
