package com.yihu.jw.wechat.enterprise;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.hospital.enterprise.WxEnterpriseDO;
import com.yihu.jw.entity.hospital.enterprise.WxEnterpriseTokenDO;
import com.yihu.jw.entity.hospital.enterprise.WxEnterpriseUserDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.wechat.enterprise.dao.WxEnterpriseDao;
import com.yihu.jw.wechat.enterprise.dao.WxEnterpriseTokenDao;
import com.yihu.jw.wechat.enterprise.dao.WxEnterpriseUserDao;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Trick on 2020/2/8.
 */
@Service
@Transactional
public class EnterpriseService {

    private Logger logger = LoggerFactory.getLogger(EnterpriseService.class);


    private String corpsecret = "SKuRnq7cZqE5ax1YxwBwkCa-jdujkzbpMjWDCYU2raE";

    private String corpid = "wwd7335a5d80a9b14f";

    private String agentId = "1000003";

    @Autowired
    private WxEnterpriseTokenDao wxEnterpriseTokenDao;
    @Autowired
    private WxEnterpriseUserDao wxEnterpriseUserDao;
    @Autowired
    private WxEnterpriseDao wxEnterpriseDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private WlyyHttpLogDao wlyyHttpLogDao;


    public String getToken(String enterpriseId)throws Exception{

        logger.info("getToken");

        WxEnterpriseDO wxEnterpriseDO = wxEnterpriseDao.findOne(enterpriseId);

        List<WxEnterpriseTokenDO> wxEnterpriseTokenDOs = wxEnterpriseTokenDao.findByCodeOrderByCreateTimeDesc(wxEnterpriseDO.getCorpid());

        if(wxEnterpriseTokenDOs!=null&&wxEnterpriseTokenDOs.size()>0) {
            logger.info("token size:"+wxEnterpriseTokenDOs.size());
            WxEnterpriseTokenDO tokenDO = wxEnterpriseTokenDOs.get(0);
            if (tokenDO.getExpiresTime().after(new Date())) {
                return tokenDO.getAccessToken();
            }else{
                wxEnterpriseTokenDao.delete(wxEnterpriseTokenDOs);
            }
        }

        String result = HttpUtil.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+wxEnterpriseDO.getCorpid()+"&corpsecret="+wxEnterpriseDO.getCorpsecret());

        logger.info("getToken result:"+result);

        JSONObject json = JSONObject.parseObject(result);

        //保存当前token
        WxEnterpriseTokenDO token = new WxEnterpriseTokenDO();
        Date date = new Date();
        token.setAccessToken(json.getString("access_token"));
        token.setCreateTime(date);
        token.setExpiresTime(DateUtil.setDateHours(date,2));
        token.setCode(wxEnterpriseDO.getCorpid());
        wxEnterpriseTokenDao.save(token);

