var system=require("../../system")
var settings=require("../../../config/settings");
var crypto = require('crypto');
const XMLParser = require('xml2js');
const Promise = require('bluebird');
const parseXML = Promise.promisify(XMLParser.parseString);
const buildXML = new XMLParser.Builder({ rootName: 'xml', cdata: true, headless: true, renderOpts: { indent: ' ', pretty: 'true' } });
const WxopBase = require("../wxop.base");
/**
 * 微信公众号平台接口
 * zhuangbing
 * 2019.07.23
 */
class PublicplatformWxop extends WxopBase{
    constructor(){
        super();
        this.options = settings.wxopenplatformconfig;
        this.appId = this.options.appid;
        this.encodingAESKey = this.options.encodingaeskey;
        this.token = this.options.checktoken;
        this.domainname = this.options.domainname || "igtest.gongsibao.com";
        this.aesKey = this.getAesKey(this.encodingAESKey);
        this.iv = this.getIv(this.aesKey);
        this.db=system.getObject("db.connection").getCon();
        this.cacheManager=system.getObject("db.cacheManager");
        this.rc=system.getObject("util.execClient");
        this.restClient=system.getObject("util.restClient");
        this.wxappSve = system.getObject("service.wxappSve");
        this.wxuserSve = system.getObject("service.wxuserSve");
        this.userSve = system.getObject("service.userSve");
        this.companySve = system.getObject("service.companySve");
    }
    /**
     * 发送模板消息
     * @param touser	必填	接收者openid
     * @param template_id	必填	模板ID
     * @param url	非必填	模板跳转链接（海外帐号没有跳转能力）
     * @param data	必填	模板数据
     * data = {
                first: wechatItem.first,
                keyword1: { value: wechatItem.keyword1 },
                keyword2: { value: wechatItem.keyword2 }
               }
     * @param color	非必填	模板内容字体颜色，不填默认为黑色
     */
    async sendTmplMsg (obj) {
        var isZj = false;
        var industryres = await this.get_industry(obj);//获取公众号行业
        if(industryres && industryres.primary_industry){
            if(industryres.primary_industry.second_class=="中介服务"){
                isZj=true;
            }
        }
        if(industryres && industryres.secondary_industry){
            if(industryres.secondary_industry.second_class=="中介服务"){
                isZj=true;
            }
        }
        if(!isZj){
            var setindustryres = await this.api_set_industry(obj);//设置行业
            console.log("设置行业+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            if(setindustryres && setindustryres.errmsg=="ok"){
                isZj=true; 
            }else{
                return {code:-400,msg:"设置行业失败"};
            }
        }
        // var templateListObj = await this.get_all_private_template({access_token:obj.access_token});//获取模板列表
        var templateObj = await this.api_add_template({access_token:obj.access_token});//获取并添加模板id 
        if(templateObj && templateObj.errmsg=="ok"){
            obj["tid"]=templateObj.template_id;
            var sendMsgUrlPattern = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+obj.access_token;
            console.log(sendMsgUrlPattern);
            var txtObj ={
                "touser":obj.touser,
                "template_id":obj.tid,
                "url":obj.url,
                "topcolor":"#FF0000",
                "data":obj.data
            }
            await this.restClient.execPost(txtObj,sendMsgUrlPattern);
            var a = await this.del_private_template({access_token:obj.access_token,template_id:templateObj.template_id});
            return {code:1};
        }else{
            return {code:-100,msg:"获取消息模板失败"};
        }
        
    }

