package com.ruoyi.system.domain.task.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.zqt.ZQTHttpHelper;
import com.ruoyi.system.domain.md.dto.JbReceiver;
import com.ruoyi.system.domain.md.dto.JbWorkBean;
import com.ruoyi.system.domain.md.request.NewMsgSendData;
import com.ruoyi.system.domain.md.request.NewMsgSendRequest;
import com.ruoyi.system.domain.md.request.NewMsgUser;
import com.ruoyi.system.domain.task.TkCommonTask;
import com.ruoyi.system.domain.task.TkRoundTask;
import com.ruoyi.system.service.md.JbTodoService;
import com.ruoyi.system.service.md.NewMsgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.*;

@Component
public class WorkMSGUtils {
    @Value("${app.msg.pcUrl}")
    private String gridPcUrl;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;
    @Value("${app.sms.url}")
    private String dxsmsurl;
    @Value("${app.sms.spid}")
    private String spid;
    @Value("${app.sms.authCode}")
    private String authCode;
    @Value("${app.sms.authKey}")
    private String authKey;
    @Resource
    private JbTodoService todoService;
    @Resource
    private NewMsgService newMsgService;

    /**
     * @Date 2019/4/28 14:10
     * @Author GuoWei
     * @Description: 创建巡查任务待办
     */
    public String createRoundWork(TkRoundTask tkRoundTask,
                                  String createdby,
                                  List<String> beassignedUserIds,
                                  String name) {
        JbWorkBean daiBan = new JbWorkBean();
        daiBan.setName(name);//待办标题
        daiBan.setLevel(1);// 级别
        daiBan.setCreatedby(createdby);//发送人用户ID
        daiBan.setAppname("ZQT_WS_GRID_MANAGE");//在卓易云平台创建应用的英文名称"
        List<JbReceiver> jbReceiver = new ArrayList<JbReceiver>();
        if (!beassignedUserIds.isEmpty()) {
            for (String beassignedUserId : beassignedUserIds) {
                JbReceiver r = new JbReceiver();
                r.setUid(beassignedUserId);//接收人用户ID
                jbReceiver.add(r);
            }
        }
        String mobileUrl = "#/roundtask/detail/";
        String pcUrl = gridPcUrl + "/task/roundtask/" + tkRoundTask.getOrigin() + "/";
        pcUrl = pcUrl + tkRoundTask.getId();
        mobileUrl = mobileUrl + tkRoundTask.getId();
        daiBan.setReceiver(jbReceiver);
        daiBan.setContent(tkRoundTask.getName() + "_");//待办内容"
        daiBan.setUrl(mobileUrl);
        daiBan.setPcurl(pcUrl);
        Integer res = todoService.save(daiBan);
        return String.valueOf(res);
    }

    /**
     * 创建任务待办
     */
    public String createWork(TkCommonTask tkCommonTask, String AssignedUserId, List<String> beassignedUserIds, String name) {
        JbWorkBean daiBan = new JbWorkBean();
        daiBan.setName(name);//待办标题
        daiBan.setLevel(1);// 级别
        daiBan.setCreatedby(AssignedUserId);//发送人用户ID
        List<JbReceiver> jbReceiver = new ArrayList<JbReceiver>();
        if (!beassignedUserIds.isEmpty()) {
            for (String beassignedUserId : beassignedUserIds) {
                JbReceiver r = new JbReceiver();
                r.setUid(beassignedUserId);//接收人用户ID
                jbReceiver.add(r);
            }
        } else {
            JSONObject res = new JSONObject();
            res.put("msg", "fail");
            return res.toJSONString();
        }
        String pcUrl = this.getPCUrl(tkCommonTask.getMatterType(), tkCommonTask.getId());
        String mobileUrl = this.getMobileUrl(tkCommonTask.getId());
        daiBan.setReceiver(jbReceiver);
        daiBan.setContent(tkCommonTask.getTkName() + "_");//待办内容"
        daiBan.setUrl(mobileUrl);
        daiBan.setPcurl(pcUrl);
        Integer workId = todoService.save(daiBan);
        JSONObject res = new JSONObject();
        res.put("msg", "success");
        JSONObject data = new JSONObject();
        data.put("workId", workId);
        res.put("data", data);
        return res.toJSONString();
    }

    private String getMobileUrl(String tkId) {
        return gridAppUrl + "/commontask/detail?id=" + tkId;
    }


    private String getPCUrl(Integer matterType, String tkId) {
        return gridPcUrl + "/order/grid?id=" + tkId;
    }


    /**
     * 修改工作状态
     */
    public void updateWork(String uid, String workId, int review) {
        todoService.workUserStatus(review, Integer.parseInt(workId), 0, uid);
    }


    /**
     * 任务指派 通知
     *
     * @param AssignedUserId   指派人id
     * @param AssignedUserName 指派人姓名
     * @param userIds          接收人ids
     */
    public void sendMsg(String AssignedUserId, String AssignedUserName, List<String> userIds, String body, Integer matterType, String tkId) {
        NewMsgSendRequest m = new NewMsgSendRequest();
        NewMsgSendData s = new NewMsgSendData();
        MsgParams p = new MsgParams();
        NewMsgUser f = new NewMsgUser();
        s.setTitle(body);
        s.setBody(body);
        s.setMsgtype((byte) 0);//政企消息 写死
        s.setNeedpush((byte) 1);
        p.setSender(AssignedUserName);//发件人名称描述（只用于展示）
        p.setMsgcategory("通知公告");
        p.setMsglevel("普通");
        p.setNeedreply("0");
        p.setRedirect_pc(this.getPCUrl(matterType, tkId));//pc跳转
        p.setRedirect_app(this.getMobileUrl(tkId));//app跳转
        s.setParams(JSONObject.from(p));
        m.setSendData(s);
        f.setUserid(AssignedUserId);
        m.setFrom(f);
        List<NewMsgUser> list = new ArrayList<>();
        if (!userIds.isEmpty()) {
            for (String userId : userIds) {
                NewMsgUser t = new NewMsgUser();
                t.setUserid(userId);//接收人用户ID
                list.add(t);
            }
        }
        m.setTo(list);
        newMsgService.send(m);
    }

