var system = require("../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../config/settings");
const AppletBase = require("../applet.base");
const fs = require("fs");
const moment = require("moment");

class MerchantApplet extends AppletBase {
  constructor() {
    super();
    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.merchantId = 1;
    this.businessmenSve = system.getObject("service.saas.businessmenSve");
    this.tradeSve = system.getObject("service.trade.tradeSve");
    this.saasInvoiceSve = system.getObject("service.saas.invoiceSve");

  }

  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 saveOrder(gobj, pobj, req, loginUser) {
    try {
      let rs = await this.buildOrder(pobj);
      if (rs.code === 0) {
        return rs;
      }
      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,
        product_id: "10010000",
        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 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,`系统错误`);
    }
  }

}

module.exports = MerchantApplet;