const system = require("../../../system");
const Dao = require("../../dao.base");
const moment = require("moment");
class InvoiceDao extends Dao {
  constructor() {
    super(Dao.getModelName(InvoiceDao));
    this.statusMap = {
      "0090": "未付款",
      "1000": "待审核",
      "1010": "审核不通过",
      "1020": "待分配",
      "1030": "待处理",
      "1040": "交付商关闭",
      "1050": "已开具",
      "1060": "待审核",
      "1070": "审核通过",
      "1080": "已邮寄",
      "1090": "完成",
      "1100": "发票撤回",
      "1200": "红冲",
      "1300": "审核失败(平台第二次审核)"
    };

    this.customerMap = {
      "0090": "未付款",
      "1000": "待审核",
      "1030": "待处理",
      "1050": "已开具",
      "1090": "完成"
    };

    this.deliverMap = {
      "1030": "待处理",
      "1040": "交付商关闭",
      "1050": "已开具",
      "1060": "待审核",
      "1080": "已邮寄",
      "1300": "审核失败(平台第二次审核)"
    }

    this.redStatusMap = {
      "1": "未红冲",
      "2": "红冲中",
      "3": "红冲失败",
      "4": "红冲成功",
    };

    this.red_statusMap = this.redStatusMap;
  }

  async countByParams(params) {
    var sql = [];
    sql.push("SELECT");
    sql.push("COUNT(1) as total");
    sql.push("FROM `invoice` t1");
    sql.push("INNER JOIN `invoice_apply` t2 ON t1.`id` = t2.`id`");
    sql.push("WHERE 1 = 1 and t2.status in('1070','1080','1090')");

    this.setCondition(params, sql);

    var counts = await this.customQuery(sql.join(" "), params);
    if(!counts || counts.length == 0) {
      return 0;
    }
    return counts[0].total || 0;
  }

  async pageByParams(params, startRow, pageSize) {
    var sql = [];
    sql.push("SELECT");
    sql.push("t1.*");
    sql.push("FROM `invoice` t1");
    sql.push("INNER JOIN `invoice_apply` t2 ON t1.`id` = t2.`id`");
    sql.push("WHERE 1 = 1 ");

    this.setCondition(params, sql);

    sql.push("ORDER BY id DESC");
    sql.push("LIMIT :startRow, :pageSize");
    params.startRow = startRow || 0;
    params.pageSize = pageSize || 10; 
    return await this.customQuery(sql.join(" "), params);
  }

  setCondition(params, sql) {
    var complateTax = params.complateTax;
    if (complateTax != "-1") {
      params.complateTax = Number(complateTax);
      sql.push("AND t1.`complate_tax` = :complateTax");
    }

    // invoiceTimeBegin   2019-01-01  2019-01-01 00:00:00
    // invoiceTimeEnd     2019-11-01  2019-11-01 23:59:59
    if(params.invoiceTimeBegin) {
      sql.push("AND t1.`invoice_time` >= :invoiceTimeBegin");
    }
    if(params.invoiceTimeEnd) {
      sql.push("AND t1.`invoice_time` <= :invoiceTimeEnd");
    }
    if(params.invoiceTime){
      sql.push("AND t1.`invoice_time` >= :invoiceTime");
    }

    if(params.applyNo) {
      sql.push("AND t2.`apply_no` = :applyNo");
    }

    if(params.redStatus) {
      sql.push("AND t1.`red_status` = :redStatus");
    }

    if (params.type) {
      sql.push("AND t2.`type` = :type");
    }
    if(params.statuses && params.statuses.length > 0){
      sql.push("AND t2.`status` in (:statuses)");
    }
  }
}
module.exports = InvoiceDao;