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 tradePage(params, pobj2, req) {
    try {
      params.unInvoice = 1;
      params.order_type = params.fee_type;
      params.trade_status = "00";
      this.doTimeCondition(params, ["createBegin", "createEnd"]);
      return await this.tradeSve.itemPage(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  // 交易列表
  async platformPage(params, pobj2, req) {
    try {
      if (["00", "10", "20"].indexOf(params.fee_type) == -1) {
        return system.getResultSuccess({count:0, rows:[], fee_type: params.fee_type});
      }
      if(params.fee_type == "00") {
        return this.orderPage(params, pobj2, req);
      } else {
        return this.tradePage(params, pobj2, req);
      }
    } 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") {
        return await this.apply00(params, pobj2, req);
      } 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);
  }

  // 功能3开票
  async apply00(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 orders = await this.orderSve.byIds({
        ids: params.data_ids,
        saas_merchant_id: params.saas_merchant_id,
        attrs: "id,price",
        handle_status: ['20','30'],
        unInvoice: true,
    }) || [];
    if (orders.data.length != params.data_ids.length) {
      return system.getResult(null, "订单数据选择有误，请重新搜索后选择");
    }
    let invoice_amount = 0;
    for(let item of orders.data){
      invoice_amount = invoice_amount + Number(item.price || 0);
    }

    let info = await this.merchantSve.signInfo({id: params.saas_merchant_id}) || {};
    // service_tax
    info = info.data || {};
    if (!info.main) {
      return system.getResult(null, "商户未设置转账交易主体，请联系平台进行设置、");
    }
    let main = info.main || {};
    let batch_no = await this.redisClient.genrateId("invoice_batch_no");
    let apply_no = batch_no;
    let service_tax = parseFloat((Number(invoice_amount) * Number(info.invoice_service_rate) / 100).toFixed(2));
    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),

      invoice_amount:invoice_amount,
      service_tax:service_tax,

    };

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

    let rs = await this.orderSve.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,`系统错误`);
    }
  }

  // 功能1 确定个体户开票
  async confirmInvoice(params, pobj2, req) {
    let invoice_type = params.invoice_type;
    let msg = error.message;
    if (msg.startsWith("bpo-validation-error:")) {
      return system.getResult(null, msg.replace("bpo-validation-error:", ""));
    }
    return system.getResult(null, `系统错误 错误信息 ${error}`);
    try {
      return await this.invoiceSve.invoiceOrder(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }

  }


  async buildTradeInvoice(params) {
    let invoiceId = params.id;
    let invoice_type = params.invoice_type;
    // 查交易
    let items = await this.tradeSve.itemByInvoiceId({saas_invoice_id: invoiceId});
    items = items.data;
    if (!items || items.length == 0) {
      return system.getResult(null, "该发票缺少交易信息，请联系平台查看原因");
    }
    let bmMap = {};
    let creditCodes = [];
    for (let item of items) {
      let creditCode = item.credit_code;
      let list = bmMap[creditCode] || [];
      list.push(item);
      bmMap[creditCode] = list;
      creditCodes.push(creditCode);
    }
    let businessmenMap = await this.orderSve.mapByCreditCodes({creditCodes: creditCodes});
    businessmenMap = businessmenMap.data;

    let invoiceList = [];
    let calcParams = [];

    for (let creditCode in bmMap) {
      let businessmen = businessmenMap[creditCode];
      let itemList = bmMap[creditCode];
      let amount = 0;
      for (let item of itemList) {
        amount = amount + Number(item.amt || 0);
      }
      calcParams.push({
        "credit_code": creditCode,
        "invoiced_time": moment().format("YYYY-MM-DD hh:mm:ss"),
        "invoice_type": invoice_type,
        "invoice_amount": amount
      });

      // TODO 总统计算 end
      invoiceList.push({
        "name": businessmen.name,
        "credit_code": creditCode,
        "is_bank": businessmen.isBank,
        "is_bank_name": businessmen.isBank ? "已开户" : "未开户",
        "invoice_amount": system.y2f(amount),
        "personal_invoice_tax": 0,
        "additional_tax": 0,
        "service_tax": 0,
        "value_added_tax": 0,
        "unit": "",
        "quantity": "",
        "price": "",
        "remark": ""
      });
    }

    let additional_tax_total = 0;
    let personal_invoice_tax_total = 0;
    let value_added_tax_total = 0;
    let service_tax_total = 0;

    // TODO 总统计算 begin
    // 计算税金
    try {
      let url = settings.deliverSysApi().calcInvoice;
      let res = await axios({
        method: 'post',
        url: url,
        data: calcParams
      });
      if(!res || !res.data || res.data.status !=0 || res.data.data.length==0){
        return system.getResult(null,`试算错误`);
      }

      let calcList = res.data.data;
      let calcMap = {};
      let errors = [];
      for (let c of calcList) {
        calcMap[c.credit_code] = c;
        if (c.error) {
          errors.push(`${c.msg}【${c.credit_code}】`);
        }
      }

      if (errors.length > 0) {
        return system.getResult(null, errors.join("、"));
      }

      for (let invoice of invoiceList) {
        let invoiceCalc = calcMap[invoice.credit_code];
        additional_tax_total = additional_tax_total + Number(invoiceCalc.additional_tax);
        personal_invoice_tax_total = personal_invoice_tax_total + Number(invoiceCalc.personal_invoice_tax);
        value_added_tax_total = value_added_tax_total + Number(invoiceCalc.value_added_tax);
        service_tax_total = service_tax_total + Number(invoiceCalc.service_amount);

        invoice.personal_invoice_tax = system.toFloat(Number(invoiceCalc.personal_invoice_tax));
        invoice.additional_tax = system.toFloat(Number(invoiceCalc.additional_tax));
        invoice.service_tax = system.toFloat(Number(invoiceCalc.service_amount));
        invoice.value_added_tax = system.toFloat(Number(invoiceCalc.value_added_tax));
      }

      return system.getResultSuccess({
        tax: {
          additional_tax_total: system.toFloat(additional_tax_total),
          personal_invoice_tax_total: system.toFloat(personal_invoice_tax_total),
          value_added_tax_total: system.toFloat(value_added_tax_total),
          service_tax_total: system.toFloat(service_tax_total),
        },
        invoiceList: invoiceList
      });
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }
}

module.exports = InvoiceCtl;
