var system = require("../../../system")
const CtlBase = require("../../ctlms.base");
const validation = system.getObject("util.validation");
var moment = require('moment');
const settings = require("../../../../config/settings");
const axios = require("axios");

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

  // 审核
  async audit(params, pobj2, req) {
    try {
      params.id = this.trim(params.id);
      let saasInvoiceApply = await this.saasinvoiceSve.getSaasInvoiceById({id:params.id,attrs:"id,fee_type,data_ids"});
      saasInvoiceApply = saasInvoiceApply.status==0?saasInvoiceApply.data:null;
      if (!params.id || !saasInvoiceApply ||  !saasInvoiceApply.id) {
        return system.getResult(null, "发票申请不存在");
      }
      params.remark = this.trim(params.remark);
      if (!params.remark) {
        return system.getResult(null, "请填写审核备注");
      }
      params.status = Number(params.status || 0) ? "1010" : "1020";

      let rs = await this.saasinvoiceSve.audit(params);
      if (rs.status === 0  &&  params.status == "1020") {
        let data_ids = saasInvoiceApply.data_ids;
        if(!data_ids || data_ids.split(',').length==0){
          return rs;
        }
        let fee_type = saasInvoiceApply.fee_type;
        if(fee_type=="10" || fee_type=="20"){//交易流水
          // await this.tradeSve.cancelInvoice({saas_invoice_id: params.id});
          await this.tradeSve.cancelInvoiceByDataIds({data_ids: data_ids.split(',')});
        }else if(fee_type=="00"){  //注册订单
          await this.orderSve.cancelInvoiceByDataIds({data_ids: data_ids.split(',')});
        }else{
          return rs;
        }
      }
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 发票开具
  // 审核
  async makeout(params, pobj2, req) {
    try {
      validation.check(params, 'invoice_no', {name: "发票代码", is_require: true});
      validation.check(params, 'invoice_number', {name: "发票号码", is_require: true});
      validation.check(params, 'invoice_time', {name: "开票时间", is_require: true});
      validation.check(params, 'mail_no', {name: "快递单号", is_require: true});
      validation.check(params, 'invoice_img', {name: "发票图片", is_require: true});
      let rs = await this.saasinvoiceSve.makeout(params);
      return rs;
    } 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}`);
    }
  }

  async platformTitleAddr(params, pobj2, req) {
    try {
      let id = params.id;
      let apply = await this.saasinvoiceSve.invoiceapplyById(params);
      if (!apply.data || !apply.data.id) {
        return system.getResult(null, "发票申请不存在");
      }
      apply = apply.data;
      let result = {};
      result.title = {
        "merchant_name": apply.from_name,
        "merchant_credit_code": apply.from_credit_code,
        "merchant_addr": apply.from_addr,
        "merchant_mobile": apply.from_mobile,
        "merchant_bank": apply.from_bank,
        "merchant_account": apply.from_account
      };
      result.addr = {"mail_addr": "", "mail_mobile": "", "mail_to": ""};
      return system.getResultSuccess(result);
    } 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}`);
    }
  }

  async platformInvoiceInfo(params, pobj2, req) {
    try {
      let id = params.id;
      let invoice_type = params.invoice_type;
      let apply = await this.saasinvoiceSve.invoiceapplyById(params);
      if (!apply.data || !apply.data.id) {
        return system.getResult(null, "发票申请不存在");
      }
      // apply = apply.data;

      let result = await this.buildTradeInvoice(params);
      return result;
    } 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}`);
    }
  }

  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 tmp = items[0];
    let signinfo = await this.merchantSve.signInfo({id: tmp.saas_merchant_id});
    if (!signinfo || !signinfo.data) {
      return system.getResult(null, "商户签约信息不存在，请先做签约配置");
    }

    let invoice_service_rate = signinfo.data.invoice_service_rate || 0;

    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;
      let data_ids = [];
      for (let item of itemList) {
        amount = amount + Number(item.amt || 0);
        data_ids.push(item.id); // TODO 总统测试
      }
      let service_tax = parseFloat((Number(amount) * Number(invoice_service_rate) / 100).toFixed(2));
      if (!businessmen.is_bank) {
        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.is_bank,
        "is_bank_name": businessmen.is_bank ? "已开户" : "未开户",
        "invoice_amount": system.f2y(amount),
        "personal_invoice_tax": 0,
        "additional_tax": 0,
        "service_tax": system.f2y(service_tax),
        "value_added_tax": 0,
        "unit": "",
        "quantity": "",
        "price": "",
        "remark": "",
        "data_ids": data_ids.join(",")    // TODO 总统测试
      });
    }

    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 calcMap = {};
      if (calcParams.length > 0) {
        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 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 businessmen = businessmenMap[invoice.credit_code];
        if (!businessmen.is_bank) {
          service_tax_total = service_tax_total + Number(invoice.service_tax);

          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);

          invoice.personal_invoice_tax = system.toFloat(Number(invoiceCalc.personal_invoice_tax));
          invoice.additional_tax = system.toFloat(Number(invoiceCalc.additional_tax));
          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, `系统错误`);
    }
  }

  async platformInvoiceApply(params, pobj2, req) {
    try {

      validation.check(params, "id", {name: "发票申请信息", is_require: true});
      validation.check(params, "invoice_type", {name: "发票类型", is_require: true, dics: ['30', "10", "20"]});
      validation.check(params, "invoiceList", {name: "开票信息", arr_require: true});
      validation.check(params, "mail_to", {name: "收件人", arr_require: true});
      validation.check(params, "mail_mobile", {name: "联系电话", arr_require: true});
      validation.check(params, "mail_addr", {name: "邮寄地址", arr_require: true});

      let invoiceList = params.invoiceList;
      let apply = await this.saasinvoiceSve.invoiceapplyById({id: params.id});
      if (!apply.data || !apply.data.id) {
        return system.getResult(null, "发票申请不存在");
      }
      apply = apply.data;
      if (apply.status != 1040) {
        return system.getResult(null, "已提交平台申请，请勿重复提交");
      }

      let creditCodes = [];
      for (let invoice of invoiceList) {
        creditCodes.push(invoice.credit_code);
      }
      let businessmenMap = await this.orderSve.mapByCreditCodes({creditCodes: creditCodes});
      businessmenMap = businessmenMap.data;

      for (let invoice of invoiceList) {
        validation.check(businessmenMap, invoice.credit_code, {name: `个体户[${invoice.credit_code}]`, is_require: true});
      }

      let applyList = [];
      let batch_no = await this.redisClient.genrateId("invoice_batch_no");
      for (let invoice of invoiceList) {
        let bussinessmen = businessmenMap[invoice.credit_code];
        let apply_no = await this.redisClient.genrateId("invoice_apply_no");
        let data = {
          saas_id: apply.saas_id,
          saas_merchant_id: apply.saas_merchant_id,
          parent_id: apply.id,
          owner_type: "10",
          status: "1000",
          batch_no: batch_no,
          apply_no: apply_no,
          fee_type: "10",
          invoice_amount: system.y2f(invoice.invoice_amount),
          invoice_type: this.trim(params.invoice_type),

          from_name: bussinessmen.name,
          from_credit_code: bussinessmen.credit_code,
          from_mobile: bussinessmen.legal_mobile,
          from_addr: bussinessmen.business_place,
          from_bank: bussinessmen.bank_name,
          from_account: bussinessmen.bank_no,

          to_name: this.trim(apply.from_name),
          to_credit_code: this.trim(apply.from_credit_code),
          to_mobile: this.trim(apply.from_mobile),
          to_addr: this.trim(apply.from_addr),
          to_bank: this.trim(apply.from_bank),
          to_account: this.trim(apply.from_account),

          mail_addr: this.trim(params.mail_addr),
          mail_mobile: this.trim(params.mail_mobile),
          mail_to: this.trim(params.mail_to),
          data_ids: this.trim(invoice.data_ids),        // TODO 总统测试

          personal_invoice_tax: system.y2f(invoice.personal_invoice_tax),
          additional_tax: system.y2f(invoice.additional_tax),
          service_tax: system.y2f(invoice.service_tax),
          value_added_tax: system.y2f(invoice.value_added_tax),
          unit: this.trim(invoice.unit),
          quantity: this.trim(invoice.quantity),
          price: this.trim(invoice.price),
          remark: this.trim(invoice.remark),
        };
        applyList.push(data);
      }
      let rs = await this.saasinvoiceSve.applyBulkSave({
        fee_type: apply.fee_type,
        dataList: applyList,
        parent_id: apply.id,
        updateStatus: {
          id: apply.id,
          preStatus: "1040",
          status: "1060",
        }
      });

      return system.getResultSuccess(rs);
    } 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}`);
    }
  }

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

  //发票申请列表
  async applyPage(params, pobj2, req) {
    try {
      params.owner_type = "00";
      let rs = await this.saasinvoiceSve.platforminvoiceapplyPage(params);
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  //发票申请列表
  async platformApplyPage(params, pobj2, req) {
    try {
      params.owner_type = "10";
      let rs = await this.saasinvoiceSve.platforminvoiceapplyPage(params);
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 审核
  async platformAudit(params, pobj2, req) {
    try {
      params.id = this.trim(params.id);
      if (!params.id) {
        return system.getResult(null, "发票申请不存在");
      }
      params.remark = this.trim(params.remark);
      if (!params.remark) {
        return system.getResult(null, "请填写审核备注");
      }
      params.status = Number(params.status || 0) ? "1010" : "1020";
      let rs = await this.saasinvoiceSve.audit(params)
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  // 发票办理
  async platformHandle(params, pobj2, req) {
    try {
      params.id = this.trim(params.id);
      if (!params.id) {
        return system.getResult(null, "发票申请不存在");
      }
      let rs = await this.saasinvoiceSve.platformHandle(params)
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  //fn:查询发票(saas_invoice,saas_invoice_apply,st_order_item)详细信息
  async queryInvoiceStOrderItem(params, pobj2, req){
    if(!params.id){
      return system.getResult(null,`发票【${params.id}】不存在`);
    }
    return  await this.saasinvoiceSve.queryInvoiceStOrderItem(params);
  }

  /**
   * fn:查询发票(saas_invoice,saas_invoice_apply,st_order_item)详细信息
   * @param {*} params
   * @param {*} pobj2
   * @param {*} req
   */
  async queryInvoiceTrad(params, pobj2, req) {
    if (!params.id) {
      return system.getResult(null, `发票ID 不能为空`);
    }
    try {
      return await this.saasinvoiceSve.queryInvoiceTrad(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

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


}

module.exports = InvoiceCtl;
