var System=require("../../system")
const crypto = require('crypto');
const querystring = require('querystring');
var xlsx = require('node-xlsx');
var fs=require("fs");
var accesskey='DHmRtFlw2Zr3KaRwUFeiu7FWATnmla';
var accessKeyId='LTAIyAUK8AD04P5S';
var settings=require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
class WxCtl{
  constructor(){
    this.imghandleApi=System.getObject("api.imghandle");
    this.gsbSearchApi=System.getObject("api.gsbtmsearch");
    this.gsbIcSearchApi=System.getObject("api.gsbicsearch");
    this.uploadCtl=System.getObject("web.uploadCtl");
    this.bytmsearch=System.getObject("api.bytmsearch");
    this.ossClient=System.getObject("util.ossClient");
    this.wxSve = System.getObject("service.wxSve");
    this.cacheManager = System.getObject("db.cacheManager");
    this.restS = System.getObject("util.restClient");
    this.orderSve = System.getObject("service.orderSve");
    }
    async getUidStr(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;
        if (len) {
          for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
        } else {
          var r;
          uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
          uuid[14] = '4';
          for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
              r = 0 | Math.random()*16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
          }
        }
        return uuid.join('');
    }
    //创建微信付款订单(用于h5端微信支付)
    async createWxJsUnifiedOrder(obj, pobj, req) {
      console.log("orderPay++++++++++++++++++++++++++++++++++++++++");
      console.log(pobj);
      var result = null;
      if (pobj) {
        var orderInfo = pobj.order;
        if(!orderInfo || !orderInfo.code){
          return {code:-1,msg:"订单参数错误"};
        }
        var order = await this.orderSve.findOneByCode(orderInfo.code);
        if(order ){
          if (order.orderPayStatus != "dfk") {
            return {code:-100,msg:"当前订单状态为："+order.orderPayStatusName+"，请勿操作"};
          } 
          var user = req.session.user;
          var notify_url = "http://igirl.gongsibao.com/wx/pay";
          var desc = order.sveItemName;
          var amount = order.totalSum;
          var product_id = order.sveItemCode;
          var openid =pobj.openid;
          var attach = order.code+";"+order.createuser_id;
          console.log("attach++++++++++++++++++++++++++");
          console.log(attach);
          try {
            result = await this.wxSve.createJsUnifiedOrder(desc, amount, notify_url, product_id, openid, attach, null);
            return {code:1,data:result};
          } catch (error) {
            return {code:-200,msg:"操作失败",error:error};
          }
        }else{
          return {code:-2,msg:"该订单不存在"};
        }
      }else{
        return {code:-3,msg:"参数错误"};
      }
    }
    //创建微信付款订单(用于PC端微信支付)
    async createWxUnifiedOrder(queryobj,qobj,req){
      var fillamount=Number(qobj.amount);
      var desc=qobj.desc;
      var orderInfo = qobj.order;
      if(!orderInfo || !orderInfo.code){
        return {code:-1,msg:"订单参数错误"};
      }
      var order = await this.orderSve.findOneByCode(orderInfo.code);
      if(!order){
        return {code:-2,msg:"订单不存在"};
      }
      if (order.orderPayStatus != "dfk") {
        return {code:-100,msg:"当前订单状态为："+order.orderPayStatusName+"，请勿操作"};
      } 
      var webuseropenid=order.code+";"+order.createuser_id;
      try{
        var result= await this.wxSve.createUnifiedOrder(desc,fillamount,'http://igirl.gongsibao.com/wx/pay',-1,webuseropenid);
        console.log(result);
        //充值下单成功后初始化业务锁
        this.cacheManager["CacheLocker"].init(result.out_trade_no);
        return {code:1,data:result};
      }catch(e){
        return {code:-200,msg:"操作失败",error:e};
      }
    }
    //关闭微信订单
    async closeWxOrder(queryobj,qobj){
      var tradekey=qobj.idkey;
      var result=await this.wxSve.closeWxOrder(tradekey);
      return System.getResult2(result,null);
    }
    //微信Oauth认证
    async fetchOAuthPath(q,obj,req){
      var subfixstr=obj.subfix;
      if(subfixstr==""){
        subfixstr=null;
      }
      try {
        var result=await this.wxSve.fetchWxOAuthPath(subfixstr);
        return System.getResult2(result,null);
      } catch (error) {
        console.log(error);
        return null;
      }
      
    }
    //通过code换取网页授权access_token
    async getToken(obj,req) {
      console.log(111111);
      var code = obj.code;
      var state = obj.state;
      if(!code){
        return {code:-1,msg:"code参数错误"};
      }
      if(!state){
        state="";
      }
       var reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
       console.log(reqUrl);
       var params = {
         appid: "wx4c91e81bbb6039cd",
         secret: "12048e66dba64f2581e02b306680b232",
         code: code,
         grant_type: 'authorization_code'
       };
       console.log(params);
       var data=querystring.stringify(params);
       try {
         console.log(111);
        var rtn=await this.restS.execGet(data,reqUrl);
        console.log(2222);
        var data = JSON.parse(rtn.stdout);
        console.log(333);
        return {code:1,data:data};
       } catch (error) {
        return {code:-1,msg:"获取openid失败",error:error};
       }
      
    }
    //获取支付的订单
    async getPaidOrder(obj, req) {
      var orderNum = obj.orderNum;
      console.log(orderNum);
      try {
        var order = await this.orderSve.dao.model.findOne({ where: { code: orderNum } });
        if (order.orderPayStatus == "yfk") {
          console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
          return {code:1,data:order};
        } else {
          return {code:-1, msg: "fail" };
        }
      } catch (e) {
        logCtl.error({
          optitle: "获取支付的订单异常error",
          op: "base/controller/impl/wxCtl.js/getPaidOrder",
          content: JSON.stringify(obj)+";"+JSON.stringify(e.stack),
          clientIp: ""
        });
        return { code:-2, msg: "err" };
      }

    }
    async getJsApiConfig(q,obj){
      console.log("getJsApiConfig.......................");
      console.log(obj.url);
      var result=await this.wxSve.getJsApiConfig(null,obj.url);
      return System.getResult2(result,null);
    }
}
module.exports=WxCtl;
// var test = new WxCtl();
// var obj = {
//   orderNum:"TMO201903271138qmKnk"
// };
// test.getPaidOrder(obj,{}).then(function(d){
//   console.log("dddddddddddddddddddd");
//   console.log(d);
// })
