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.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.Toke;
import com.yeejoin.amos.latentdanger.common.enums.MsgSubscribeEnum;
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 java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 异步执行任务
 *
 * @author Administrator
 */
@Component(value = "asyncTask")
public class AsyncTask {
    private static final String TAB = "\r\n";
    private final Logger log = LoggerFactory.getLogger(AsyncTask.class);
//    @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;
        }
        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);
        }
    }
}
