const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
const moment = require("moment");

class IborderbaseService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(IborderbaseService));
    this.iborderSve = system.getObject("service.order.iborderSve");
    this.iborderdkSve = system.getObject("service.order.iborderdkSve");
    this.iborderdzSve = system.getObject("service.order.iborderdzSve");
    this.businessmenSve = system.getObject("service.business.businessmenSve");
    this.channelSve = system.getObject("service.order.channelSve");
    this.paymentSve = system.getObject("service.order.paymentSve");
    this.services = {
      "1000": this.iborderSve,   // 注册订单
      "1010": this.iborderdzSve, // 代开订单
      "1030": this.iborderdkSve, // 代账订单
      "1040": this.iborderSve,   // 增值服务
    }
  }


  getService(productType) {
    return this.services[productType];
  }

  /**
   * 创建基类订单
   * @param {*} params
   */
  async apiCreateOrder(params) {
    this.trimObject(params);
    // if(!params.productType){
    //   return system.getResult(null, `参数错误 产品类型错误`);
    // }
    // if(!params.productItems instanceof Array){
    //   return system.getResult(null, `参数错误 产品项目错误`);
    // }
    // if(!params.channelNo){
    //   return system.getResult(null, `参数错误 渠道名称错误`);
    // }
    if(!params.thirdNo){
      return system.getResult(null, `请传入订单id`);
    }
    // if(!Number(params.price)<0){
    //   return system.getResult(null, `参数错误 订单价格错误`);
    // }
    // if(!params.payType){
    //   return system.getResult(null, `参数错误 支付方式错误`);
    // }
    // if(!params.legalName){
    //   return system.getResult(null, `参数错误 联系人不能为空`);
    // }
    // if(!params.legalMobile){
    //   return system.getResult(null, `参数错误 联系电话不能为空`);
    // }
    // if(!params.invoiceType){
    //   return system.getResult(null, `参数错误 发票类型错误`);
    // }

    let productType = this.trim(params.productTypes);
    let childSve = this.getService(productType);
    if (!childSve) {
      return system.getResult(null, `暂不支持此种产品类型：${productType}`);
    }

    try {
      let channel = this.channelSve.findOne({channelNo: params.channelNo});
      if (!channel) {
        return system.getResult(null, `渠道${params.channelNo}不存在`);
      }

      params.channelNo = this.trim(params.channelNo);
      params.thirdNo = this.trim(params.thirdNo);
      params.notes = this.trim(params.notes);
      params.legalName = this.trim(params.legalName);
      params.legalMobile = this.trim(params.legalMobile);
      params.legalEmail = this.trim(params.legalEmail);
      params.payType = Number(params.payType || 1);
      params.productType = productType;
      params.price = Number(params.price || 0);
      params.status = "1000"; // 待处理
      params.channelOrderNo = params.channelNo;

      let self = this;
      //1 保存基类的信息
      await this.db.transaction(async t => {
        //创建基类表
        let _baseOrder = await self.create(params, t);

        // 处理payment
        if (payType != 2) {
          var payment = {
            order_id: _baseOrder.id,
            price: params.price,
            channelName: channel.channelName,
            companyName: "",
            payType: payType,
            payStatus: "10",
          };
          payment = await this.paymentSve.create(payment);
          params.orderpay_id = payment.id;
        }
        // 将id赋值
        params.id = _baseOrder.id;

        // 创建订单
        await childSve.createOrder(params, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 完善信息
   * @param {*} params
   *   legalName
   *   legalMobile
   *   names
   *   creditCode
   *   isBank
   *   businessScope
   */
  async completedOrder(params) {
    try {
      //1 检查个体户是否存在 （根据统一社会信用代码查个体工商户是否存在）
      this.trimObject(params);
      if (!params.id) { return system.getResult(null, `参数错误 ID 不能为空`); }
      if (!params.legalName) { return system.getResult(null, `参数错误 法人姓名不能为空`); }
      if (!params.legalMobile) { return system.getResult(null, `参数错误 法人电话不能为空`); }
      if (!params.creditCode) { return system.getResult(null, `参数错误 法人统一社会信用代码不能为空`); }
      if (!params.names) { return system.getResult(null, `参数错误 个体户名称不能为空`); }
      if (!params.businessScope) { return system.getResult(null, `参数错误 经营范围不能为空`); }

      //2 如果不存在添加保存个体户  完善信息
      let _businessmenRes = await this.businessmenSve.findBusinessmenByCreditCode(this.trim(params.creditCode));
      if (_businessmenRes.hasOwnProperty("status")) {
        return _businessmenRes;
      }
      let childSve = this.getService(productType);
      if (_businessmenRes.id) {
        //如果用户存在id 直接更新  
        let _iborderbase = await this.dao.findById(this.trim(params.id));
        if (!_iborderbase) {
          return system.getResult(null, `参数错误 订单不存在`);
        }
        let self = this;
        await this.db.transaction(async t =>{
          //更新主表
          await self.dao.update({businessmen_id:self.trim(_businessmenRes.id),id:self.trim(params.id)},t);
          //更新子表
          await childSve.dao.update(params, null);
        });
      } else {
        let self = this;
        await this.db.transaction(async t =>{
          //如果不存在id 创建后更新
          let _businessment = await this.businessmenSve.dao.create(params,t);
          //更新主表
          await self.dao.update({businessmen_id:self.trim(_businessment.id),id:self.trim(params.id)},t);
          //更新子表
          await childSve.dao.update(params, null);
        });
      }
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单办理
   * @param {} params 
   */
  async apiHandling (params){
    //1 检查个体户参数
    //2 检查是否支付
  }

  /**
   * 计算 增值税 和 附加税
   * @param {*} params 
   */
  async calInvoiceAmount (params){
    let res = await this.cal
  }


  /**
   * 更新base表
   * @param {*} params 
   */
  async completedOrderInfo(params, t) {
    try {
      return await this.dao.update(params, t);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  async apiAdd(params) {
    try {
      let sve = this.getService(params.productType);
      if (!sve) {
        return system.getResult(null, `产品类型错误${params.productType}`);
      }
      return sve.addOrder(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiSaveInfo() {
    try {
      let sve = this.getService(params.productType);
      if (!sve) {
        return system.getResult(null, `产品类型错误${params.productType}`);
      }
      return sve.saveInfo(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }
}

module.exports = IborderbaseService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });