const ServiceBase = require("../../sve.base");
const system = require("../../../system");
const moment = require('moment');
/**
 * 平台提交的信息
 */
class IinvoicedeliverService extends ServiceBase {
  constructor() {
    super("invoice", ServiceBase.getDaoName(IinvoicedeliverService));

    this.iinvoiceDao = system.getObject("db.invoice.iinvoiceDao");
    this.iinvoiceprocessDao = system.getObject("db.invoice.iinvoiceprocessDao");
    this.iinvoiceinforegDao = system.getObject("db.invoice.iinvoiceinforegDao");

    this.iproductDao = system.getObject("db.product.iproductDao");
    this.iprocessDao = system.getObject("db.product.iprocessDao");
    this.iproductprocessDao = system.getObject("db.product.iproductprocessDao");

  }

  async invoicePage(params) {
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);
    params.startRow = Number((params.currentPage - 1) * params.pageSize);

    let deliver_id = params.deliver_id;

    let total = await this.dao.countByParams(params);
    if (total == 0) {
      return system.getResult({ count: 0, rows: [] });
    }

    let list = await this.dao.pageByParams(params);
    if (list) {
      for (var item of list) {
        if (item.red_status == '1') {
          // 1为红冲 2已红冲 3 红冲中
          item.red_status_name ="未红冲";
        } else if (item.red_status == '2') {
          item.red_status_name ="已红冲";
        } else if (item.red_status == '3') {
          item.red_status_name ="红冲中";
        }
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
        this.handleDate(item, ['invoice_time', 'apply_time'], 'YYYY-MM-DD');
      }
      await this.setStatus(list);
      await this.setProduct(list);
    }
    return system.getResultSuccess({ count: total, rows: list });
  }

  /**
   * 格式化产品
   * @param {*} list
   */
  async setProduct(list) {
    let productIdList = [];
    for (let item of list) {
      if (item.product_id) {
        productIdList.push(item.product_id);
      }
    }
    let productMap = await this.iproductDao.mapByIds(productIdList);
    for (let item of list) {
      item.oproduct = productMap[item.product_id] || {}
    }
  }

  /**
   * 处理状态数据
   * @param list
   * @returns {Promise<void>}
   */
  async setStatus(list) {
    let ids = [];
    let statuses = [];
    for (let item of list) {
      ids.push(item.id);
      statuses.push(item.status);
    }

    let map = await this.iinvoiceprocessDao.mapByInvoiceIdsAndStatus(ids, statuses);
    for (let item of list) {
      let key = item.id + "_" + item.status;
      let v = map[key] || {};
      item.status_name = v.name;
      item.name1 = v.name1;
      item.name2 = v.name2;
      item.name3 = v.name3;
      item.name4 = v.name4;
      item.next_status = JSON.parse(v.next_status || "[]");
    }
    console.log(list);
  }
}
module.exports = IinvoicedeliverService;