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

import com.google.common.collect.Sets;
import com.yeejoin.amos.boot.biz.common.constants.RuleConstant;
import com.yeejoin.amos.boot.module.common.api.dto.CompanyPerson;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
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.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.latentdanger.business.dto.LatentDangerRo;
import com.yeejoin.amos.latentdanger.business.feign.JcsFeignClient;
import com.yeejoin.amos.latentdanger.business.util.DateUtil;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerState;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDanger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xl
 * @Description: 隐患触发规则
 * @Date: 2021/11/12 14:55
 */
@Service
public class RuleDangerService {

    private final String packageId = "消息/addDangerRule";
    private final String msgType = "danger";

    @Autowired
    private RuleTrigger ruleTrigger;
    @Autowired
    private JcsFeignClient jcsFeignClient;

    public Boolean addLatentDangerRule(LatentDanger latentDanger, String ruleType, String roleName) throws Exception {
        LatentDangerRo latentDangerRo = buildLatentDangerRo(latentDanger, ruleType);
        latentDangerRo.setTerminal(RuleConstant.APP);
        List<RoleModel> result = Privilege.roleClient.queryRoleList(roleName, null).getResult();
        if (result.size() > 0) {
            List<AgencyUserModel> userModels = Privilege.agencyUserClient.queryByRoleId(String.valueOf(result.get(0).getSequenceNbr()), null).getResult();

            //只发送给本部门的人员
            Long pointId = latentDanger.getBizInfo().getLong("pointId");
            if (pointId == null || pointId == 0) {
                return false;
            }
            FeignClientResult<List<CompanyPerson>> companyPersons = jcsFeignClient.selectCompanyPerson(Collections.singletonList(pointId));
            if (companyPersons.getStatus() != 200) {
                return false;
            }
            //本部门的人员列表
            List<CompanyPerson> personList = companyPersons.getResult();
            List<OrgUsrDto> OrgUsrDtos = new ArrayList<>();
            personList.forEach(companyPerson -> OrgUsrDtos.addAll(companyPerson.getPersons()));
            //角色人员列表与本部门的人员列表取交集
            List<AgencyUserModel> userModelList = userModels.stream().filter(
                    agencyUserModel -> OrgUsrDtos.stream().anyMatch(
                            orgUsrDto -> agencyUserModel.getUserId().equals(orgUsrDto.getAmosOrgId())
                    )
            ).collect(Collectors.toList());
            List<String> userIds = userModelList.stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
            latentDangerRo.setRecivers(userIds);
        }
        //触发规则
        ruleTrigger.publish(latentDangerRo, packageId, new String[0]);
        return true;
    }

    public Boolean addDangerSubmitRule(LatentDanger latentDanger, List<String> userIds, String ruleType, String excuteStateName) throws Exception {
        LatentDangerRo latentDangerRo = buildLatentDangerRo(latentDanger, ruleType);
        Map<String, String> extras = !ValidationUtil.isEmpty(latentDangerRo.getExtras()) ? latentDangerRo.getExtras() : new HashMap<>();
        // 跳转url
        Map<String, String> enumMapByCode = LatentDangerState.SupervisionDangerStateEnum.getEnumMapByCode(latentDanger.getDangerState());
        extras.putAll(enumMapByCode);
        latentDangerRo.setExtras(extras);
        latentDangerRo.setExcuteStateName(excuteStateName);
        latentDangerRo.setIsSendWeb(true);
        latentDangerRo.setRecivers(userIds);
        latentDangerRo.setTerminal(RuleConstant.APP_WEB);
        if (ValidationUtil.isEmpty(userIds)) {
            return false;
        }
        //触发规则
        ruleTrigger.publish(latentDangerRo, packageId, new String[0]);
        return true;
    }

    private LatentDangerRo buildLatentDangerRo(LatentDanger latentDanger, String ruleType) {
        LatentDangerRo latentDangerRo = new LatentDangerRo();
        BeanUtils.copyProperties(latentDanger, latentDangerRo);
        latentDangerRo.setMsgType(msgType);
        latentDangerRo.setIsSendApp(true);
        latentDangerRo.setRuleType(ruleType);
        latentDangerRo.setCategory(RuleConstant.TASK);
        latentDangerRo.setRelationId(String.valueOf(latentDanger.getId()));
        latentDangerRo.setSendTime(DateUtil.date2LongStr(new Date()));

        String type = null;
        latentDanger.getDangerState();
        LatentDangerState.SupervisionDangerStateEnum stateEnum =
                LatentDangerState.SupervisionDangerStateEnum.getEnumByCode(latentDanger.getDangerState());
        if (!ValidationUtil.isEmpty(stateEnum)) {
            if (stateEnum.getProcessState().equals("0") || stateEnum.getProcessState().equals("1")) {
                type = "1";
            } else if (stateEnum.getProcessState().equals("4")) {
                type = "2";
            }
        }

        if (!ValidationUtil.isEmpty(type)) {
            Map<String, String> map = new HashMap<>();
            map.put("type", type);
            map.put("id", String.valueOf(latentDanger.getId()));
            latentDangerRo.setExtras(map);
        }
        return latentDangerRo;
    }
}
