var system = require("../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../config/settings");
const AppletBase = require("../applet.base");
const moment = require("moment");
const axios = require("axios");
const validation = system.getObject("util.validation");
const md5 = require("MD5");

class MerchantApplet extends AppletBase {
  constructor() {
    super();
    this.SMS_BANKMOBILE_KEY = "gtb_appl_mobile_";
    this.BANK_FOUR = "https://bpohhr.gongsibao.com/api/econtractApi/bankfour";
    this.GTB_APPID = "gtb-mcht-applet";
    this.GTB_KEY = "0e2e4e7249b79q50f234071651971242";

    this.uploadCtl = system.getObject("web.common.uploadCtl");
    this.idcardClient = system.getObject("util.idcardClient");
    this.merchantappletuserSve = system.getObject("service.uc.merchantappletuserSve");
    this.orderSve = system.getObject("service.saas.orderSve");
    this.businessmenSve = system.getObject("service.saas.businessmenSve");
    this.tradeSve = system.getObject("service.trade.tradeSve");
    this.saasInvoiceSve = system.getObject("service.saas.invoiceSve");
    this.merchantSve = system.getObject("service.saas.merchantSve");
    this.redisClient = system.getObject("util.redisClient");

    this.smsClient = system.getObject("util.smsClient");

  }

  async test(o, obj, req) {
    return {code: 0, data: 1};
  }

  async uploadConfig(gobj, pobj, req, loginUser) {
    try {
      // if(!loginUser){
      //     return {code: 0};
      // }
      // var openid = loginUser.openId;
      var data = await this.uploadCtl.getOssConfig();
      return this.returnSuccess(data);
    } catch (error) {
      console.log(error);
      return {code: 500};
    }
  }


  // 登录接口 post
  async login(o, obj, req) {
    try {
      let merchant_id = req.merchant_id;
      let nickName = obj.nickName;
      let avatarUrl = obj.avatarUrl;

      let merchant = await this.getMerchant(merchant_id);

      let user;
      let wxSession = await this.code2Session(obj, req);
      if (!wxSession.openid) {
        return this.returnFail("登录信息解析错误，请重试");
      }
      let params = {
        saas_merchant_id: merchant_id,
        saas_id: merchant.saas_id,
        openid: wxSession.openid,
        nickName: nickName,
        avatarUrl: avatarUrl,
      };
      let res = await this.merchantappletuserSve.login(params);
      if (res.status === 0) {
        return this.returnSuccess(res.data);
      } else {
        return this.returnFail(res.msg, res.data);
      }
    } catch (e) {
      console.log(e.stack);
    }
  }

  async loginUser(gobj, pobj, req, loginUser) {
    let user = await this.getLoginUser(pobj.merchant_id, pobj.openid);
    return this.returnSuccess(user);
  }

  async addLog(pobj, consume_type) {
    let user = await this.getLoginUser(pobj.merchant_id, pobj.openid);
    let log = {saas_id: user.saas_id, saas_merchant_id: user.saas_merchant_id, consume_type: consume_type, consume_id: user.id};
    let rs = await this.merchantSve.addConsumeLog({log: log});
    console.log("log rs : ", rs);
  }

  // 保存订单信息
  async saveOrder(gobj, pobj, req, loginUser) {
    try {
      let rs = await this.buildOrder(pobj);
      if (rs.code === 0) {
        return rs;
      }
      let bminfo = rs.data;
      // 银行卡四要数验证
      let bf = await this.bankfour({
        userName: bminfo.legal_name,
        userIdNo: bminfo.legal_idno,
        userBankNo: bminfo.bank_no,
        userMobile: bminfo.bank_mobile,
      });
      this.addLog(pobj, "bankfour");
      if (bf.code !== 0) {
        return this.returnFail("银行卡四要素验证失败，请检查法人姓名，身份证，银行卡号，银行卡预留手机号正确");
      }

      let merchant = await this.getMerchant(pobj.merchant_id);
      let loginUser = await this.getLoginUser(pobj.merchant_id, pobj.openid);
      let order = {
        saas_id: merchant.saas_id,
        merchant_id: merchant.id,
        channel_id: merchant.channel_id,
        product_id: "10020000",
        merchant_app_user_id: loginUser.id,
        price: system.y2f(merchant.sign.bm_reg_price) || 0,
        bminfo: rs.data
      };

      let res = await this.orderSve.microAdd(order);
      if (res.status === 0) {
        return this.returnSuccess(res.data);
      } else {
        return this.returnFail(res.msg || "保存订单失败");
      }
    } catch (e) {
      console.log(e.stack);
      return {
        code: -200,
        msg: "error",
        data: {},
        stack: e.stack
      };
    }
  }

