package com.zcloud.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.zcloud.entity.PageData;
import com.zcloud.entity.TemplateData;
import com.zcloud.entity.WxMssVo;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.notice.NoticeCorpService;
import com.zcloud.service.notice.NoticeCorpUserService;
import com.zcloud.service.notice.NoticeManagementService;
import com.zcloud.service.notice.NoticeTemplateService;
import com.zcloud.service.sms.MSMLoginService;
import com.zcloud.service.sms.SMSManagementService;
import com.zcloud.service.system.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author fangjiakai
 * @date 2022/05/23 15:38
 */
@Component
public class SendMessageUtil {
    @Autowired
    private CorpInfoService corpinfoService;
    @Autowired
    private MSMLoginService msmloginService;
    @Autowired
    private SMSManagementService smsmanagementService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private NoticeTemplateService noticeTemplateService;
    @Autowired
    private NoticeCorpService noticeCorpService;
    @Autowired
    private NoticeCorpUserService noticeCorpUserService;
    @Autowired
    private NoticeManagementService noticemanagementService;

    /**
     * 短信发送
     *
     * @param pd         短信数据
     * @param paramsList 参数集合
     * @throws Exception
     */
    public void sendMessages(PageData pd, List<PageData> paramsList) throws Exception {
        sendNotice(pd, paramsList);
//        pushWxNotice(pd, paramsList);
//
//        Map<String,Object> map = new HashMap<String,Object>();
//        // 查询公司信息
//        PageData corpinfo = new PageData();
//        corpinfo.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
//        corpinfo =corpinfoService.findById(corpinfo);
//        // 查看公司剩余短信条数是否足以支持发送短信
//        Boolean canSend = checkCorpMsg(corpinfo);
//        // 发送抄送短信
//        PageData sms = new PageData();
//        sms.put("CORPINFO_ID",  pd.getString("CORPINFO_ID"));
//        sms.put("ISENABLE",  "1");
//        sms.put("SMSCODE", pd.get("templateCode"));
//        List<PageData> sList =smsmanagementService.listAll(sms);
//        if(canSend && sList.size()>0) {
//            // 发送短信
//            // 收信人
//            PageData user = new PageData();
//            user.put("USER_ID", pd.get("RECEIVER_ID"));
//            user = usersService.findById(user);
//            if(user.get("USERNAME") != null && Tools.notEmpty(user.get("USERNAME").toString())) {
//                String phone=user.get("USERNAME").toString();
//                // 发送短信
//                SendSmsResponse ssms= send(pd, phone, paramsList);
//                if(ssms.getCode().equals("OK")){
//                    map.put("result", "success");
//                }else{
//                    map.put("result", "fail");
//                    map.put("msg", "您的操作过去频繁，请稍后重试!");
//                    return map;
//                }
//            }
//        } else {
//            map.put("result", "fail");
//            map.put("msg", "公司剩余短信数量不足");
//            return map;
//        }
//
//        if(sList.size()>0 && sList.get(0).get("ADDRESSEE") != null && !sList.get(0).getString("ADDRESSEE").equals("")) {// 查看是否有需要抄送的人
//            String[] uid=sList.get(0).getString("ADDRESSEE").split(",");
//            for(int i=0;i<uid.length;i++) {
//                if(checkCorpMsg(corpinfo)) {// 查看公司剩余短信条数是否足以支持发送短信
//                    PageData suser = new PageData();
//                    suser.put("USER_ID", uid[i].toString());
//                    suser = usersService.findById(suser);
//                    if(suser.get("USERNAME") != null && Tools.notEmpty(suser.get("USERNAME").toString())) {
//                        String uphone=suser.get("USERNAME").toString();
//                        // 发送短信
//                        SendSmsResponse ssms= send(pd, uphone, paramsList);
//                        if(ssms.getCode().equals("OK")){
//                            map.put("result", "success");
//                        }else{
//                            map.put("result", "fail");
//                            map.put("msg", "您的操作过去频繁，请稍后重试!");
//                            return map;
//                        }
//                    }
//                } else {
//                    map.put("result", "fail");
//                    map.put("msg", "公司剩余短信数量不足抄送所有用户");
//                    return map;
//                }
//            }
//        }
//        return map;
    }

    /**
     * 重点工程相关方人员短信发送
     *
     * @param pd         短信数据
     * @param paramsList 参数集合
     * @throws Exception
     */
    public Object sendMessagesKeyproject(PageData pd, String phone, List<PageData> paramsList) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        // 查询公司信息
        PageData corpinfo = new PageData();
        corpinfo.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
        corpinfo = corpinfoService.findById(corpinfo);
        // 查看公司剩余短信条数是否足以支持发送短信
        Boolean canSend = checkCorpMsg(corpinfo);

