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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Value("${supervision.person.charger.role:Person_charge_unit_fire_protection_supervision_inspection}")
    private String supervisionPersonChargerRole;

    @Autowired
    private RuleTrigger ruleTrigger;

    @Autowired
    private JCSFeignClient jcsFeignClient;

    @Autowired
    private RemoteSecurityService remoteSecurityService;

    @Autowired
    private PointServiceImpl pointService;

    public Boolean addPlanRule(Plan plan, List<String> userIds, RuleTypeEnum ruleType, Long pointId) throws Exception {
        PlanRo planRo = buildPlanRo(plan, userIds, ruleType, pointId);
        //触发规则
        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, Long pointId) {
        // 设置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);
        }

        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();
            // pointId是被检查单位id
            if (!ValidationUtil.isEmpty(pointId)) {
                Point point = pointService.queryPointById(pointId);
                List<OrgUsrFormDto> personList  =
                        jcsFeignClient.getPersonListByCompanyId(point.getOriginalId()).getResult();
                List<String> personIdList = Lists.transform(personList, OrgUsrFormDto::getAmosOrgId);
                List<RoleModel> roleList =
                        Privilege.roleClient.queryRoleList(supervisionPersonChargerRole, null).getResult();
                if (!ValidationUtil.isEmpty(roleList)) {
                    List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient.queryByRoleId(
                            String.valueOf(roleList.get(0).getSequenceNbr()), null).getResult();
                    if (!ValidationUtil.isEmpty(agencyUserModelList)) {
                        List<String> finalUserIds = userIds;
                        agencyUserModelList.forEach(userModel -> {
                            if (personIdList.contains(userModel.getUserId()) && !finalUserIds.contains(userModel.getUserId())) {
                                finalUserIds.add(userModel.getUserId());
                            }
                        });
                        userIds = finalUserIds;
                    }
                }
            }
        }
        planRo.setSendTime(DateUtil.date2LongStr(new Date()));
        planRo.setRecivers(userIds);
        planRo.setExtras(map);
        return planRo;
    }
}
