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

class IborderdkService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(IborderdkService));

    this.baseDao = system.getObject("db.order.iborderbaseDao");
    this.businessmenDao = system.getObject("db.business.businessmenDao");
    this.iborderbaseDao = system.getObject("db.order.iborderbaseDao");
  }

  async addOrder(params) {
  }

  /**
   * 创建订单
   * @param {*} params
   */
  async createOrder(params, t) {
    try {
      this.trimObject(params);
      let _ibOrderDk = await this.dao.create(params, t);
      return system.getResult(_ibOrderDk);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 更新数据
   * @param {*} params
   * @param {*} t
   */
  async updateOrder(params, t) {
    try {
      if (!params.id) {
        return system.getResult(null, `参数错误 ID 不能为空`);
      }
      this.trimObject(params);
      return await this.dao.update(params, t);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 完善信息
   * @param {*} params
   *   legalName
   *   legalMobile
   *   names
   *   creditCode
   *   isBank
   *   businessScope
   *   orderId
   */
  async completedOrder(params) {
    try {
      //1 检查个体户是否存在 （根据统一社会信用代码查个体工商户是否存在）
      this.trimObject(params);
      if (!params.orderId) {
        return system.getResult(null, `参数错误 ID 不能为空`);
      } else {
        params.order_id = this.trim(params.orderId);
      }
      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.businessmenDao.findBusinessmenByCreditCode(this.trim(params.creditCode));
      if (_businessmenRes.hasOwnProperty("status")) {
        return _businessmenRes;
      }
      if (_businessmenRes.id) {
        //如果用户存在id 直接更新  
        let _iborderbase = await this.iborderbaseDao.findById(this.trim(params.orderId));
        if (!_iborderbase) {
          return system.getResult(null, `参数错误 订单不存在`);
        }
        let self = this;

        //向参数中添加 是否完善信息标识

        // 更新字段设置
        let updateFields = {
          businessmen_id: self.trim(_businessmenRes.id),
          id: self.trim(params.id),
          isInfoComplete: 1
        };

        // 如果businessmen不存在order_id, 设置更新
        if(!_businessmenRes || !_businessmenRes.order_id) {
          updateFields.order_id = _iborderbase.id;
        }

        await this.db.transaction(async t => {
          //更新主表
          await self.iborderbaseDao.update(updateFields, t);
          //更新子表
          params.id = self.trim(params.order_id);
          params.isInfoComplete = 1;
          await self.dao.update(params, t);
        });
      } else {
        delete params.id;   // 删除id, 因为这个id是 orderId

        let self = this;
        await this.db.transaction(async t => {
          //如果不存在id 创建后更新
          let _businessment = await this.businessmenDao.create(params, t);
          //更新主表
          params.id = self.trim(params.orderId);
          params.isInfoComplete = 1;
          await self.iborderbaseDao.update({
            businessmen_id: self.trim(_businessment.id),
            isInfoComplete: 1,
            id: params.id
          }, t);
          //更新子表
          await self.dao.update(params, t);
        });
      }
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单办理
   * @param {} params
   * businessmenId  个体户ID
   * id             订单ID
   */
  async handling(params) {
    try {

      let _iborderbase = await this.iborderbaseDao.findById(this.trim(params.id));
      if (!_iborderbase.isInfoComplete != 1) {
        return system.getResult(null, `请完善信息再注册`);
      }
      //1 检查个体户是否签约
      let _businessmen = await this.businessmenDao.findById(this.trim(params.businessmenId));
      if (!_businessmen.signTime) {
        return system.getResultFail(-2, "个体户未签约",-2);
      }
      let valueAddedTax = 0;
      let additionalTax = 0;

      ///**************************************************************** */

      if (_iborderbase.payType != 20) {
        //如果不是年付费  计算费用
        let invoiceParams = await this.buildParamForCalInvoice(params);
        valueAddedTax = await calInvoice.calculationValueAddedTax(invoiceParams);
        //填充 增值税参数
        invoiceParams.valueAddedTax = valueAddedTax;
        additionalTax = await calInvoice.calculationAdditionalTax(invoiceParams);
        let res = {valueAddedTax: valueAddedTax, additionalTax: additionalTax};
        //4 推送计算结果  暂不推送
        return system.getResult(res);
      } else {
        //5 如果是不是按照年付款 直接更新订单金额
        // let _arguments = {};
        // _arguments.price=Number(valueAddedTax) + Number(additionalTax);
        // let updatePriceRes =await this.updateOrder(_arguments);
        //6 提交发票申请
        let submitApplyInvoiceParams = await this.buildParamForApplyInvoice(params);
        if (submitApplyInvoiceParams.hasOwnProperty("status") == 0) {
          return system.getResultSuccess(null, `发票申请已提交`);
        } else {
          return system.getResult(null, `发票申请失败`);
        }
      }
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息${error}`);
    }
  }

  /**
   * 创建计算发票所需的参数
   */
  async buildParamForCalInvoice(params) {
    let data = {
      "businessmenCreditCode": "111",
      "businessmenType": "10",
      "calNames": "valueAddedTax",
      "valCalWay": "1",
      "businessmenId": "12795594625000138",
      "taxIncPriRat": 0.03,
      "invoiceTime": "2019-11-26",
      "invoiceAmount": 20000000,
      "perIncTaxRange": [
        {
          "minValue": 0,
          "rate": "5",
          "quiCalDed": 0,
          "maxValue": 3000000
        },
        {
          "minValue": 3000100,
          "rate": "6",
          "quiCalDed": 200000,
          "maxValue": 10000000
        },
        {
          "minValue": 10000001,
          "rate": "8",
          "quiCalDed": 0,
          "maxValue": 214748364700
        }
      ],
      "valAddTaxRange": [
        {
          "minValue": 0,
          "zengzhiRate": "3",
          "fujiaRate": "12",
          "maxValue": 3000000
        },
        {
          "minValue": 3000100,
          "zengzhiRate": "3",
          "fujiaRate": "15",
          "maxValue": 10000000
        },
        {
          "minValue": 10000001,
          "zengzhiRate": "4",
          "fujiaRate": "16",
          "maxValue": 214748364700
        }
      ]
    }
    return data;
  }

  /**
   * 创建申请发票所需的参数
   * @param {*} params
   */
  async buildParamForApplyInvoice(params) {
    let data = {
      "serviceRate": 4,
      "perCalWay": "1",
      "valCalWay": "2",
      "taxCostPriRat": 0.95,
      "taxIncPriRat": 1.50,
      "invoiceTime": "2019-10-19",
      "perIncTaxRange": [
        {
          "minValue": 0,
          "rate": "1",
          "quiCalDed": 100000,
          "maxValue": 3000000
        },
        {
          "minValue": 3000100,
          "rate": "1.5",
          "quiCalDed": 200000,
          "maxValue": 10000000
        },
        {
          "minValue": 10000001,
          "rate": "4.86",
          "quiCalDed": 300000,
          "maxValue": 214748364700
        }
      ],
      "valAddTaxRange": [
        {
          "minValue": 0,
          "zengzhiRate": "1",
          "fujiaRate": "6",
          "maxValue": 3000000
        },
        {
          "minValue": 3000100,
          "zengzhiRate": "2",
          "fujiaRate": "8",
          "maxValue": 10000000
        },
        {
          "minValue": 10000001,
          "zengzhiRate": "3",
          "fujiaRate": "12",
          "maxValue": 214748364700
        }
      ],
      "merchantId": "11064622752480055",
      "merchantAccount": "driverBabyPublicAccount",
      "merchantName": "司机宝",
      "merchantCreditCode": "91110108MA008KB56P",
      "merchantAddr": "北京市海淀区北太平庄路18号3层3-0227",
      "merchantMobile": "010-5369854",
      "merchantBank": "110108022130868",

      "businessmenId": "110115023996882",
      "businessmenCreditCode": "91110115MA00HDC44L",
      "businessName": "北京富通勤国际贸易有限责任公司（个体工商）",
      "isBank": 1,
      "taxAuthorities": "北京大兴税务局",
      "type": 20,
      "invoiceAmount": 4000000,
      "statements": "wwww.baidu.com",
      "contract": "www.qq.com",
      "applyNo": "gongsibao-futong001",
      "isInvalid": 2,
      "parentId": null,
      "status": "1000",
      "customerStatus": "1000",
      "payWay": "20",
      "payAccount": null,
      "isPay": 1,
      "mailAddr": "北京市海淀区北太平庄路18号3层3-0227",
      "mailMobile": "18633923636",
      "mailTo": "赵彩红"
    }
    return data;
  }

  /**
   * 更新订单金额 、订单的状态
   * @param {*} params
   * id         订单的ID
   * price     订单的金额
   * status     订单的状态
   * orderpay_id 订单的支付Id
   */
  async updateOrder(params) {
    try {
      if (!params.id) {
        return system.getResult(null, `参数错误 ID不能为空`);
      }
      let _iborderbase = await this.iborderbaseDao.findById(this.trim(params.id));
      if (!_iborderbase) {
        return system.getResult(null, `订单不存在`);
      }
      let _iborderdk = await this._ibOrderDk.findById(this.trim(params.id));
      if (!_iborderdk) {
        return system.getResult(null, `订单不存在`);
      }
      let updateDate = {};
      if (params.status) {
        updateDate.status = this.trim(params.status);
      }
      if (params.price) {
        updateDate.price = Number(params.price || 0);
      }
      if (params.orderpay_id) {
        updateDate.orderpay_id = this.trim(params.orderpay_id);
      }
      let self = this;
      let res = await this.dao.db.transaction(async t => {
        //更新主表
        await self._iborderbase.dao.update(updateDate, t);
        //更新子表
        await self.dao.update(updateDate, t);
      });
      return system.getResult(res);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async orderPage(params) {
    let currentPage = Number(params.currentPage || 1);
    let pageSize = Number(params.pageSize || 10);

    let statuses = params.statuses;

    var where = {};

    var orderby = [
      ["id", 'desc']
    ];

    if (params.id) {
      where.id = params.id;
    }

    if (statuses && statuses.length > 0) {
      where.status = {
        [this.db.Op.in]: statuses
      }
    }

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);

    var page = await this.getPageList(currentPage, pageSize, where, orderby, null);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "status");

        this.handleDate(row, ["created_at"], null, -8);
      }
    }
    return system.getResultSuccess(page);
  }
}

module.exports = IborderdkService;