    /**
     * 设置所属行业(中介服务)
     * @param industry_id1 公众号模板消息所属行业编号 34 中介服务
     * @param industry_id2 公众号模板消息所属行业编号 32 法律
     */
    async api_set_industry(obj){
        var url="https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execPost({ "industry_id1":34,"industry_id2":32},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 获取设置的行业信息
     * 
     */
    async get_industry(obj){
        var url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execGet({},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }

    /**
     * 获得模板ID
     * @param access_token	接口调用凭证
     * @param template_id_short	模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式
     * 返回结果：
     *  {
            "errcode":0,
            "errmsg":"ok",
            "template_id":"Doclyl5uP7Aciu-qZ7mJNPtWkbkYnWBWVja26EGbNyk"
        }
     * OPENTM417832651 OPENTM417832652 OPENTM410290761 OPENTM206953685 OPENTM400034088
     */
    async api_add_template(obj){
        var url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execPost({ "template_id_short":"OPENTM400034088"},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 获取模板列表
     * @param access_token
     * 返回结果：
     * access_token	是	接口调用凭证
        template_id	是	模板ID
        title	是	模板标题
        primary_industry	是	模板所属行业的一级行业
        deputy_industry	是	模板所属行业的二级行业
        content	是	模板内容
        example	是	模板示例
     * 返回实例：
        {    
                "template_list": [{
                "template_id": "iPk5sOIt5X_flOVKn5GrTFpncEYTojx6ddbt8WYoV5s",
                "title": "领取奖金提醒",
                "primary_industry": "IT科技",
                "deputy_industry": "互联网|电子商务",
                "content": "{ {result.DATA} }\n\n领奖金额:{ {withdrawMoney.DATA} }\n领奖  时间:    { {withdrawTime.DATA} }\n银行信息:{ {cardInfo.DATA} }\n到账时间:  { {arrivedTime.DATA} }\n{ {remark.DATA} }",
                "example": "您已提交领奖申请\n\n领奖金额：xxxx元\n领奖时间：2013-10-10 12:22:22\n银行信息：xx银行(尾号xxxx)\n到账时间：预计xxxxxxx\n\n预计将于xxxx到达您的银行卡"
            }]
        }
     */
    async get_all_private_template(obj){
        var url="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execGet({},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 删除模板
     * @param access_token 接口调用凭证 template_id 公众帐号下模板消息ID
     * 返回结果：
     * {
        "errcode" : 0,
        "errmsg" : "ok"
        }
     */
    async del_private_template(obj){
        var url="https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execPost({template_id:obj.template_id},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 获取用户基本信息（包括UnionID机制）
     * access_token	是	调用接口凭证
     * openid	是	普通用户的标识，对当前公众号唯一
     * lang	否	返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
     */
    async api_user_info(obj){
        var url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+obj.access_token+"&openid="+obj.openid+"&lang=zh_CN";
        try{
            var rtn=await this.rc.execGet({},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 生成公众号二维码(临时)
     * 有效期 600秒
     */
    async makeQrWithScene(obj){
        var ak=obj.appid;
        var acck=obj.access_token;
        var cmdUrl=`https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${acck}`;
        var postobj={
            "action_name":"QR_STR_SCENE",
            "expire_seconds":600,
            "action_info":{
                "scene":{
                    "scene_str":obj.scene
                }
            }
        };
        var rtn=await this.rc.execPost(postobj,cmdUrl);
        // var result=await this.restClient.execPost(postobj,cmdUrl);
        var rtnobj=JSON.parse(rtn.stdout);
        var tkt=rtnobj.ticket;
        var qrurl=`https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${tkt}`;
        return qrurl;
    }
    /**
     * 被动回复用户消息
     * @param appid 必须 公众号的appid
     * @param company_id 必须 公众号绑定的公司id
     * @param redirect_uri 非必须 //回调uri
     * @param state 非必须 //附加参数，不传默认company_id
     * @param replyType 非必须 回复类型，不传默认1 (1,2,3 图文消息，文本消息，图片消息)
     * @param title 消息标题 图文消息必须
     * @param description 消息描述 图文消息必须
     * @param picUrl 消息图片链接 图文消息必须
     * @param url 非必须 点击图文消息跳转链接 不传默认oauth链接
     * @param content 回复的消息内容（换行：在content中能够换行，微信客户端就支持换行显示） 文本消息必须
     */
    async replyMsg(obj){
        // 
        var replyType = obj.replyType || 1;
        var openid =obj.openid;
        var company_id =obj.company_id;
        var appid = obj.appid;
        if(!openid){
            return null;
        }
        // if(!company_id){
        //     return null;
        // }
        if(!appid){
            return null;
        }
        var wxapp = await this.wxappSve.dao.model.findOne({where:{appid:appid,authorized_status:"authorized"},raw:true});
        if(!wxapp || !wxapp.original_id){
            return null;
        }
        if(company_id){
            var company = await this.companySve.dao.model.findOne({where:{id:company_id,isEnabled:true},raw:true});
            if(!company || !company.domainname){
                return null;
            }
        }
        var picUrl = obj.picUrl;
        var redirect_uri = obj.redirect_uri;
        var title =obj.title;
        var description =obj.description;
        if(replyType==1){
            if(!picUrl){
                return null;
            }
            if(!redirect_uri){
                var domainname = this.domainname;
                redirect_uri="http://"+domainname+"/wxop/oauth";
            }
            if(!title){
                return null;
            }
            if(!description){
                return null;
            }
        }
        if(replyType==2){
            if(!obj.content){
                return null;
            }
        }
        var state = obj.state || company_id || "";
        var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&amp;redirect_uri="+encodeURIComponent(redirect_uri)+"&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state="+state+"&amp;component_appid="+this.appId+"#wechat_redirect";
        console.log(url);
        var replyMsg="";
        if(replyType==1){
            replyMsg="<xml><ToUserName>"+openid+"</ToUserName>"+
            "<FromUserName>"+wxapp.original_id+"</FromUserName>"+
            "<CreateTime>"+Date.parse(new Date())/1000+"</CreateTime>"+
            "<MsgType>news</MsgType>"+
            "<ArticleCount>1</ArticleCount>"+
            "<Articles><item>"+
                "<Title>"+title+"</Title><Description>"+description+"</Description>"+
                "<PicUrl>"+picUrl+"</PicUrl><Url>"+url+"</Url>"+
            "</item></Articles></xml>";
        }else if(obj.replyType==2){
            replyMsg="<xml><ToUserName>"+openid+"</ToUserName>"+
            "<FromUserName>"+wxapp.original_id+"</FromUserName>"+
            "<CreateTime>"+Date.parse(new Date())/1000+"</CreateTime>"+
            "<MsgType>text</MsgType>"+
            "<Content>"+obj.content+"</Content>"+
            "</xml>";
        }else if(obj.replyType==3){
            //图片信息暂无
        }
        if(!replyMsg){
            return null;
        }
        var xml = await super.encryptMsg(replyMsg,null);
        return xml;
    }
    //全网发布测试发送消息
    async replyMsg2(obj){
        var openid =obj.openid;
        var appid = obj.appid;
        if(!openid){
            return null;
        }
        if(!appid){
            return null;
        }
        if(!obj.content){
            return null;
        }var replyMsg="";
        replyMsg="<xml><ToUserName>"+openid+"</ToUserName>"+
            "<FromUserName>gh_3c884a361561</FromUserName>"+
            "<CreateTime>"+Date.parse(new Date())/1000+"</CreateTime>"+
            "<MsgType>text</MsgType>"+
            "<Content>"+obj.content+"</Content>"+
            "</xml>";
        var xml = await super.encryptMsg(replyMsg,null);
        return xml;
    }
    /**
     * 获取oauth链接
     * @param company_id 公司id
     * @param state 自定义参数 默认空字符串
     */
    async getOauthLink(obj){
        var company_id =obj.company_id;
        var company = await this.companySve.dao.model.findOne({where:{id:company_id,isEnabled:true},raw:true});
        if(!company || !company.domainname){
            return null;
        }
        var appid = null;
        if(!company_id){
            return null;
        }
        var wxapp = await this.wxappSve.dao.model.findOne({where:{company_id:company_id,authorized_status:"authorized"},raw:true});
        if(!wxapp || !wxapp.original_id){
            return null;
        }
        appid = wxapp.appid;
        var redirect_uri="http://"+this.domainname+"/wxop/oauth";
        var state = obj.state || "";
        var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+encodeURIComponent(redirect_uri)+"&response_type=code&scope=snsapi_userinfo&state="+state+"&component_appid="+this.appId+"#wechat_redirect";
        return url;
    }
    /**
     * 自定义菜单查询接口
     */
    async menu_get(obj){
        var url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execGet({},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 自定义菜单创建接口
     */
    async menu_create(obj){
        var url=" https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execPost(obj.buttonObj,url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }

    /**
     * 自定义菜单删除接口
     * @param {*} obj 
     */
    async menu_delete(obj){
        var url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execGet({},url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
    /**
     * 客服接口-发消息
     */
    async custom_send(obj){
        var url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+obj.access_token;
        try{
            var rtn=await this.rc.execPost(obj.msgObj,url);
            console.log(rtn);
            var result=JSON.parse(rtn.stdout);
            return result;
        }catch(e){
            return null;
        }
    }
}
module.exports=PublicplatformWxop; 
// var task = new PublicplatformWxop();
// var replyMsg = {
//     replyType:2,appid:"wx5411ca0e225f2772",company_id:4,openid:"oV9ul1X4EZ2v7ttYzqaFiMWCH_NA",
//     content:"偏旁部首是一款在线学习汉字的字典类教学工具，用互联网技术帮助儿童用更有趣更简单的方式学习、认识汉字以及了解汉字演变历史和中华汉字文化。适合3-12岁童学使用学习。\n所属公司：北京联大共享科技有限公司"+
//     "\n合作联系   张老师微信：540381744，添加好友时，请加备注。"
//   };
// task.getOauthLink({company_id:4}).then(d=>{
//     console.log("dddddddddddddddddddd");
//     console.log(d);
// })
// var obj={
//     appid:"wx5411ca0e225f2772",company_id:4,title:"测试图文消息",description:"图文消息描述",openid:"oV9ul1X4EZ2v7ttYzqaFiMWCH_NA",
//     picUrl:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_238415589395610622019271446162公司宝logo.png"
// };
// task.replyMsg(replyMsg).then(d=>{
//     console.log("dddddddddddddddd");
//     console.log(d.toString());
// })