        return token.getAccessToken();
    }

    public String getXCXToken(String enterpriseId)throws Exception{

        logger.info("getXCXToken");

        WxEnterpriseDO wxEnterpriseDO = wxEnterpriseDao.findOne(enterpriseId+"_xcx");

        List<WxEnterpriseTokenDO> wxEnterpriseTokenDOs = wxEnterpriseTokenDao.findByCodeOrderByCreateTimeDesc(enterpriseId+"_xcx");

        if(wxEnterpriseTokenDOs!=null&&wxEnterpriseTokenDOs.size()>0) {
            logger.info("token size:"+wxEnterpriseTokenDOs.size());
            WxEnterpriseTokenDO tokenDO = wxEnterpriseTokenDOs.get(0);
            if (tokenDO.getExpiresTime().after(new Date())) {
                return tokenDO.getAccessToken();
            }else{
                wxEnterpriseTokenDao.delete(wxEnterpriseTokenDOs);
            }
        }

        String result = HttpUtil.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+wxEnterpriseDO.getCorpid()+"&corpsecret="+wxEnterpriseDO.getCorpsecret());

        logger.info("getToken result:"+result);

        JSONObject json = JSONObject.parseObject(result);

        //保存当前token
        WxEnterpriseTokenDO token = new WxEnterpriseTokenDO();
        Date date = new Date();
        token.setAccessToken(json.getString("access_token"));
        token.setCreateTime(date);
        token.setExpiresTime(DateUtil.setDateHours(date,2));
        token.setCode(enterpriseId+"_xcx");
        wxEnterpriseTokenDao.save(token);

        return token.getAccessToken();
    }

    public String sendTextMes(String enterpriseId,String userId,String content)throws Exception{

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+getToken(enterpriseId);

        JSONObject param = new JSONObject();
        param.put("touser",userId);
        param.put("toparty","");
        param.put("totag","");
        param.put("msgtype","text");

        WxEnterpriseDO wxEnterpriseDO = wxEnterpriseDao.findOne(enterpriseId);

        param.put("agentid",wxEnterpriseDO.getAgentid());

        JSONObject text = new JSONObject();
        text.put("content",content);
        param.put("text",text);
        param.put("safe",0);
        param.put("enable_id_trans",0);
        param.put("enable_duplicate_check",0);

        String rs = HttpUtil.sendPost(url,param.toJSONString());

        logger.info("Mes:"+rs);

        return rs;
    }

    public String sendMKMesByDoctor(String enterpriseId,String doctor,String content)throws Exception {
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        String res="";
        if (baseDoctorDO != null && StringUtils.isNotBlank(baseDoctorDO.getMobile())) {
            WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId, baseDoctorDO.getMobile());
            if (user != null) {
                WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
                wlyyHttpLogDO.setDoctor(doctor);
                wlyyHttpLogDO.setRequest(content);
                wlyyHttpLogDO.setName("im消息推送");
                wlyyHttpLogDO.setCode(enterpriseId);
                wlyyHttpLogDO.setCreateTime(new Date());
                wlyyHttpLogDO.setRequest("enterpriseId:"+enterpriseId+",doctor:"+doctor+",url:"+content);
                res=sendTextMes(enterpriseId, user.getUserid(), content);
                wlyyHttpLogDO.setResponse(res);
                logger.info(res);
                wlyyHttpLogDao.save(wlyyHttpLogDO);
                return res;
            }
        }
        return "";
    }

    public String  sendMKMesByMobile(String enterpriseId,String mobile,String content)throws Exception{

        WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId,mobile);
        if(user!=null){
            return sendTextMes(enterpriseId,user.getUserid(),content);
        }
        return "";
    }
    public String sendTWMesByDoctor(String enterpriseId,String doctor,String title,String description,String url)throws Exception{

        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        String res = "";
        if(baseDoctorDO!=null&&StringUtils.isNotBlank(baseDoctorDO.getMobile())){
            WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId,baseDoctorDO.getMobile());
            if(user!=null){
                res =sendTWMes(enterpriseId,user.getUserid(),title,description,url);
                logger.info("开始保存日志");
                logger.info("url==="+url);
                try {
                    if (StringUtils.isNoneBlank(url)){
                        logger.info("进入保存接口");
                        String outPatientId = url.substring(url.lastIndexOf("=")+1,url.length());
                        WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
                        wlyyHttpLogDO.setDoctor(doctor);
                        wlyyHttpLogDO.setRequest(url);
                        wlyyHttpLogDO.setName(title);
                        wlyyHttpLogDO.setCode(outPatientId);
                        wlyyHttpLogDO.setCreateTime(new Date());
                        wlyyHttpLogDO.setRequest("enterpriseId:"+enterpriseId+",doctor:"+doctor+",url:"+url);
                            wlyyHttpLogDO.setResponse(res);
                        logger.info(res);
                        wlyyHttpLogDao.save(wlyyHttpLogDO);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return res;
            }
        }
        return "";
    }

    public String sendTWMesBymobile(String enterpriseId,String mobile,String title,String description,String url)throws Exception{
        WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId,mobile);
        if(user!=null){
            return sendTWMes(enterpriseId,user.getUserid(),title,description,url);
        }
        return "";
    }
    
    /**
     *
     * @param enterpriseId
     * @param doctor
     * @param appid
     * @param page
     * @param title
     * @param description （不能超过12个字符）
     * @param emphasis_first_item
     * @param content_item
     * @return
     * @throws Exception
     */
    public String sendXCXMesByDoctor(String enterpriseId, String doctor, String appid,String page, String title, String description, Boolean emphasis_first_item, String content_item)throws Exception {
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);

        if (baseDoctorDO != null && StringUtils.isNotBlank(baseDoctorDO.getMobile())) {
            WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId, baseDoctorDO.getMobile());
            if (user != null) {
                return sendXCXMes(enterpriseId,user.getUserid(),appid,page,title,description,emphasis_first_item,content_item);
            }
        }
        return "";
    }

    public String sendXCXMesByMobile(String enterpriseId, String mobile, String appid,String page, String title, String description, Boolean emphasis_first_item, String content_item)throws Exception{

        WxEnterpriseUserDO user = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId,mobile);
        if(user!=null){
            return sendXCXMes(enterpriseId,user.getUserid(),appid,page,title,description,emphasis_first_item,content_item);
        }
        return "";
    }


    public String sendTWMes(String enterpriseId,String userId,String title,String description,String url)throws Exception{

        String mesurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+getToken(enterpriseId);

        JSONObject param = new JSONObject();
        param.put("touser",userId);
        param.put("toparty","");
        param.put("totag","");
        param.put("msgtype","news");
        WxEnterpriseDO wxEnterpriseDO = wxEnterpriseDao.findOne(enterpriseId);

        param.put("agentid",wxEnterpriseDO.getAgentid());

        JSONObject news = new JSONObject();

        JSONArray articles = new JSONArray();
        JSONObject article = new JSONObject();

        article.put("title",title);
        article.put("description",description);
        article.put("url",url);
        article.put("picurl","");
        articles.add(article);

        news.put("articles",articles);

        param.put("news",news);
        param.put("enable_id_trans",0);
        param.put("enable_duplicate_check",0);

        logger.info("TWparam:"+param.toJSONString());

        String rs = HttpUtil.sendPost(mesurl,param.toJSONString());

        logger.info("TWMes:"+rs);

        return rs;
    }

    public String getDeptsId(String enterpriseId)throws Exception{

        logger.info("getDeptsId");

        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="+getToken(enterpriseId);

        String rs = HttpUtil.sendGet(url);

        logger.info("dept rs:"+rs);

        JSONObject r = JSONObject.parseObject(rs);

        JSONArray depts = r.getJSONArray("department");

        String deptStr ="";

        if(depts!=null&&depts.size()>0){
            for(int i=0;i<depts.size();i++){
                JSONObject dept = (JSONObject) depts.get(i);
                deptStr+=dept.getString("id")+",";
            }
            deptStr = deptStr.substring(0,deptStr.length()-1);
        }
        logger.info("deptStr"+deptStr);

        return deptStr;
    }

    public String sendMKMes(String enterpriseId,String userId,String content)throws Exception{

        String mesurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+getToken(enterpriseId);

        JSONObject param = new JSONObject();
        param.put("touser",userId);
        param.put("toparty","");
        param.put("totag","");
        param.put("msgtype","markdown");
        WxEnterpriseDO wxEnterpriseDO = wxEnterpriseDao.findOne(enterpriseId);

        param.put("agentid",wxEnterpriseDO.getAgentid());

        JSONObject markdown = new JSONObject();

        markdown.put("content",content);

        param.put("markdown",markdown);
        param.put("enable_duplicate_check",0);

        logger.info("MKparam:"+param.toJSONString());

        String rs = HttpUtil.sendPost(mesurl,param.toJSONString());

        logger.info("MKMes:"+rs);
        WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
        wlyyHttpLogDO.setDoctor(userId);
        wlyyHttpLogDO.setRequest(content);
        wlyyHttpLogDO.setName("im消息推送");
        wlyyHttpLogDO.setCode(enterpriseId);
        wlyyHttpLogDO.setCreateTime(new Date());
        wlyyHttpLogDO.setRequest("enterpriseId:"+enterpriseId+",doctor:"+userId+",url:"+content);
        wlyyHttpLogDO.setResponse(rs);
        logger.info(rs);
        wlyyHttpLogDao.save(wlyyHttpLogDO);

        return rs;
    }

    /**
     *
     touser	否	成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）
     toparty	否	部门ID列表，多个接收者用‘|’分隔，最多支持100个。
     totag	否	标签ID列表，多个接收者用‘|’分隔，最多支持100个。
     msgtype	是	消息类型，此时固定为：miniprogram_notice
     appid	是	小程序appid，必须是与当前小程序应用关联的小程序
     page	否	点击消息卡片后的小程序页面，仅限本小程序内的页面。该字段不填则消息点击后不跳转。
     title	是	消息标题，长度限制4-12个汉字（支持id转译）
     description	否	消息描述，长度限制4-12个汉字（支持id转译）
     emphasis_first_item	否	是否放大第一个content_item
     content_item	否	消息内容键值对，最多允许10个item
     key	是	长度10个汉字以内
     value	是	长度30个汉字以内（支持id转译）
     enable_id_trans	否	表示是否开启id转译，0表示否，1表示是，默认0
     enable_duplicate_check	否	表示是否开启重复消息检查，0表示否，1表示是，默认0
     duplicate_check_interval	否	表示是否重复消息检查的时间间隔，默认1800s，最大不超过4小时
     * @throws Exception
     */
    public String sendXCXMes(String enterpriseId, String userId, String appid,String page, String title, String description, Boolean emphasis_first_item, String content_item)throws Exception{

        String mesurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+getXCXToken(enterpriseId);

        JSONObject param = new JSONObject();
        param.put("touser",userId);
        param.put("toparty","");
        param.put("totag","");
        param.put("msgtype","miniprogram_notice");

        JSONObject miniprogram_notice = new JSONObject();
        miniprogram_notice.put("appid",appid);
        miniprogram_notice.put("page",page);
        miniprogram_notice.put("title",title);
        miniprogram_notice.put("description",description);
        miniprogram_notice.put("emphasis_first_item",emphasis_first_item);
        JSONArray contents = JSONArray.parseArray(content_item);
        miniprogram_notice.put("content_item",contents);
        param.put("miniprogram_notice",miniprogram_notice);

        param.put("enable_id_trans",0);
        param.put("enable_duplicate_check",0);


        logger.info("XCXparam:"+param.toJSONString());

        String rs = HttpUtil.sendPost(mesurl,param.toJSONString());

        logger.info("XCXMes:"+rs);

        return rs;
    }


    public JSONArray getUserInfo(String enterpriseId,String dept)throws Exception{

        logger.info("getUserInfo dept:"+dept);

        if(StringUtils.isNotBlank(dept)){

            String userUrl ="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="+getToken(enterpriseId)+"&department_id="+dept+"&fetch_child=FETCH_CHILD";

            String users = HttpUtil.sendGet(userUrl);

            logger.info("usrs:"+users);

            JSONObject us = JSONObject.parseObject(users);

            JSONArray list = us.getJSONArray("userlist");

            logger.info("list size:"+list.size());

            return list;
        }
        return null;
    }

    public String saveAllUser(String enterpriseId)throws Exception{
        logger.info("saveAllUser");
        String depts = getDeptsId(enterpriseId);
        if(StringUtils.isNotBlank(depts)){
            //多部门过滤
            String dept[] = depts.split(",");
            logger.info("dept size:"+dept.length);
            if(dept!=null&&dept.length>0){
                for(String dp : dept){
                    JSONArray usrs = getUserInfo(enterpriseId,dp);
                    if(usrs!=null&&usrs.size()>0){
                        for(int i=0;i<usrs.size();i++){
                            JSONObject user = (JSONObject) usrs.get(i);
                            String mobile =user.getString("mobile");
                            if(StringUtils.isNotBlank(mobile)){
                                WxEnterpriseUserDO wxEnterpriseUserDO = wxEnterpriseUserDao.findByEnterpriseIdAndMobile(enterpriseId,mobile);
                                if(wxEnterpriseUserDO!=null){
                                    wxEnterpriseUserDO.setName(user.getString("name"));
                                    wxEnterpriseUserDO.setUserid(user.getString("userid"));
                                    wxEnterpriseUserDao.save(wxEnterpriseUserDO);
                                }else{
                                    WxEnterpriseUserDO userDO = new WxEnterpriseUserDO();
                                    userDO.setEnterpriseId(enterpriseId);
                                    userDO.setMobile(mobile);
                                    userDO.setUserid(user.getString("userid"));
                                    userDO.setName(user.getString("name"));
                                    wxEnterpriseUserDao.save(userDO);
                                }
                            }
                        }
                    }
                }
            }
        }
        return "ok";
    }


