var system = require("../../../system")
const CtlBase = require("../../ctlms.base");
const validation = system.getObject("util.validation");

class InvoiceCtl extends CtlBase {
  constructor() {
    super();
    this.orderSve = system.getObject("service.saas.orderSve");
    this.tradeSve = system.getObject("service.trade.tradeSve");
    this.invoiceSve = system.getObject("service.saas.invoiceSve");
    this.merchantSve = system.getObject("service.saas.merchantSve");

    this.redisClient = system.getObject("util.redisClient");
  }

  // 注册订单列表
  async orderPage(params, pobj2, req) {
    try {
      params.unInvoice = 1;
      params.handle_statuses = ['20', '30'];
      this.doTimeCondition(params, ["createBegin", "createEnd"]);
      return await this.orderSve.page(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 平台交易列表
  async platformPage(params, pobj2, req) {
    try {
      params.unInvoice = 1;
      params.order_type = "10";
      params.trade_status = "00";
      this.doTimeCondition(params, ["createBegin", "createEnd"]);
      return await this.tradeSve.itemPage(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 商户交易列表
  async merchantPage(params, pobj2, req) {
    try {
      params.unInvoice = 1;
      params.order_type = "20";
      params.trade_status = "00";
      this.doTimeCondition(params, ["createBegin", "createEnd"]);
      return await this.tradeSve.itemPage(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  //发票列表
  async invoicePage(params, pobj2, req) {
    try {
      let rs = await this.invoiceSve.merchantinvoicePage(params);
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  // 发票申请
  async apply(params, pobj2, req) {
    try {
      let fee_type = this.trim(params.fee_type);
      if (fee_type == "00") {

      } else if (fee_type == "10") {
        return await this.apply10(params, pobj2, req);
      } else if (fee_type == "20") {
      } else {
        return system.getResult(null, "费用类型错误");
      }
      return await this.orderSve.page(params);
    } catch (error) {
      let msg = error.message;
      if (msg.startsWith("bpo-validation-error:")) {
        return system.getResult(null, msg.replace("bpo-validation-error:", ""));
      }
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 功能2开票
  async apply10(params, pobj2, req) {
    validation.check(params, 'data_ids', {name: "交易信息", arr_require: true});

    let title = await this.merchantSve.title(params) || {};
    title = title.data || {};
    if (!title.merchant_name || !title.merchant_credit_code || !title.merchant_addr
      || !title.merchant_mobile || !title.merchant_bank || !title.merchant_account) {
      return system.getResult(null, "开票抬头不完整，请联系平台");
    }

    let addr = await this.merchantSve.addr(params) || {};
    addr = addr.data || {};
    if (!addr || !addr.mail_to || !addr.mail_addr || !addr.mail_mobile) {
      return system.getResult(null, "开票邮寄不完整");
    }

    let trades = await this.tradeSve.byIds({
      ids: params.data_ids,
      saas_merchant_id: params.saas_merchant_id,
      attrs: "id",
      trade_statuses: ['00'],
      unInvoice: true,
    }) || [];
    if (trades.data.length != params.data_ids.length) {
      return system.getResult(null, "交易数据选择有误，请重新搜索后选择");
    }

    let info = await this.merchantSve.signInfo({id: params.saas_merchant_id}) || {};
    info = info.data || {};
    if (!info.main_trade || !info.main_trade.id) {
      return system.getResult(null, "商户未设置转账交易主体，请联系平台进行设置、");
    }
    let main = info.main_trade || {};
    let batch_no = await this.redisClient.genrateId("invoice_batch_no");
    let apply_no = await this.redisClient.genrateId("invoice_apply_no");
    let data = {
      saas_id: params.saas_id,
      saas_merchant_id: params.saas_merchant_id,
      parent_id: "",
      owner_type: "00",
      status: "1000",
      batch_no: batch_no,
      apply_no: apply_no,
      fee_type: this.trim(params.fee_type),
      invoice_type: this.trim(params.invoice_type),

      from_name: main.name,
      from_credit_code: main.credit_code,
      from_mobile: main.mobile,
      from_addr: main.addr,
      from_bank: main.bank_name,
      from_account: main.bank_account,

      to_name: this.trim(title.merchant_name),
      to_credit_code: this.trim(title.merchant_credit_code),
      to_addr: this.trim(title.merchant_addr),
      to_mobile: this.trim(title.merchant_mobile),
      to_bank: this.trim(title.merchant_bank),
      to_account: this.trim(title.merchant_account),

      mail_addr: this.trim(addr.mail_addr),
      mail_mobile: this.trim(addr.mail_mobile),
      mail_to: this.trim(addr.mail_to),
    };

    data = await this.invoiceSve.applySave(data);
    console.log(data);
    data = data.data;
    if (!data || !data.id) {
      return system.getResult(null, "网络异常，发票申请失败");
    }

    let rs = await this.tradeSve.updateInvoice({ids: params.data_ids, saas_invoice_id: data.id});
    console.log(rs);

    console.log(data);
    return system.getResultSuccess(data);
  }

  //发票申请列表
  async merchantinvoiceapplyPage(params, pobj2, req) {
    try {
      params.currentPage = Number(params.currentPage || 1);
      params.pageSize = Number(params.pageSize || 1);
      let rs = await this.invoiceSve.merchantinvoiceapplyPage(params);
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 发票账单列表
   * @param {*} params 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async invoiceOrder(params, pobj2, req){
    if(!params.id){
      return system.getResult(null,`发票ID 不能为空`);
    }
    try {
      return await this.invoiceSve.invoiceOrder(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }
}

module.exports = InvoiceCtl;