        if (canSend) {
            // 发送短信
            SendSmsResponse ssms = send(pd, phone, paramsList);
            if (ssms.getCode().equals("OK")) {
                map.put("result", "success");
            } else {
                map.put("result", "fail");
                map.put("msg", "您的操作过去频繁，请稍后重试!");
                return map;
            }
        } else {
            map.put("result", "fail");
            map.put("msg", "公司剩余短信数量不足");
            return map;
        }

        return map;
    }

    /**
     * 查看公司剩余短信条数是否足以支持发送短信
     *
     * @return
     * @throws Exception
     */
    public boolean checkCorpMsg(PageData corpinfo) throws Exception {
        PageData lpd = new PageData();
        lpd.put("STATE", "OK");
        lpd.put("CORPINFO_ID", corpinfo.getString("CORPINFO_ID"));
        int usedCount = msmloginService.msUsedCount(lpd);
        if (corpinfo.getString("ISRECEIVE").equals("1") && Integer.parseInt(corpinfo.getString("SMS_COUNT")) - usedCount > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送短信
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public SendSmsResponse send(PageData pd, String phone, List<PageData> paramsList) throws Exception {
        Map<String, Object> mes = new HashMap<String, Object>();
        mes.put("phone", phone);
        mes.put("templateCode", pd.get("templateCode"));
        // 发送短信
        SendSmsResponse ssms = AliSmsToolUtil.sendSms(mes, paramsList);
        // 记录日志
        msmloginService.addForAliSmsToolUtil(mes, pd.getString("CORPINFO_ID"), ssms, paramsList);
        return ssms;
    }

    /**
     * 发送通知
     *
     * @param pd
     * @param paramsList
     * @return
     * @throws Exception
     */
    private void sendNotice(PageData pd, List<PageData> paramsList) throws Exception {
        PageData nm = new PageData();
        nm.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
        nm.put("ISENABLE", "1");
        nm.put("NOTICE_CODE", pd.get("templateCode"));
        List<PageData> nmList = noticemanagementService.listAll(nm);
        if (nmList == null || nmList.isEmpty()) {
            //未开启该提醒
            return;
        }
        PageData template = new PageData();
        template.put("TEMPLATE_CODE", pd.get("templateCode"));
        template = this.noticeTemplateService.findByCode(template);

        String content = template.getString("TEMPLATE_STR");
        if (paramsList != null && paramsList.size() > 0) {
            StringBuffer parStr = new StringBuffer();
            for (PageData par : paramsList) {
                content = content.replace(("${" + par.getString("name") + "}"), par.getString("value"));
            }
        }

        PageData pd1 = new PageData();
        pd1.put("NOTICECORP_ID", UuidUtil.get32UUID());
        pd1.put("USERNAME", "秦安双控");
        pd1.put("CREATOR", "秦安双控");    //添加人
        pd1.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
        pd1.put("SYNOPSIS", template.getString("NAME"));
        pd1.put("CONTENT", "<p>" + content + "</p>");
        pd1.put("ISALL", "yes");
        pd1.put("ISREPLY", 0);
        pd1.put("ISDELETE", 0);
        pd1.put("ISTOP", 0);
        pd1.put("STATUS", 1);
        pd1.put("CORP_INFO_ID", pd.getString("CORPINFO_ID"));
        noticeCorpService.save(pd1);
        pd1.put("NOTICECORPUSERID_ID", UuidUtil.get32UUID());
        pd1.put("USER_ID", pd.getString("RECEIVER_ID"));
        pd1.put("TYPE", 0);
        noticeCorpUserService.save(pd1);

//        Set<String> push_cids_set = new HashSet<String>();

        PageData user = new PageData();
        if ("".equals(pd.getString("RECEIVER_ID"))) {
            PageData userPd = new PageData();
            userPd.put("ISMAIN", "1");
            userPd.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
            List<PageData> mainUser = usersService.listAllUser(userPd);
            user.put("USER_ID", mainUser.get(0).getString("USER_ID"));
            pd.put("RECEIVER_ID", mainUser.get(0).getString("USER_ID"));
        } else {
            user.put("USER_ID", pd.get("RECEIVER_ID"));

        }
        user = usersService.findById(user);
//        if(user.get("PUSH_CID") != null){
//            push_cids_set.add(user.getString("PUSH_CID"));
//        }
        //查看是否有抄送
        if (nmList.size() > 0 && nmList.get(0).get("ADDRESSEE") != null && !nmList.get(0).getString("ADDRESSEE").equals("")) {// 查看是否有需要抄送的人
            String[] uid = nmList.get(0).getString("ADDRESSEE").split(",");
            for (int i = 0; i < uid.length; i++) {
                pd1.put("NOTICECORPUSERID_ID", UuidUtil.get32UUID());
                pd1.put("USER_ID", uid[i].toString());
                pd1.put("TYPE", 0);
                if (!pd.get("RECEIVER_ID").equals(pd1.get("USER_ID"))) {
                    noticeCorpUserService.save(pd1);
                    PageData user1 = new PageData();
                    user1.put("USER_ID", uid[i].toString());
                    user1 = usersService.findById(user1);
//                    if(user1.get("PUSH_CID") != null){
//                        push_cids_set.add(user1.getString("PUSH_CID"));
//                    }
                }
            }
        }
//        if(push_cids_set.size()>0){
//            PushUtil.push(push_cids_set.toArray(),"通知",pd1.getString("SYNOPSIS"));
//        }
    }

    /*
     * 微信推送新消息
     * */
    public void pushWxNotice(PageData pd, List<PageData> paramsList) throws Exception {

        PageData nm = new PageData();
        nm.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
        nm.put("ISENABLE", "1");
        nm.put("NOTICE_CODE", pd.get("templateCode"));
        List<PageData> nmList = noticemanagementService.listAll(nm);
        if (nmList == null || nmList.size() == 0) {//未开启该提醒
            return;
        }

        RestTemplate restTemplate = new RestTemplate();
        String APPID = "wx641d6a98d89ddd03";
        String SECRET = "22cd2198a03e5a1a70351f55b3d7687d";
        String access_token = getAccess_token(APPID, SECRET);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

        PageData template = new PageData();
        template.put("TEMPLATE_CODE", pd.get("templateCode"));
        template = this.noticeTemplateService.findByCode(template);

        PageData user = new PageData();
        user.put("USER_ID", pd.get("RECEIVER_ID"));
        user = usersService.findById(user);
        if (user.get("OPENID") == null || user.get("OPENID").equals("")) {//未绑定微信
            return;
        }
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(user.getString("OPENID"));//用户openid
//        wxMssVo.setTouser("o1v8O57wbhhU0ANGHSLExy1wH42o");//用户openid
//        wxMssVo.setUrl("https://www.qdkjchina.com/notice/notice.html?SCHOOLNOTICE_ID="+pd.getString("SCHOOLNOTICE_ID"));//跳转链接
//        wxMssVo.setTemplate_id(template_id);//模版id
        wxMssVo.setTemplate_id("5InweJzYRkmP9FhCE4V_X9m1_OgDGM141mLRio4AE6s");//模版id

        String content = template.getString("TEMPLATE_STR");
        if (paramsList != null && paramsList.size() > 0) {
            StringBuffer parStr = new StringBuffer();
            for (PageData par : paramsList) {
                content = content.replace(("${" + par.getString("name") + "}"), par.getString("value"));
            }
        }

        Map<String, TemplateData> m = new HashMap<String, TemplateData>();
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(template.getString("NAME"));
        m.put("first", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue(user.getString("NAME"));
        m.put("keyword1", keyword2);

        TemplateData keyword3 = new TemplateData();
        keyword3.setValue(DateUtil.date2Str(new Date()));
        m.put("keyword2", keyword3);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue(content);
        m.put("keyword3", keyword4);
        wxMssVo.setData(m);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        System.out.println("pushNotice:" + responseEntity.getBody());

        if (nmList.size() > 0 && nmList.get(0).get("ADDRESSEE") != null && !nmList.get(0).getString("ADDRESSEE").equals("")) {// 查看是否有需要抄送的人
            String[] uid = nmList.get(0).getString("ADDRESSEE").split(",");
            for (int i = 0; i < uid.length; i++) {
                PageData suser = new PageData();
                suser.put("USER_ID", uid[i].toString());
                suser = usersService.findById(suser);
                if (suser.get("OPENID") != null && suser.get("OPENID") != "") {
                    wxMssVo.setTouser(suser.get("OPENID").toString());//用户openid
                    restTemplate.postForEntity(url, wxMssVo, String.class);
                }
            }
        }
    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    private String getAccess_token(String appid, String appsecret) {
        //获取access_token
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        return jsonObject.get("access_token").toString();
    }
}