//    public String send

//    public static void main(String args[])throws Exception{
//
//        String corpsecret = "SKuRnq7cZqE5ax1YxwBwkCa-jdujkzbpMjWDCYU2raE";
//
//        String corpid = "wwd7335a5d80a9b14f";
//
//        String agentId = "1000003";
//
//        String result = HttpUtil.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
//
//        JSONObject json = JSONObject.parseObject(result);
//
//        String token = json.getString("access_token");
//
//        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token;
//
//        JSONObject param = new JSONObject();
//        param.put("touser","MuOu");
//        param.put("toparty","");
//        param.put("totag","");
//        param.put("msgtype","markdown");
//        param.put("agentid",agentId);
//        JSONObject markdown = new JSONObject();
//
//        markdown.put("content","dd[查看详情](www.baidu.com)");
//
//        param.put("markdown",markdown);
//        param.put("enable_duplicate_check",0);
//
//
//        String rs = HttpUtil.sendPost(url,param.toJSONString());
//
//        System.out.println(rs);
//    }


//    public static void main(String args[])throws Exception{
//
//        String corpsecret = "SKuRnq7cZqE5ax1YxwBwkCa-jdujkzbpMjWDCYU2raE";
//
//        String corpid = "wwd7335a5d80a9b14f";
//
//        String agentId = "1000003";
//
//        String result = HttpUtil.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
//
//        JSONObject json = JSONObject.parseObject(result);
//
//        String token = json.getString("access_token");
//
//        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token;
//
//        JSONObject param = new JSONObject();
//        param.put("touser","ShenZaiXin");
//        param.put("toparty","");
//        param.put("totag","");
//        param.put("msgtype","news");
//        param.put("agentid",agentId);
//
//        JSONObject news = new JSONObject();
//
//        JSONArray articles = new JSONArray();
//        JSONObject article = new JSONObject();
//
//        article.put("title","标题");
//        article.put("description","图文描述");
//        article.put("url","www.baidu.com");
//        article.put("picurl","");
//        articles.add(article);
//
//        news.put("articles",articles);
//
//        param.put("news",news);
//        param.put("enable_id_trans",0);
//        param.put("enable_duplicate_check",0);
//
//        String rs = HttpUtil.sendPost(url,param.toJSONString());
//
//    }

