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

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.yeejoin.amos.boot.biz.common.constants.RuleConstant;
import com.yeejoin.amos.boot.biz.common.enums.RuleTypeEnum;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.supervision.business.dao.mapper.PointMapper;
import com.yeejoin.amos.supervision.business.dto.OrgUsrFormDto;
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.business.util.Toke;
import com.yeejoin.amos.supervision.dao.entity.Plan;
import com.yeejoin.amos.supervision.dao.entity.Point;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.*;

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

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

    @Autowired
    private RuleTrigger ruleTrigger;

    @Autowired
    private JCSFeignClient jcsFeignClient;

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

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

    private PlanRo buildPlanRo(Plan plan, List<String> userIds, RuleTypeEnum ruleType, List<String> extraUserIds) {
        // 设置token
//        if (ValidationUtil.isEmpty(RequestContext.getToken())) {
//            Toke tokenObj = remoteSecurityService.getServerToken();
//            RequestContext.setProduct(tokenObj.getProduct());
//            RequestContext.setAppKey(tokenObj.getAppKey());
//            RequestContext.setToken(tokenObj.getToke());
//        }

        PlanRo planRo = new PlanRo();
        BeanUtils.copyProperties(plan, planRo);
        planRo.setMsgType(msgType);
        planRo.setRuleType(ruleType.getCode());
        planRo.setRelationId(String.valueOf(plan.getId()));
        planRo.setTerminal(ruleType.getTerminal());
        planRo.setCategory(ruleType.getCategory());
        Map<String, String> map = new HashMap<>();
        map.put("planId", String.valueOf(plan.getId()));

        if (!ValidationUtil.isEmpty(ruleType.getUrl())){
            map.put("url", ruleType.getUrl());
        }

        if (RuleConstant.WEB.equals(ruleType.getTerminal())){
            planRo.setIsSendWeb(true);
        } else if (RuleConstant.APP.equals(ruleType.getTerminal())){
            planRo.setIsSendApp(true);
        } else if (RuleConstant.APP_WEB.equals(ruleType.getTerminal())){
            planRo.setIsSendWeb(true);
            planRo.setIsSendApp(true);
        }

        //此处判断会导致给执行人和牵头人消息及任务都发送，产生Bug 先去除，如后续业务需要，在外层修改
//        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();
//        }
        if (!ValidationUtil.isEmpty(extraUserIds)) {
            List<String> finalUserIds = userIds;
            if (!ValidationUtil.isEmpty(finalUserIds)) {
                extraUserIds.forEach(id -> {
                    if (!finalUserIds.contains(id)) {
                        finalUserIds.add(id);
                    }
                });
        }
            if (!ValidationUtil.isEmpty(finalUserIds)){
                userIds = finalUserIds;
            }else {
                userIds = extraUserIds;
            }

        }
        planRo.setSendTime(DateUtil.date2LongStr(new Date()));
        planRo.setRecivers(userIds);
        planRo.setExtras(map);
        return planRo;
    }
}
