package com.yeejoin.amos.latentdanger.core.async;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.MessageModel;
import com.yeejoin.amos.latentdanger.business.param.JPushTypeEnum;
import com.yeejoin.amos.latentdanger.business.param.PushMsgParam;
import com.yeejoin.amos.latentdanger.business.util.DateUtil;
import com.yeejoin.amos.latentdanger.business.util.Toke;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerState;
import com.yeejoin.amos.latentdanger.common.enums.MsgSubscribeEnum;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDanger;
import com.yeejoin.amos.latentdanger.dao.entity.Msg;
import com.yeejoin.amos.latentdanger.feign.RemoteSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.context.RequestContextModel;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 异步执行任务
 *
 * @author Administrator
 */
@Component(value = "asyncTask")
public class AsyncTask {
    private static final String TAB = "\r\n";
    private final Logger log = LoggerFactory.getLogger(AsyncTask.class);
    private final String msgType = "danger";
//    @Autowired
//    private IMsgDao iMsgDao;
//    @Autowired
//    private IMessageService messageService;
    @Autowired
    private RemoteSecurityService remoteSecurityService;

    /**
     * 隐患待治理到期提醒
     */
    @Async("asyncTaskExecutor")
    public void pushLatentDangerReformLimitDateExpireMessage(String informerList, String orgCode,
                                                             String latentDangerName, String reformLimitDate,
                                                             Long latentDangerId, Integer state,
                                                             String userRealName) {
        MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.隐患治理推送;
        String body = "";
        body += "隐患治理提醒：您好，隐患治理即将到期，请及时处理！" + TAB;
        body += "隐患名称：" + latentDangerName + TAB;
        body += "治理日期：" + reformLimitDate;
        saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), latentDangerId, state, userRealName);
    }

    /**
     * 隐患治理
     */
    @Async("asyncTaskExecutor")
    public void pushLatentDangerExecuteMessage(String informerList, String orgCode,
                                               String latentDangerName, String pointName,
                                               String exeDeptName, Long latentDangerId,
                                               String exeUserRealName, String flowName,
                                               String flowResult, String executeDate,
                                               Integer state) {
        MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.隐患治理推送;
        String body = "";
        body += executeDate + TAB;
        body += exeDeptName + " " + exeUserRealName + " " + flowName + "：" + flowResult + TAB;
        body += "隐患名称：" + latentDangerName + TAB;
        if (pointName != null) {
            body += "关联检查点：" + pointName + TAB;
        }
        body = body.replaceAll(null, "").replaceAll("null", "");
        saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), latentDangerId, state, "");
    }

    /**
     * 隐患验证通过
     */
    @Async("asyncTaskExecutor")
    public void pushRiskWarnMessage(String informerList, String orgCode,
                                    String latentDangerName, Long riskFactorId,
                                    String riskFactorName, String pointName,
                                    String executeDate) {
        MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.风险评价提醒推送;
        String body = "";
        body += latentDangerName + "管控措施失效，隐患治理验证完毕,需重新进行风险评价！" + TAB;
        body += "关联危险源：" + pointName + TAB;
        body += "关联危险因素：" + riskFactorName + TAB;
        body += "执行时间：" + executeDate + TAB;
        if (pointName != null) {
            body += "关联检查点：" + pointName + TAB;
        }
        MessageModel messageModel = new MessageModel();
        messageModel.setBody(body);
//        Systemctl.messageClient.create(messageModel);
//        saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), riskFactorId, null, "");
    }

    private void saveAndSendMsg(String orgCode, String informerList,
                                String title, String body, String msgType,
                                Long relationId, Integer state,
                                String userRealName) {
        JSONArray array = JSONArray.parseArray(informerList);
        Set<String> sendUserIds = new HashSet<>();
        if (array.size() > 0) {
            Date date = new Date();
            List<Msg> msgs = Lists.newArrayList();
            for (int i = 0; i < array.size(); i++) {
                JSONObject user = array.getJSONObject(i);
                Msg msg = new Msg();
                msg.setOrgCode(orgCode);
                msg.setUserId(user.getString("userId"));
                msg.setTitle(title);
                msg.setBody(body);
                msg.setMsgType(msgType);
                msg.setRelationId(relationId);
                msg.setIsImmediately(true);
                msg.setSendTime(date);
                msg.setCreateDate(date);
                msg.setTargetTel(user.getString("username"));
                msg.setReciverName(user.getString("realName"));
                sendUserIds.add(user.getString("userId"));
                msgs.add(msg);
            }


            Map<String, String> extras = Maps.newHashMap();
            extras.put("type", msgType);
            extras.put("id", String.valueOf(relationId));
            if (state != null) {
                extras.put("state", String.valueOf(state));
            }
            PushMsgParam pushMsgParam = new PushMsgParam();
            pushMsgParam.setContent(body);
            pushMsgParam.setRecivers(Lists.newArrayList(sendUserIds));
            pushMsgParam.setSubject(title);
            pushMsgParam.setRelationId(String.valueOf(relationId));
            pushMsgParam.setType(JPushTypeEnum.ALIAS.getCode());
            pushMsgParam.setExtras(extras);
//            iMsgDao.saveAll(msgs);
            Toke toke = remoteSecurityService.getServerToken();
//            messageService.pushMsg(toke.getToke(), toke.getProduct(), toke.getAppKey(), pushMsgParam);
        }
    }

    /**
     * 提交隐患发送消息至检查组员被检查单位确认隐患
     */
    @Async
    public void sendDangerMsg(RequestContextModel requestContextModel, LatentDanger latentDanger, String roleName){
        RequestContext.setToken(requestContextModel.getToken());
        RequestContext.setProduct(requestContextModel.getProduct());
        RequestContext.setAppKey(requestContextModel.getAppKey());
        MessageModel model = new MessageModel();
        String body = String.format("隐患名称：%s；隐患级别：%s；治理方式：%s；当前状态：%s；推送时间：%s",
                latentDanger.getDangerName(), latentDanger.getDangerLevelName(), latentDanger.getReformTypeName(), latentDanger.getDangerStateName(), DateUtil.date2LongStr(new Date()));
        model.setBody(body);
        getMessageModel(model, latentDanger);
        try {
            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();
                List<String> userIds = userModels.stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
                model.setRecivers(userIds);
            }
            Systemctl.messageClient.create(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认隐患发送消息
     */
    @Async
    public void sendDangerSubmitMsg(RequestContextModel requestContextModel, LatentDanger latentDanger, List<String> userIds, String executeName){
        RequestContext.setToken(requestContextModel.getToken());
        RequestContext.setProduct(requestContextModel.getProduct());
        RequestContext.setAppKey(requestContextModel.getAppKey());
        MessageModel model = new MessageModel();
        String body = String.format("隐患名称：%s；隐患级别：%s；治理方式：%s；当前状态：%s；审核结果：%s；推送时间：%s",
                latentDanger.getDangerName(), latentDanger.getDangerLevelName(), latentDanger.getReformTypeName(), latentDanger.getDangerStateName(), executeName, DateUtil.date2LongStr(new Date()));
        model.setBody(body);
        model.setIsSendWeb(true);
        model.setRecivers(userIds);
        getMessageModel(model, latentDanger);
        try {
            Systemctl.messageClient.create(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private MessageModel getMessageModel(MessageModel model, LatentDanger latentDanger) {
        String type = null;
        latentDanger.getDangerState();
        LatentDangerState.SupervisionDangerStateEnum stateEnum =
                LatentDangerState.SupervisionDangerStateEnum.getEnumByCode(latentDanger.getDangerState());
        if (!ValidationUtil.isEmpty(stateEnum)) {
            if (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);
            model.setExtras(map);
        }
        model.setTitle(latentDanger.getDangerName());
        model.setIsSendApp(true);
        model.setMsgType(msgType);
        model.setRelationId(String.valueOf(latentDanger.getId()));
        return model;
    }
}