//    public static void main(String args[])throws Exception{
//
//        String corpsecret = "Uo-QnbYthpUC0tZt--l71n3QEafT3g2oH_j4mLjCokU";
//
//        String corpid = "ww4bf28f7a26e67fee";
//
//        String result = HttpUtil.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
//
//        JSONObject json = JSONObject.parseObject(result);
//
//        String token = json.getString("access_token");
//
////        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="+token;
////
////        String rs = HttpUtil.sendGet(url);
////
////        JSONObject r = JSONObject.parseObject(rs);
////
////        JSONArray depts = r.getJSONArray("department");
////
////        String deptStr ="";
////
////        if(depts!=null&&depts.size()>0){
////            for(int i=0;i<depts.size();i++){
////                JSONObject dept = (JSONObject) depts.get(i);
////                deptStr+=dept.getString("id")+"|";
////            }
////           deptStr = deptStr.substring(0,deptStr.length()-1);
////        }
////        System.out.println("deptStr"+deptStr);
//
//        String userUrl ="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="+token+"&department_id=20&fetch_child=FETCH_CHILD";
//
//        String users = HttpUtil.sendGet(userUrl);
//
//        JSONObject us = JSONObject.parseObject(users);
//
//        JSONArray list = us.getJSONArray("userlist");
//
//        System.out.println("list"+list.size());
//
//    }


}