    /**
     * 电信发送短信
     */
    public void sendDXSMS(SysUser userInfo, Map<String, Object> map) {
        String receiver = StringUtils.isBlank(userInfo.getPhonenumber()) ? userInfo.getUserName() : userInfo.getPhonenumber();
        if (StringUtils.isBlank(receiver)) {
            return;
        }
        String content = "【万事通】" + map.get("name") + "您好,您所在的" + map.get("address") + "有一条新任务：" + map.get("taskName") + "，待" + map.get("type") + "，如任务指派错误或其他问题，请联系万事通指挥中心";
        this.send(content,receiver);
    }

    public void sendSms(SysUser userInfo,Map<String,String> map){
        String receiver = StringUtils.isBlank(userInfo.getPhonenumber()) ? userInfo.getUserName() : userInfo.getPhonenumber();
        if (StringUtils.isBlank(receiver)) {
            return;
        }
        String content = "【万事通】" + map.get("name") + "（签批人）您好,您所在的" + map.get("address") + "有一条新任务：" + map.get("taskName") + "，待签批，如任务指派错误或其他问题，请联系万事通指挥中心";
        this.send(content,receiver);
    }

    private void send(String content,String receiver){
        try {
            String url = dxsmsurl + "/SMSController/sendSms.do";
            content = URLEncoder.encode(content, "utf-8");
            String smsid = UUID.randomUUID().toString();
            long timeMillis = System.currentTimeMillis();
            String sign = SHA1.encode(authCode + spid + "" + smsid + receiver + "" + content + timeMillis + authKey);
            JSONObject jo = new JSONObject();
            jo.put("auth_code", authCode);
            jo.put("smsid", smsid);
            jo.put("spid", spid);
            jo.put("mobiles", receiver);//目标手机号列表  用英文,隔开；
            jo.put("content", content);
            jo.put("sendtime", "");
            jo.put("timestamp", timeMillis);
            jo.put("sign", sign);
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            String ret = ZQTHttpHelper.doPostJson(url, jo.toString(), headParams);
            System.out.println("短信返回--------------" + ret);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 电信发送短信-通用
     */
    public void sendDXSMSCurrency(SysUser userInfo, String content) {
        try {
            String receiver = StringUtils.isBlank(userInfo.getPhonenumber()) ? userInfo.getUserName() : userInfo.getPhonenumber();
            if (StringUtils.isBlank(receiver)) {
                return;
            }
            String url = dxsmsurl + "/SMSController/sendSms.do";
            content = URLEncoder.encode(content, "utf-8");
            String smsid = UUID.randomUUID().toString();
            long timeMillis = System.currentTimeMillis();
            String sign = SHA1.encode(authCode + spid + "" + smsid + receiver + "" + content + timeMillis + authKey);
            JSONObject jo = new JSONObject();
            jo.put("auth_code", authCode);
            jo.put("smsid", smsid);
            jo.put("spid", spid);
            jo.put("mobiles", receiver);//目标手机号列表  用英文,隔开；
            jo.put("content", content);
            jo.put("sendtime", "");
            jo.put("timestamp", timeMillis);
            jo.put("sign", sign);
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            String ret = ZQTHttpHelper.doPostJson(url, jo.toString(), headParams);
            System.out.println("短信返回--------------" + ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //调用电信短信接口--判定
    public void sendPanDingDXSMS(SysUser userInfo, Map<String, Object> map) {
        try {
            String receiver = StringUtils.isBlank(userInfo.getPhonenumber()) ? userInfo.getUserName() : userInfo.getPhonenumber();
            if (StringUtils.isBlank(receiver)) {
                return;
            }
            String url = dxsmsurl + "/SMSController/sendSms.do";
            String content = "【万事通】" + map.get("name") + "您好,您所在的" + map.get("address") + "有一条任务：标题为'" + map.get("taskName") + "'判定无效，请重新上传，如有问题，请联系万事通指挥中心";
            content = URLEncoder.encode(content, "utf-8");
            String smsid = UUID.randomUUID().toString();
            long timeMillis = System.currentTimeMillis();
            String sign = SHA1.encode(authCode + spid + "" + smsid + receiver + "" + content + timeMillis + authKey);
            JSONObject jo = new JSONObject();
            jo.put("auth_code", authCode);
            jo.put("smsid", smsid);
            jo.put("spid", spid);
            jo.put("mobiles", receiver);//目标手机号列表  用英文,隔开；
            jo.put("content", content);
            jo.put("sendtime", "");
            jo.put("timestamp", timeMillis);
            jo.put("sign", sign);
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            String ret = ZQTHttpHelper.doPostJson(url, jo.toString(), headParams);
            System.out.println("短信返回--------------" + ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