  async buildOrder(obj) {
    if (!obj.idcard_front) {
      return this.returnFail("请上传身份证人像面");
    }
    if (!obj.idcard_back) {
      return this.returnFail("请上传身份证国徽图");
    }
    if (!obj.legal_name) {
      return this.returnFail("请填写法人姓名");
    }
    if (!obj.legal_mobile) {
      return this.returnFail("请填写联系手机");
    }
    if (!/^1\d{10}$/.test(obj.legal_mobile)) {
      return this.returnFail("联系手机格式错误");
    }
    if (!obj.legal_idno) {
      return this.returnFail("请填写身份证号码");
    }
    if (!await this.idcardClient.checkIDCard(obj.legal_idno)) {
      return this.returnFail("身份证号码错误，请检查后重新输入");
    }
    if (!obj.company_names) {
      return this.returnFail("请填写公司名称");
    }

    if (!obj.bank_front) {
      return this.returnFail("请上传银行卡正面");
    }
    if (!obj.bank_back) {
      return this.returnFail("请上传银行卡反面");
    }
    if (!obj.bank_name) {
      return this.returnFail("请填写银行预留手机号");
    }
    if (!obj.bank_no) {
      return this.returnFail("请填写银行预留手机号");
    }
    if (!obj.bank_mobile) {
      return this.returnFail("请填写银行预留手机号");
    }
    let noteCode = (obj.note_code || "").trim();
    if (!noteCode) {
      return this.returnFail("请填写短信验证码");
    }

    let vcode = await this.redisClient.get(this.SMS_BANKMOBILE_KEY + obj.bank_mobile);
    if (!vcode) {
      return this.returnFail("短信验证码已过期，请重新发送");
    }
    if (vcode != noteCode) {
      return this.returnFail("短信验证码错误，请重新填写");
    }
    let bminfo = {
      idcard_front: obj.idcard_front,
      idcard_back: obj.idcard_back,
      legal_name: obj.legal_name,
      legal_mobile: obj.legal_mobile,
      legal_idno: obj.legal_idno,
      company_names: obj.company_names,
      bank_front: obj.bank_front,
      bank_back: obj.bank_back,
      bank_name: obj.bank_name,
      bank_no: obj.bank_no,
      bank_mobile: obj.bank_mobile,
    };

    return this.returnSuccess(bminfo);
  }

  async myOrders(gobj, pobj, req) {
    let loginUser = await this.getLoginUser(pobj.merchant_id, pobj.openid);
    if (!loginUser) {
      return this.returnSuccess({count: 0, rows: []});
    }
    try {
      let params = {
        pageSize: Number(pobj.pageSize || 10),
        currentPage: Number(pobj.currentPage || 1),
        merchant_app_user_id: loginUser.id,
        merchant_id: loginUser.merchant_id,
      }

      let page = await this.orderSve.page(params);
      if (page.status === 0) {
        return this.returnSuccess(page.data);
      } else {
        return this.returnFail(page.msg);
      }
    } catch (e) {
      console.log(e.stack);
      //日志记录
      return {
        code: -200,
        msg: "error",
        data: {},
        stack: e.stack
      };
    }

    console.log(decryptData);
  }

  /**
   * 查询订单明细
   * @param {*} gobj
   * @param {*} pobj
   * @param {*} req
   * @param {*} loginUser
   */
  async orderInfo(gobj, pobj, req) {
    let loginUser = await this.getLoginUser(pobj.merchant_id, pobj.openid);
    if (!loginUser) {
      return this.returnSuccess({});
    }
    try {
      let rs = await this.orderSve.orderInfo(pobj);
      if (rs.status === 0) {
        return this.returnSuccess(rs.data);
      } else {
        return this.returnFail(page.msg);
      }
    } catch (error) {
      console.log(error);
      return system.getResult(null, error);
    }
  }

  async idNoValid(gobj, pobj, req, loginUser) {
    try {
      let idno = (pobj.idno || "").trim();
      if (!idno) {
        return {code: 0, msg: "请填写身份证号码"};
      }

      let success = await this.idcardClient.checkIDCard(idno);
      if (success) {
        return this.returnSuccess(1);
      }
      return this.returnFail("身份证号码格式错误");
    } catch (error) {
      console.log(error);
      return {code: 500, msg: "服务忙，请稍后重试"};
    }
  }

  /**
   * 个体户列表/个体户列表
   * @param params
   * @param pobj2
   * @param req
   * @returns {Promise<void>}
   */
  async saasorderbusinessmenPage(params, pobj2, req) {
    let loginUser = await this.getLoginUser(pobj2.merchant_id, pobj2.openid);
    pobj2.merchant_app_user_id = loginUser.id;
    let res = await this.businessmenSve.saasorderbusinessmenPage(pobj2);
    if (res.status == 0) {
      return this.returnSuccess(res.data);
    } else {
      this.returnFail("请求超时 请稍后在试");
    }
  }

  /**
   * 获取用户下的所有交易记录
   * @param pobj1
   * @param pobj2
   * @param req
   * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
   */
  async saasTradeBusinessmenPage(pobj1, pobj2, req) {
    let loginUser = await this.getLoginUser(pobj2.merchant_id, pobj2.openid);
    pobj2.merchant_app_user_id = loginUser.id;
    pobj2.attrs = ["credit_code"];
    if (!pobj2.merchant_app_user_id) {
      return system.getResult(null, `登录失效，请重新登录`);
    }
    try {
      let creditCodeArray = await this.businessmenSve.assorderBusinessmenInfo(pobj2);
      if (creditCodeArray.status != 0) {
        return this.returnSuccess({count: 0, rows: []});
      }
      let creditCodes = [];
      for (let val of creditCodeArray.data) {
        creditCodes.push(val.credit_code);
      }
      if (!creditCodes || creditCodes.length == 0) {
        return this.returnSuccess({count: 0, rows: []});
      }
      pobj2.credit_code_array = creditCodes;
      let res = await this.tradeSve.tradeItemBycreditCode(pobj2);
      if (res.status == 0) {
        return this.returnSuccess(res.data);
      } else {
        return this.returnFail("请求超时 请稍后在试");
      }
    } catch (e) {
      console.log(e);
      return this.returnFail("请求超时 请稍后在试");
    }
  }

  /**
   * 发票管理
   * @param pobj1
   * @param pobj2
   * @param req
   * @returns {Promise<void>}
   */
  async invoiceBycreditCode(pobj1, pobj2, req) {
    let loginUser = await this.getLoginUser(pobj2.merchant_id, pobj2.openid);
    pobj2.merchant_app_user_id = loginUser.id;
    pobj2.attrs = ["credit_code"];
    if (!pobj2.merchant_app_user_id) {
      return system.getResult(null, `登录失效，请重新登录`);
    }
    try {
      let creditCodeArray = await this.businessmenSve.assorderBusinessmenInfo(pobj2);
      if (creditCodeArray.status != 0) {
        return this.returnSuccess({count: 0, rows: []});

      }
      let creditCodes = [];
      for (let val of creditCodeArray.data) {
        creditCodes.push(val.credit_code);
      }
      if (!creditCodes || creditCodes.length == 0) {
        return this.returnSuccess({count: 0, rows: []});
      }
      pobj2.credit_code_array = creditCodes;

      let res = await this.saasInvoiceSve.invoiceBycreditCode(pobj2);
      if (res.status == 0) {
        return this.returnSuccess(res.data);
      } else {
        return this.returnFail("请求超时 请稍后在试");
      }
    } catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * 银行卡预留手机号短信验证码
   * @param pobj1
   * @param pobj
   * @param req
   * @returns {Promise<void>}
   */
  async sendBankMobileCode(pobj1, pobj, req) {
    let loginUser = await this.getLoginUser(pobj.merchant_id, pobj.openid);
    let mobile = pobj.mobile;
    if (!mobile) {
      return this.returnFail("请先填写银行卡预留手机号");
    }
    if (validation.isMobile(mobile)) {
      return this.returnFail("银行卡预留手机号格式错误");
    }
    try {
      let key = this.SMS_BANKMOBILE_KEY + mobile;
      let vcode = await this.redisClient.get(key + "t");
      // let vcode;
      if (!vcode) {
        vcode = await this.getVCode();
        await this.redisClient.setWithEx(key, vcode, 5 * 60);
        await this.redisClient.setWithEx(key + "t", vcode, 60);
        let msg = "您的个体户注册手机验证码为" + vcode + ", (切勿将验证码告知别人, 请在5分钟内输入完成验证, 如有问题请联系客服。)";
        let rs = await this.smsClient.sendMsg(mobile, msg);
        this.addLog(pobj, "sms");
        console.log(rs);
      }
      return this.returnSuccess(1);
    } catch (error) {
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  getVCode() {
    var randomNum = "" + Math.round(Math.random() * 1000000);
    while (randomNum.length < 6) {
      randomNum = "0" + randomNum;
    }
    return randomNum;
  }

  async bankfour(params) {
    let nonceStr = await this.getUidStr(16, 36);
    let data = {
      appId: this.GTB_APPID,
      userName: params.userName,
      userIdNo: params.userIdNo,
      userBankNo: params.userBankNo,
      userMobile: params.userMobile,
      nonceStr: nonceStr,
    };

    // 签名
    var signArr = [];
    var keys = Object.keys(data).sort();
    for (var i = 0; i < keys.length; i++) {
      var k = keys[i];
      var v = data[k];
      if (!k || !v || k == 'sign') {
        continue;
      }
      signArr.push(k + "=" + v);
    }

    var signStr = signArr.join("&") + "&key=" + this.GTB_KEY;
    var sign = md5(signStr).toUpperCase();
    console.log(sign);
    data.sign = sign;
    let rs = await axios({
      method: 'post',
      url: this.BANK_FOUR,
      data: data,
    });
    try {
      console.log(rs.data, `个体户注册银行卡四要素验证request[${JSON.stringify(data)}], response[${JSON.stringify(rs.data)}]`);
    } catch (e) {
      console.log(e.stack);
    }
    return rs.data || {};
  }
}

module.exports = MerchantApplet;