const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const moment = require('moment');
var rule =require("../../../utils/invoiceRule/rule");
const Decimal = require('decimal.js');
class ApplyService extends ServiceBase {
  constructor() {
    super("invoice", ServiceBase.getDaoName(ApplyService));
    let is = system.getObject("util.invoiceStatus");
    this.invoiceStatus = is.status;
    this.delivererDao = system.getObject("db.invoice.delivererDao");
    this.invoiceDao = system.getObject("db.invoice.invoiceDao");
    //最大的发票总额度
    this.MAX_TOTAL_AMOUNT = 500000000;
    //警告发票额度
    this.WARNING_AMOUNT = 400000000;
    this.PER_TAX = 1; //个税
    this.VAL_TAX = 2; //增值税
    this.INVOICE_MAX = 10; //一次性插入最大值
  }


  /**
   * 保存发票信息
  */
  async apiSaveInvoice(params) {
    try {
      let res = await this.saveInvoice(params);
      return res;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息：${error}`);
    }
  }

  /**
   * 查询申请列表（平台）
   * @param {*} params 
   */
  async apiQueryApplyInvoices(params) {
    try {
      return await this.queryApplyInvoices(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  /**
   * 查询发票明细（平台）
   * @param {*} params 
   */
  async apiQueryInvoice(params) {
    try {
      var merchantId = params.merchantId || params.merchant_id;
      if ((params.merchantId && params.applyNo) || params.id) {
        let res = await this.queryInvoice(params.applyNo, merchantId, params.id);
        return res;
      } else {
        return system.getResultSuccess();
      }
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息：${error}`);
    }
  }


  /**
   * 发票撤回
   * @param params
   * {
   *    applyNo:"",    //发票申请编号
   *    merchantId:"", //商户id
   * }
   */
  async apiCancelInvoice(params) {
    try {
      var merchantId = params.merchantId || params.merchant_id;

      if (!params.applyNo || !merchantId) {
        return system.getResult(null, "发票申请编号不合法。");
      }
      return await this.cancelInvoice(params.applyNo, merchantId);
    } catch (error) {
      return system.getResult(null, `系统错误：错误信息 ${error}`);
    }
  }

  /**
   * 平台业务分配
   * @param {*} params 
   * {
   *    id:"xxx"    //发票id
   *    nextStatus:"xxx",   //发票状态
   * 
   * }
   */
  async apiAssignment(params) {
    try {
      if (!params.id) {
        return system.getResult(null, `参数错误`);
      }
      return await this.assignment(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 平台业务分配
   * @param {*} params 
   * {
   *    id:"xxx"    //发票id
   *    nextStatus:"xxx",   //发票状态
   * 
   * }
   */
  async apiVerificationByBusinessmenCreditCode(params) {
    try {
      if (!params.businessmenCreditCode) {
        return system.getResult(null, `参数错误`);
      }
      return await this.verificationByBusinessmenCreditCode(this.trim(params.businessmenCreditCode));
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 发票红冲
   * @param {*} params 
   */
  async apiRedRushInvoice(params) {
    if (!params.id) {
      return system.getResult(null, `参数错误 发票ID不合法`);
    }
    try {
      let res = await this.redRushInvoice(params);
      return res;
    } catch (error) {
      return system.getResult(null, `参数错误 错误信息 ${error}`);
    }
  }

  /**
   * 交易数据(平台)
   * @param {*} params 
   */
  async apiStatTransData(params) {
    try {
      return await this.statTransData(params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 发票办理（平台）
   * @param {*} params
   */
  async apiStatBusinessData(params) {
    try {
      return await this.statBusinessData(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }


  //===========================================================================================

  /**
   * 插入发票
   * @param {*} params 
   */
  async saveInvoice(params) {
    try {
      //试算
      let val = await rule.dispatcher(params);
      if(val.data==-1){
        return system.getResult(-1,`系统错误 ${val.msg}`);
      }
      params.personalIncomeTax = this.trim(val.personalIncomeTax);
      params.additionalTax = this.trim(val.additionalTax);
      params.valueAddedTax = this.trim(val.valueAddedTax);
      params.serviceCharge = this.trim(val.serviceCharge);
      params.isPay = (params.isPay) ? 1 : 0;
      params.status = "1000";
      params.customerStatus = "1000";
      params.ruleCode = this.trim(params.ruleCode);
      params.ruleParams = JSON.stringify(params);

      await this.db.transaction(async (t) => {
        //插入发票申请单
        let _apply = await this.dao.create(params, t);
        //插入一条发票信息
        await this.invoiceDao.model.create({
          id: _apply.id,
          applyNo: _apply.applyNo,
          merchantId: _apply.merchantId,
          businessmenId: params.businessmenId,
          businessmenType: params.businessmenType,
          ruleCode: params.ruleCode,
          ruleParams: params.ruleParams
        }, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 发票办理(平台)
   * @param {*} params
   */
  async statBusinessData(params) {
    var result = {};
    var type = Number(params.type || 1);
    // 查 已完成订单，待分配订单，待审核订单，办理中订单
    var begin, end;
    // 取开始时间
    if (type == 1) {
      begin = moment().format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    } else if (type == 2) {
      begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    }

    // 先按照订单状态查
    var statMap = await this.dao.statByStatus(begin, end);

    // 已开具 1050
    result.completeCount = this.addStatCount(statMap, ['1050']);
    // 待申请审核 1000
    result.toApplyCount = this.addStatCount(statMap, ['1000']);
    // 待交付审核 1130 1140
    result.toAuditCount = this.addStatCount(statMap, ['1060']);
    // 办理中 "1030", "1050", "1060", "1080", "1300"
    result.handlingCount = this.addStatCount(statMap, ["1030", "1050", "1060", "1080", "1300"]);
    return system.getResultSuccess(result);
  }



  /**
   * 交易数据(平台)
   * @param {*} params
   */
  async statTransData(params) {
    try {
      var result = {
        invoiceCount: 0,
        serviceChange: 0,
      };
      var type = Number(params.type || 1);

      var begin, end;
      // 取开始时间
      if (type == 1) {
        begin = moment().format("YYYY-MM") + "-01 00:00:00";
      } else if (type == 2) {
        begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
      }

      // echart数据
      var days = [];
      var dayCounts = [];
      var priceCounts = [];

      // 处理查询业务
      if (type == 1 || type == 2) { // 取结束时间
        end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
        days = this.getDays(end);
        // 按天统计
        var dayMap = await this.dao.statDayByTime(begin, end);
        for (var day of days) {
          var ditem = dayMap[day] || {};
          dayCounts.push(ditem.invoiceCount || 0);
          priceCounts.push(system.f2y(ditem.serviceChange || 0));
        }
      } else {
        var monthMap = await this.dao.statMonthByTime(begin, end);
        var bm = monthMap.begin || "";
        var em = monthMap.end || "";
        if (bm && em) {
          // 开始月份-结束月份所有月份
          var curMonth = bm;
          while (true) {
            days.push(curMonth);
            if (curMonth == em) {
              break;
            }
            curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
          }
        }
        for (var day of days) {
          var ditem = monthMap[day] || {};
          dayCounts.push(ditem.invoiceCount || 0);
          priceCounts.push(system.f2y(ditem.serviceChange || 0));
        }
      }

      var invoiceApplyData = await this.dao.statInvoiceByTime(begin, end) || {};
      result.invoiceCount = invoiceApplyData.invoiceCount;
      result.serviceChange = system.f2y(invoiceApplyData.serviceChange);

      result.days = days;
      result.dayCounts = dayCounts;
      result.priceCounts = priceCounts;
      return system.getResultSuccess(result);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  /**
   * 红冲
   * @param {*} params 
   */
  async redRushInvoice(params) {
    try {
      let _apply = await this.dao.findById(params.id) || {};
      let invoice = await this.invoiceDao.findById(params.id) || {};
      //判断红冲状态
      if (invoice.redStatus == 2) {
        return system.getResult(null, `发票红冲中`);
      } else if (invoice.redStatus == 4) {
        return system.getResult(null, `红冲已红冲`);
      }

      let nowObj = {};
      nowObj.merchantId = this.trim(_apply.merchantId);
      nowObj.merchantName = this.trim(_apply.merchantName);
      nowObj.merchantCreditCode = this.trim(_apply.merchantCreditCode);
      nowObj.merchantAddr = this.trim(_apply.merchantAddr);
      nowObj.merchantMobile = this.trim(_apply.merchantMobile);
      nowObj.merchantBank = this.trim(_apply.merchantBank);
      nowObj.merchantAccount = this.trim(_apply.merchantAccount);
      nowObj.businessmenCreditCode = this.trim(_apply.businessmenCreditCode);
      nowObj.businessmenId = this.trim(_apply.businessmenId);
      nowObj.businessmenName = this.trim(_apply.businessmenName);
      nowObj.businessmenAddr = this.trim(_apply.businessmenAddr);
      nowObj.businessmenMobile = this.trim(_apply.businessmenMobile);
      nowObj.businessmenBank = this.trim(_apply.businessmenBank);
      nowObj.businessmenAccount = this.trim(_apply.businessmenAccount);
      nowObj.isBank = _apply.isBank ? 1 : 0;
      nowObj.taxAuthorities = this.trim(_apply.taxAuthorities);
      nowObj.type = this.trim(_apply.type);
      nowObj.invoiceAmount = this.trim(_apply.invoiceAmount);
      nowObj.statements = this.trim(_apply.statements);
      nowObj.contract = this.trim(_apply.contract);
      nowObj.invoiceTime = this.trim(_apply.invoiceTime);
      nowObj.settleImg = this.trim(_apply.settleImg);
      nowObj.applyNo = this.trim(_apply.applyNo);
      nowObj.invoiceConten = this.trim(_apply.invoiceConten);
      nowObj.personalIncomeTax = this.trim(_apply.personalIncomeTax);
      nowObj.additionalTax = this.trim(_apply.additionalTax);
      nowObj.valueAddedTax = this.trim(_apply.valueAddedTax);
      nowObj.serviceCharge = this.trim(_apply.serviceCharge);
      nowObj.applyMobile = this.trim(_apply.applyMobile);
      nowObj.parentId = this.trim(_apply.id);
      nowObj.status = this.trim("1000");
      nowObj.customerStatus = this.trim("1000");
      nowObj.payWay = this.trim(_apply.payWay);
      nowObj.payAccount = this.trim(_apply.payAccount);
      nowObj.mailAddr = this.trim(_apply.mailAddr);
      nowObj.mailMobile = this.trim(_apply.mailMobile);
      nowObj.mailTo = this.trim(_apply.mailTo);
      nowObj.remark = this.trim("");
      nowObj.delivererId = this.trim("");
      nowObj.isPay = 0;
      nowObj.businessmenType = this.trim(_apply.businessmenType);
      nowObj.ruleCode = this.trim(_apply.ruleCode);
      nowObj.ruleParams = this.trim(_apply.ruleParams);
      let res = await this.db.transaction(async (t) => {
        // 插入发票申请单
        let _nowObj = await this.dao.create(nowObj, t);
        // 插入一条发票信息
        await this.invoiceDao.create({
          id: _nowObj.id,
          applyNo: _nowObj.applyNo,
          merchantId: _nowObj.merchantId,
          red_status: '1',
          businessmenType : nowObj.businessmenType,
          ruleCode : nowObj.ruleCode,
          ruleParams : nowObj.ruleParams
        }, t);

        // 源发票改为红冲办理中
        var updfields = {
          redStatus: '2',
          id: _apply.id,
        }
        await this.invoiceDao.update(updfields, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `参数错误 错误信息 ${error}`);
    }
  }

  async getByApplyNo(params) {
    var merchantId = params.merchantId || params.merchant_id;
    var applyNo = params.applyNo;

    var item = await this.dao.getByApplyNo(merchantId, applyNo);
    if (item) {
      this.handleDate(item, ["created_at", "updated_at"], null, -8);
    }
    return system.getResultSuccess(item);
  }

  /**
   * 查询发票明细
   * @param {*} applyNo 
   * @param {*} merchantId
   */
  async queryInvoice(applyNo, merchantId, id) {
    try {
      let _apply;
      if (merchantId && applyNo) {
        _apply = await this.dao.model.findOne({
          where: {
            merchantId: merchantId,
            applyNo: applyNo
          },
          raw: true
        });
      } else if (id) {
        _apply = await this.dao.model.findOne({
          where: {
            id: this.trim(id)
          },
          raw: true
        });
      } else {
        _apply = null;
      }
      if (!_apply) {
        return system.getResult(null)
      }
      this.dao.setRowCodeName(_apply, "status");
      this.dao.setRowCodeName(_apply, "customerStatus");
      //查询平台审批内容
      let deliverer = await this.delivererDao.model.findOne({
        where: {
          id: _apply.delivererId
        },
        raw: true
      });
      _apply.deliverer = deliverer;
      //查询发票信息
      let invoice = await this.invoiceDao.model.findOne({
        where: {
          id: _apply.id
        },
        raw: true
      });
      this.dao.setRowCodeName(invoice, "status");
      //红冲关联
      let parentInvoice = await this.dao.model.findOne({
        where: {
          id: _apply.parentId
        },
        raw: true
      });
      this.dao.setRowCodeName(parentInvoice, "status");
      this.dao.setRowCodeName(parentInvoice, "customerStatus");
      _apply.invoice = invoice;
      _apply.deliverer = deliverer || {};
      _apply.parentInvoice = parentInvoice;

      this.handleDate(_apply.invoice, ["taxTime", "invoiceTime"], "YYYY-MM-DD");
      return system.getResult(_apply);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息：${error}`);
    }
  }
  /**
   * 发票撤回
   * @param {*} applyNo 
   * @param {*} merchantId
   * @param 
   */
  async cancelInvoice(applyNo, merchantId) {
    let _invoice = await this.dao.model.findOne({
      where: {
        applyNo: applyNo,
        merchantId: merchantId
      },
      attributes: ['id', 'status']
    });
    if (_invoice.status != this.invoiceStatus.unpay) {
      return system.getResult(null, `当前发票正在处理，不能撤回`);
    } else {
      _invoice.status = this.invoiceStatus.recall;
      try {
        let res = await _invoice.save();
        return system.getResult(res);
      } catch (error) {
        return system.getResult(null, `系统错误： ${error}`);
      }
    }
  }



  /**
   * 发票业务分配
   * @param {*} params
   * {
   *    id:""         //发票id
   *    nextStatus:"" //发票状态
   * } 
   */
  async assignment(params) {
    let _apply = await this.verification(params);
    try {
      let res;
      switch (params.nextStatus) {
        case "1010": //审核不通过
          res = await this.examine1000(params, _apply);
          break;
        case "1020": //待分配
          res = await this.examine1000(params, _apply);
          break;
        case "1030": //待处理
          res = await this.examine1030(params, _apply);
          break;
        case "1070": //审核通过
          res = await this.examine1070(params, _apply);
          break;
        case "1300": //审核失败
          res = await this.examine1300(params, _apply);
          break;
        case "1090": //已完成
          res = await this.examine1090(params, _apply);
          break;
        default:
          res = system.getResult(null, "action_type参数错误");
          break;
      }
      return res;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 第一次审核 
   * @param {*} params 
   * {
   *    id: xxx, //发票id
   *    isPay:1, //时候付款
   *    nextStatus:1020,//发票状态
   *    remark:""//发票标注
   * }
   */
  async examine1000(params, _apply) {
    if (Number(params.isPay) != 1) {
      return system.getResult(null, `参数错误 请核对付款信息`);
    }
    params.nextStatus = this.trim(params.nextStatus);
    params.remark = this.trim(params.remark);
    _apply.status = params.nextStatus;
    _apply.remark = params.remark;
    _apply.isPay = Number(params.isPay);
    if (params.nextStatus == "1010") {
      _apply.customerStatus = "1010";
    }
    try {
      let res = await _apply.save();
      if (_apply.parentId && params.nextStatus == "1010") {
        await this.invoiceDao.update({ id: _apply.parentId, redStatus: '3' });
      }
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 待处理  (当前状态待分配或者是审核为通过)
   * @param {*} params 
   * {
   *    id: xxx, //发票id
   *    delivererId:1, //交付商
   *    nextStatus:examine1020,//发票状态
   *    delivererName:""//交付商名称
   *    delivererAmount:"" //分成
   * }
   */
  async examine1030(params, _apply) {
    if (!params.id || !params.delivererName) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
    await this.db.transaction(async (t) => {
      let _deliverer = await this.delivererDao.create({
        invoiceId: _apply.id,
        applyNo: _apply.applyNo,
        merchantId: _apply.merchantId,
        delivererId: this.trim(params.delivererId),
        delivererName: this.trim(params.delivererName),
        delivererAmount: Number(this.trim(params.delivererAmount))
      }, t);
      let applyData = {};
      applyData.status = this.trim(params.nextStatus);
      applyData.customerStatus = this.trim(params.nextStatus);
      applyData.delivererId = this.trim(_deliverer.id);
      applyData.id = this.trim(params.id);
      //更新申请发票内容
      await this.dao.update(applyData, t);
      //更改发票状态
      let invoiceData = {};
      invoiceData.status = this.trim(params.nextStatus);
      invoiceData.id = this.trim(params.id);
      await this.invoiceDao.update(invoiceData, t);
    }).catch(error => {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    });
    return system.getResultSuccess();
  }

  /**
   * 第二次审核 
   * @param {*} params 
   * {
   *    id: xxx, //发票id
   *    auditContent:1, //审核备注
   *    nextStatus:1070,//发票状态
   *    delivererContent:""//发票内容
   *    mailAddr:"",    //邮寄地址
   *    mailMobile:"",  //邮寄电话
   *    mailTo:"",      //邮寄人
   * }
   */
  async examine1070(params, _apply) {
    let delivererData = {},
      applyData = {},
      invoiceData = {};
    let _deliverer = await this.delivererDao.findOne({
      id: _apply.delivererId
    });

    delivererData.auditContent = this.trim(params.auditContent);
    delivererData.delivererContent = this.trim(params.delivererContent);
    delivererData.mailAddr = this.trim(params.mailAddr);
    delivererData.mailMobile = this.trim(params.mailMobile);
    delivererData.mailTo = this.trim(params.mailTo);
    delivererData.mailEmail = this.trim(params.mailEmail);
    delivererData.id = this.trim(_deliverer.id);
    applyData.status = this.trim(params.nextStatus);
    applyData.id = this.trim(params.id);
    invoiceData.status = this.trim(params.nextStatus);
    invoiceData.id = this.trim(params.id);

    await this.db.transaction(async (t) => {
      //更新deliverer信息
      await this.delivererDao.update(delivererData, t);
      //更新 申请单和发票单
      await this.dao.update(applyData, t);
      await this.invoiceDao.update(invoiceData, t);

      if (_apply.parentId) {
        await this.invoiceDao.update({ id: _apply.parentId, redStatus: '4' }, t);
      }

    }).catch(error => {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    });
    return system.getResultSuccess();
  }

  /**
   * 第二次审核失败
   * @param {*} params 
   */
  async examine1300(params) {
    let _apply = await this.dao.findOne({
      id: this.trim(params.id)
    });
    if (!_apply) {
      return system.getResult(null, `发票不存在，请核对发票ID`);
    }
    let _deliverer = await this.delivererDao.model.findOne({
      where: {
        id: _apply.delivererId
      }
    });
    if (!_deliverer) {
      return system.getResult(null, `交付商不存在，请联系管理员`);
    }
    await this.db.transaction(async (t) => {
      //更新 申请单和发票单
      await this.dao.update({
        status: "1300",
        id: _apply.id
      }, t);
      await this.invoiceDao.update({
        status: "1300",
        id: _apply.id
      }, t);

      if (_deliverer.id) {
        //提交审核信息
        await this.delivererDao.update({
          auditContent: this.trim(auditContent),
          id: _deliverer.id
        });
      }
    }).catch(error => {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    });
    return system.getResultSuccess();
  }
  /**
   * 平台更新 已完成状态
   * @param {*} params 
   * @param {*} _apply 
   */
  async examine1090(params, _apply) {
    let applyData = {};

    applyData.status = this.trim(params.nextStatus);
    applyData.customerStatus = this.trim(params.nextStatus);
    applyData.id = this.trim(params.id);

    // invoiceData.status = this.trim(params.nextStatus);
    // invoiceData.id=this.trim(params.id);

    await this.db.transaction(async (t) => {
      //更新 申请单和发票单
      await this.dao.update(applyData, t);
      // await this.invoiceDao.update(invoiceData,t);
    }).catch(error => {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    });
    return system.getResultSuccess();
  }

  /**
   * 检查状态是否正确
   * @param {*} params 
   * {
   *    id:xxx  //发票id
   *    nextStatus:xxx  //发票状态
   * }
   */
  async verification(params) {
    let _apply = await this.dao.findOne({
      id: this.trim(params.id)
    });
    if (!_apply) {
      return system.getResult(null, `此发票不存在`);
    }
    //获取当前状态 的对象
    let _status = this.invoiceStatus[_apply.status];
    //如果不符合状态则退出
    if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
      return _apply;
    }
    if (!_status && _status.next != params.nextStatus) {
      let name = this.invoiceStatus[this.invoiceStatus[_apply.status].next].name;
      return system.getResult(null, `更新状态错误，提示：当前状态的下一个状态是 ${name}`);
    }
    return _apply;
  }

  /**
   * 发票申请列表查询(平台)
   * @param {*} params 
   * @param applyNo   发票的申请编号
   * @param invoiceTime 发票的申请时间
   * @param type      发票的类型
   * @param status    业务进度
   */
  async queryApplyInvoices(params) {
    let where = {};
    if (this.trim(params.applyNo)) {
      where.applyNo = this.trim(params.applyNo);
    }
    if (this.trim(params.businessmenCreditCode)) {
      where.businessmenCreditCode = this.trim(params.businessmenCreditCode);
    }
    if (this.trim(params.invoiceTime)) {
      where.invoiceTime = {
        [this.db.Op.gte]: this.trim(params.invoiceTime)
      }
    }
    if (this.trim(params.type)) {
      where.type = this.trim(params.type);
    }
    if (this.trim(params.status)) {
      where.status = this.trim(params.status);
    }

    let pageIndex = params.pageIndex || 1;
    let pageSize = params.pageSize || 10;
    let orderObj = [
      // ['updatedAt', 'desc'],
      ['id', 'desc']
    ];

    try {
      let _apply = await this.dao.getPageList(pageIndex, pageSize, where, orderObj, null, null);
      for (let item of _apply.rows) {
        let _deliverer = await this.delivererDao.model.findOne({
          // where: {
          //   delivererId: item.delivererId
          // },
          attributes: ['delivererName']
        });
        if (_deliverer) {
          item.delivererName = _deliverer.delivererName;
        } else {
          item.delivererName = "";
        }
        if (item.type == "10") {
          item.type = "普通发票";
        } else if (item.type == "20") {
          item.type = "增值税专用发票";
        } else if (item.type == "30") {
          item.type = "电子发票";
        } else {
          item.type = "";
        }
        let _invoice = await this.invoiceDao.model.findOne({
          where: {
            id: item.id
          },
          attributes: ['status', 'invoiceImg']
        });
        if (_invoice.status) {
          this.dao.setRowCodeName(_invoice, "status");
        } else {
          _invoice.status = "";
        }
        item.invoiceImg = this.trim(_invoice.invoiceImg);
        item.delivererStatus = _invoice.statusName;
        //处理时间
        this.handleDate(item, ["invoiceTime"], null, -8);
        this.dao.setRowCodeName(item, "status");
        item.isPay = item.isPay == 1 ? '已付款' : '未付款';
      }
      return system.getResult(_apply);
    } catch (error) {
      return system.getResult(`系统错误 错误信息 ${error}`);
    }
  }
  /**
   * 列举所有日期
   * @param {*} end 
   */
  getDays(end) {
    var days = [];
    var month = moment(end).format("YYYY-MM");
    var endDay = Number(moment(end).format("DD"));
    for (var i = 1; i <= endDay; i++) {
      if (i < 10) {
        days.push(month + "-0" + i);
      } else {
        days.push(month + "-" + i);
      }
    }
    return days;
  }

  addStatCount(statusMap, statuses) {
    var count = 0;
    if (!statuses) {
      return count;
    }

    for (var status of statuses) {
      count = count + Number(statusMap[status] || 0);
    }
    return count;
  }

  //查询发票状态  只有在状态为 '1000','0090' 或者信息不存在的情况下 验证成功 参考 applySve.verificationByBusinessmenCreditCode接口
  async verificationInvoiceStatus(businessmenType, businessmenId, businessmenCreditCode) {
    try {
      let condition = {
        businessmenType: businessmenType,
        businessmenId: businessmenId,
        status: {
          [this.db.Op.in]: ['1000', '0090']
        }
      };
      if (businessmenCreditCode) {
        condition.businessmenCreditCode = businessmenCreditCode;
      }
      let invoices = await this.dao.model.findAll({
        where: condition,
        attributes: ["id", "status"]
      });
      if (!invoices) { return false; }
      for (let item of invoices) {
        if (!item) { continue; }
        if (item['status'] != "1000" || item['status'] != "0090") {
          return false;
        }
      }
      return true;
    } catch (error) {
      return false;
    }
  }

    /** 
   * 累计不含税价
   * @param {*} businessmenId  商户id 
   * @param {*} taxIncPriRat 不含税价百分比
   * @param {*} invoiceAmount 发票总额
   * @param {*} type          计算类型 1：个税 2：增值税
   * @param {*} valCalWay     增值税计算类型 1：月 2：季度 3:年
   * @param {*} perCalWay     增值税计算类型 1：月 2：季度 3:年
   * @param {*} invoiceTime   格式 YYYY-MM-DD hh:mm:ss
   */
  async calAccumulatedPriceExcludingTax(businessmenId,businessmenType, businessmenCreditCode, taxIncPriRat, invoiceAmount, type, valCalWay, perCalWay, invoiceTime) {
    try {
      let now = moment(invoiceTime),startTime, attribute;
      if (type === 1) { //个税
        attribute = `invoiceAmount`;
        if (perCalWay === 3) { //按照年
          startTime = `${now.get('year')}-01-01 00:00:00`;
        } else if (perCalWay === 2) { //按照季度
          let quarter = now.quarter();
          if (1 == quarter) { //第一季度
            startTime = `${now.get('year')}-01-01 00:00:00`;
          } else if (2 == quarter) {
            startTime = `${now.get('year')}-04-01 00:00:00`;
          } else if (3 == quarter) {
            startTime = `${now.get('year')}-07-01 00:00:00`;
          } else {
            startTime = `${now.get('year')}-10-01 00:00:00`;
          }
        } else { //按照月
          let _month = now.month() < 10 ? "0" + now.month() : now.month();
          startTime = `${now.get('year')}-${_month}-01 00:00:00`;
        }
      } else {
        attribute = `valueAddedTax`;
        if (valCalWay === 1) { //月
          startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
        } else if (valCalWay === 2) { //季度
          let quarter = now.quarter();
          if (1 == quarter) { //第一季度
            startTime = `${now.get('year')}-01-01 00:00:00`;
          } else if (2 == quarter) {
            startTime = `${now.get('year')}-04-01 00:00:00`;
          } else if (3 == quarter) {
            startTime = `${now.get('year')}-07-01 00:00:00`;
          } else {
            startTime = `${now.get('year')}-10-01 00:00:00`;
          }
        } else { //年
          startTime = `${now.get('year')}-01-01 00:00:00`;
        }
      }
      console.log("本年度开始的时间：" + startTime + "  至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
      let condition = {
        businessmenId: businessmenId,
        businessmenType:businessmenType,
        status: {
          [this.db.Op.in]: ['1020', '1030', '1040', '1050', '1060', '1070', '1080', '1090', '1100', '1200', '1300']
        },
        invoiceTime: {
          [this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
        }
      };
      if(businessmenCreditCode){
        condition.businessmenCreditCode=businessmenCreditCode;
      }

      let beforeAmount = await this.dao.model.sum(attribute, {
        where: condition
      });
      beforeAmount = isNaN(beforeAmount) ? 0 : beforeAmount;
      let res = new Decimal(invoiceAmount).plus(beforeAmount).div(Decimal.add(1, taxIncPriRat)).toFixed(2);
      console.log("当前累计金额 ：" + res);
      return res;
    } catch (error) {
      console.log(error);
      return system.getResult(-1,`系统错误 错误信息 ${error}`);
    }
  }

    /**
   * 计算累计税值
   * @param {*} businessmenId 
   * @param {*} type          计算类型 1：个税 2：增值税
   * @param {*} valCalWay     增值税计算类型 1：月 2：季度
   * 
   */
  async calCumulativeProfit(businessmenId,businessmenType, type, valCalWay) {
    let now = moment(),
      startTime, attribute;
    if (type == 1) {
      attribute = `personalIncomeTax`;
      startTime = `${now.get('year')}-01-01 00:00:00`;
    } else {
      attribute = `valueAddedTax`;
      if (valCalWay === 1) { //月
        startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
      } else { //季度
        let quarter = now.quarter();
        if (1 == quarter) { //第一季度
          startTime = `${now.get('year')}-01-01 00:00:00`;
        } else if (2 == quarter) {
          startTime = `${now.get('year')}-04-01 00:00:00`;
        } else if (3 == quarter) {
          startTime = `${now.get('year')}-07-01 00:00:00`;
        } else {
          startTime = `${now.get('year')}-10-01 00:00:00`;
        }
      }
    }
    console.log("本年度开始的时间：" + startTime + "  至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
    let cumulativeProfit = await this.dao.model.sum(attribute, {
      where: {
        businessmenId: businessmenId,
        businessmenType: businessmenType,
        status: this.invoiceStatus.auditPass,
        invoiceTime: {
          [this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
        }
      }
    });
    return cumulativeProfit || 0;
  }
}
module.exports = ApplyService;