const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class InvoiceService extends ServiceBase {
  constructor() {
    super("invoice", ServiceBase.getDaoName(InvoiceService));
  }

  //获取所有发票信息 (条件分页)
  async invoices(params) {
    if (!params.uid) {
      return system.getResultFail(-1, '用户id不能为空');
    } else {
      var currentPage = Number(params.currentPage || 1);
      var pageSize = Number(params.pageSize || 10);
      var where = {};
      if (params.type && (params.type == 'electronic' || params.type == 'paperQuality')) {
        params.type = this.trim(params.type);
        where.type = params.type;
      }
      if (params.id) {
        where.id = this.trim(params.id);
      }
      where.uid = params.uid;
      var orderby = [
        ["id", 'desc']
      ];
      let res = await this.getPageList(currentPage, pageSize, where, orderby);

      if (res && res.rows) {
        for (var row of res.rows) {
          this.handleDate(row, ["created_at", "updated_at"], null, -8);
          await this.transfield(row);
        }
      }
      return system.getResultSuccess(res);
    }
  }

  async transfield(row) {
    if (!row) {
      return;
    }
    row.creditCode = this.trim(row.merchantCode);
    row.name  = this.trim(row.merchantName);
    row.legalName = this.trim(row.corporations);
    row.legalIdcard = this.trim(row.identityCode);
    row.isBank = this.trim(row.bank);
  }

  //创建发票
  async create(invoices) {
    console.log(invoices);
    if (invoices && invoices.length > 0) {
      console.log("要插入的数据数组：" + JSON.stringify(invoices));
      try {
        let res = await this.dao.bulkCreate(invoices);
        if (res) {
          return system.getResultSuccess(res)
        } else {
          return system.getResultFail();
        }
      } catch (error) {
        console.log(error);
        return system.getResultFail(-1, `插入失败：失败信息：${JSON.stringify(error)}`);
      }
    } else {
      return system.getResultFail(-1, `参数错误`);
    }

  }

}
module.exports = InvoiceService;