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 { count: 0, rows: [] };
    }

    let list = await this.dao.pageByParams(params);
    if (list) {
      for (var item of list) {
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
      }
      await this.setStatus(list);
      await this.setProduct(list);
    }
    return { 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.next_status = JSON.parse(v.next_status || "[]");
    }
    console.log(list);
  }
}
module.exports = IinvoicedeliverService;