const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
const moment = require("moment");

class BusinessmenService extends ServiceBase {
  constructor() {
    super();
  }

  async info(params) {
    let rs = await this.callms("order", "queryObusinessmen", params);
    this.transField([rs.data]);
    return rs;
  }

  async allPage(params) {
    let rs = await this.callms("order", "businessmenPage", params);
    if (rs.status != 0 || !rs.data || !rs.data.rows) {
      return rs;
    }
    this.transField(rs.data.rows);
    return rs;
  }

  /**
   * @params 个体户签约
   */
  async signing(params) {
    try {
      return await this.callms("order", "signing", params);
    } catch (error) {
      console.log(error);
      return system.getResult(error);
    }
  }

  async signNames(params) {
    try {
      return await this.callms("order", "signNames", params);
    } catch (error) {
      console.log(error);
      return system.getResult(error);
    }
  }

  /**
   * @params 建仗
   */
  async createAccount(params) {
    try {
      // 查个体户
      let businessmen = await this.callms("order", "queryObusinessmen", params);
      businessmen = businessmen.data;
      // 查个体户的交付商
      var deliver = await this.callms("common", "deliverInfo", {id: params.deliver_id});
      deliver = deliver.data;

      let user = await this.callms("common", "deliverUserInfo", {id: deliver.admin_id}) || {};
      user = (user.data || {}).user || {};
      let data = {
        customerName: businessmen.name,
        initPeriod: Number(moment().format("YYYYMM")),
        // initPeriod:  moment().format("YYYYMM"),
        accountStandard: 1,
        valueAddedTax: 2,
        bankStatus: businessmen.is_bank ? 1 : 0,
        accountant: user.nt_user_id,
        province: params.province,
        companyId: deliver.nt_company_id,
      }
      let url = settings.ntapi().createCustomer;
      let res = await this.callApi(url, data, "建账");
      console.log(res);
      if (!res || !res.data) {
        return system.getResult(null, "建账失败");
      }
      if (res.data) {
        await this.callms("order", "createAccount", {
          id: params.id,
          province: params.province,
          customer_id: res.data,
        });

        // 异步推送建账信息 TODO 孙总统测
        this.pushBusinessmenInfo({
          order_id: businessmen.order_id,
          company_id: deliver.nt_company_id,
          customer_id: res.data,
          name: businessmen.name,
          credit_code: businessmen.credit_code,
        });
      }
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(error);
    }
  }

  // 推送建账信息 TODO 孙总统测
  async pushBusinessmenInfo(params) {
    let order = await this.callms("order", "orderInfo", {id: params.order_id}) || {};
    order = order.data;
    if (!order) {
      return;
    }
    if (!order.saas_deliver_api) {
      return;
    }
    let data = {
      source_no: order.source_no,
      status: "1000000",
      company_id: params.company_id,
      customer_id: params.customer_id,
      name: params.name,
      credit_code: params.credit_code,
    }
    axios({
      method: 'post',
      url: order.saas_deliver_api,
      data: data
    });
  }

  transField(rows) {
    if (!rows) {
      return;
    }

    for (var row of rows) {
      if (!row) {
        continue;
      }
      row.costRate = system.f2y(row.costRate);
      row.taxRate = system.f2y(row.taxRate);
      row.serviceRate = system.f2y(row.serviceRate);
      row.serviceBeginTime = system.f2y(row.serviceRate);
      row.serviceRate = system.f2y(row.serviceRate);
      this.handleDate(row, ["service_begin_time", "service_end_time", "tax_reg_day", "reg_date", "sign_time"], "YYYY-MM-DD", -8);
      this.parseJsonField(row, ["common_tax_ladder", "common_other_ladder", "special_tax_ladder", "special_other_ladder"]);
    }
  }

  parseJsonField(row, fields) {
    if (!row || !fields || fields.length == 0) {
      return;
    }
    for (var f of fields) {
      if (!f) {
        continue;
      }
      if (!row[f]) {
        row[f] = [];
        continue;
      }
      try {
        row[f] = JSON.parse(row[f] || "[]");
      } catch (error) {
        console.log(error);
      }
    }
  }
}

module.exports = BusinessmenService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });