var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const md5 = require("MD5");
const moment = require("moment");

const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
class EsettleCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EsettleCtl));
    this.userSve = system.getObject("service.userSve");
    this.userbpocompanySve = system.getObject("service.userbpocompanySve");
    this.epartnerSve = system.getObject("service.epartnerSve");
    this.ecompanySve = system.getObject("service.ecompanySve");

    this.restClient = system.getObject("util.restClient");
    this.redisClient = system.getObject("util.redisClient");

    this.outTradeNoKey = 'bpo_outtradeno';
    this.verifyCode = 'T90W&uFOsV@vN2mKC!5A';
  }

  async busiAccount(queryobj,qobj,req) {
    var result = {};
    try {
      var param = {
        "appId": "1103817785",
        "sign": "439BAC772B4ECF9B7D9BB2EBB4A1C438",
        "mchtId": "1103817785420820481",
        "signType": "MD5",
        "nonceStr": await this.getUidStr(16)
      }

      var signArr = [];
      signArr.push("appId=" + param.appId);
      signArr.push("mchtId=" + param.mchtId);
      signArr.push("nonceStr=" + param.nonceStr);
      signArr.push("signType=" + param.signType);
      signArr.push("key=ca47edd3ae8bac3f7a68d8126d891f52");

      param.sign = md5(signArr.join("&")).toUpperCase();

      console.log(param);
      try {
        let rs = await this.restClient.execPost(param, "https://pay.gongsibao.com/merchant/busiAccount/query");
        console.log(rs)
        if (rs && rs.stdout) {
          var stdout = JSON.parse(rs.stdout) || {};
          var code = stdout.code;

          if (code == 0) {
            code = 1;
          } else if (code == 1) {
            code = 0;
          } else {}
          result.code = code;
          result.msg = stdout.msg;
          result.data = stdout.data;
        } else {
          result.code = 0;
          result.msg = '结算接口返回空';
        }
      } catch (error) {
        result.code = 500;
        result.msg = '结算接口异常';
      }
    } catch (error) {
      result.code = 500;
      result.msg = '服务异常';
    }
    return result;
  }

  async getSign(queryobj,qobj,req) {

    var outTradeNo = await this.redisClient.get(this.outTradeNoKey);
    if (!outTradeNo) {
      outTradeNo = 123456579921;
    } else {
      outTradeNo = Number(outTradeNo) + 1;
    }

    this.redisClient.set(this.outTradeNoKey, outTradeNo.toString());
    var now = moment().add(30, 'seconds').format('YYYYMMDDHHmmss');

    var nonceStr = await this.getUidStr(16);
    var signArr = [];
    signArr.push("appId=" + qobj.appId);
    signArr.push("currency=" + qobj.currency);
    signArr.push("mchtId=" + qobj.mchtId);
    signArr.push("nonceStr=" + nonceStr);
    signArr.push("notityUrl=" + qobj.notityUrl);
    signArr.push("outTradeNo=" + outTradeNo);
    signArr.push("signType=" + qobj.signType);
    signArr.push("tradeTime=" + now);
    signArr.push("key=" + (qobj.key || "ca47edd3ae8bac3f7a68d8126d891f52"));
    var sign = md5(signArr.join("&")).toUpperCase();

    var data = {
      sign : sign,
      tradeTime : now,
      outTradeNo : outTradeNo,
      nonceStr : nonceStr
    }
    return system.getResult2(data);
  }

  async transfer(queryobj,qobj,req) {
    if(this.verifyCode != qobj.verifyCode)  {
      return system.getErrResult2('验证码错误');
    }

    var obj = JSON.parse(qobj.params);
    
    var bizs = obj.bizContent;
    var bizContent = [];
    if(!bizs || bizs.length == 0) {
      return system.getErrResult2('请求参数缺少转账业务人员');
    }

    for (var biz of bizs) {
      bizContent.push({
        "note": biz.note,
        "idType": biz.idType,
        "idName": biz.idName,
        "seqNo":  biz.seqNo,
        "accNo": biz.accNo,
        "mobile": biz.mobile,
        "amt": Number(biz.amt || 100),
        "accType": biz.accType || "00",
        "idNo": biz.idNo
      });
    }

    // var now = moment().add(30, 'seconds').format('YYYYMMDDHHmmss');

    var param = {
      "appId": obj.appId,
      "currency": obj.currency,
      "mchtId": obj.mchtId,
      "nonceStr": qobj.nonceStr,
      "notityUrl": obj.notityUrl,
      "outTradeNo": qobj.outTradeNo,
      "signType": obj.signType,
      "tradeTime": qobj.tradeTime,
      "bizContent": bizContent,
    }

    // now
    var signArr = [];
    signArr.push("appId=" + param.appId);
    signArr.push("currency=" + param.currency);
    signArr.push("mchtId=" + param.mchtId);
    signArr.push("nonceStr=" + param.nonceStr);
    signArr.push("notityUrl=" + param.notityUrl);
    signArr.push("outTradeNo=" + param.outTradeNo);
    signArr.push("signType=" + param.signType);
    signArr.push("tradeTime=" + param.tradeTime);
    signArr.push("key=" + (param.key || "ca47edd3ae8bac3f7a68d8126d891f52"));
    param.sign = md5(signArr.join("&")).toUpperCase();
    if(param.sign != qobj.sign) {
      return system.getErrResult2('签名错误, 请重新签名');
    }
    console.log(JSON.stringify(param));
    try {
      let rs = await this.restClient.execPost(param, "https://pay.gongsibao.com/merchant/order/transfer");
      param.result = rs;
      console.log(rs);
    } catch (error) {
      console.log(error);
    }
    return system.getResult2(param);
  }

  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('');
  }

  async allList(queryobj, qobj, req) {
    try {
      var params = qobj.search || {};

      var loginUser = req.session.user;
      var roles = loginUser.Roles || [];
      var isZC = false;
      for(var r of roles) {
        if(r.code == 'zcry' || r.code == 'zcgl') {
          isZC = true;
          break;
        }
      }

      if(!loginUser.isAdmin && !isZC) {
        if(!req.session.myIds || req.session.myIds.length == 0) {
          return system.getResult2({count: 0, rows: []});
        }
        var companyNames = await this.ecompanySve.findNamesByOwnerIds(req.session.myIds);
        if(!companyNames || companyNames.length == 0) {
          return system.getResult2({count: 0, rows: []});
        }
        params.companyNames = companyNames;
      }

      var params = this.getSettleParams(params);
      var page = await this.service.ratepayingList(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async statAllAmt(queryobj, qobj, req) {
    try {
      var params = this.getSettleParams(qobj.search);
      var rs = await this.service.statSettleAmt(params);
      return system.getResult2(rs);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async balanceList(queryobj, qobj, req) {
    try {
      var params = qobj.search || {};

      var user = await this.userSve.findById(req.session.user.id);
      if(!user.isAdmin && !user.isBpoManager) {
        var list = await this.userbpocompanySve.byUserId(user.id);
        if(!list || list.length == 0) {
          return system.getResult2({total:0, rows:[]});
        }

        var companyNames = [];
        for(var item of list) {
          companyNames.push(item.companyName);
        }

        params.companyNames = companyNames;
      }

      var page = await this.service.balancePage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }


  async settleList(queryobj, qobj, req) {
    var ecompany = req.session.ecompany;
    if(!ecompany) {
      return system.getResult2({count:0, rows:[]});
    }

    try {
      var params = this.getSettleParams(qobj.search);
      params.companyName = ecompany.name;
      var page = await this.service.settlePage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async epartneramtlist(queryobj, qobj, req) {
    try {
      var nameList = await this.ecompanySve.findNamesByOwnerIds([req.session.user.id]);
      if(!nameList || nameList.length == 0) {
        return system.getResult2({count:0, rows:[]});
      }
      
      var params = this.getSettleParams(qobj.search);

      params.companyNames = nameList;
      var page = await this.service.settlePage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");  
    }
  }

  async settleItemList(queryobj, qobj, req) {
    try {
      var params = qobj.search;
      var page = await this.service.settleItemList(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");  
    }
  }

  
  getSettleParams(search) {
    var params = search || {};
    if(this.trim(params.createBegin)) {
      params.createBegin = this.trim(params.createBegin) + " 00:00:00";
    }
    if(this.trim(params.createEnd)) {
      params.createEnd = this.trim(params.createEnd) + " 23:59:59";
    }
    
    if(params.amtBegin) {
      params.amtBegin = Number(params.amtBegin) * 100;
    }
    if(params.amtEnd) {
      params.amtEnd = Number(params.amtEnd) * 100;
    }
    return params;
  }

  async statOnlineSettle(queryobj, qobj, req) {
    var loginUser = req.session.user;
    if(!loginUser.isBpoManager && !loginUser.isAdmin) {
      return system.getResult2({});
    }

    try {
      var params = qobj.search || {};

      var payTimeBegin, payTimeEnd;
      if (this.trim(params.month)) {
        params.payTimeBegin = moment(params.month).format("YYYY-MM-DD") + " 00:00:00";
        params.payTimeEnd = moment(params.month).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
      }
      var rs = await this.service.statOnlineSettle(params);
      return system.getResult2(rs);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }
}
module.exports = EsettleCtl;