const system = require("../../../system");
const ServiceBase = require("../../sve.base")
/**
 * 个体户
 */
class ObusinessmenService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(ObusinessmenService));
    this.oorderDao = system.getObject("db.order.oorderDao");
    this.oorderdeliverDao = system.getObject("db.order.oorderdeliverDao");

    this.ASSIGN_STATUS = ['1160', '1170', '1180', '1190', '1200'];
  }

  /**
   * 根据ID查记录
   * @param {*} params 
   * @Id 个体户ID
   */
  async queryObusinessmen(params) {
    try {
      let obj = await this.findById(this.trim(params.id));
      this.handleDate(obj, ["created_at", "assignTime","reg_date","tax_reg_day","updated_at"], null, -8);
      return system.getResult(obj);
    } catch (error) {
      console.log(error);
      return system.getResult(`系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 签约
   * @params
   * @id       
   * 
   */
  async signing(params) {
    if (!params.id) {
      return system.getResult(null, `参数错误 个体户ID不能为空`);
    }
    if (!params.hasOwnProperty('cost_rate')) {
      return system.getResult(null, `参数错误 核定成本费用率不能为空`);
    }
    if (!params.hasOwnProperty('add_value_up_type') && !params.add_value_up_type) {
      return system.getResult(null, `参数错误 增值税累计类型不能为空`);
    }
    if (!params.hasOwnProperty('tax_up_type')) {
      return system.getResult(null, `参数错误 个税累计类型不能为空`);
    }
    if (!params.hasOwnProperty('service_begin_time')) {
      return system.getResult(null, `参数错误 服务开始时间不能为空`);
    }
    if (!params.hasOwnProperty('service_end_time')) {
      return system.getResult(null, `参数错误 服务结束时间不能为空`);
    }
    if (!params.hasOwnProperty('service_rate') && !params.service_rate) {
      return system.getResult(null, `参数错误 服务费比例不能为空`);
    }
    if (!params.hasOwnProperty('tax_rate') && !params.tax_rate) {
      return system.getResult(null, `参数错误 含税价百分比不能为空`);
    }

    let _obusinessmen = await this.dao.findById(this.trim(params.id));
    let _order = await this.oorderDao.model.findOne({
      where:{
        id:_obusinessmen.order_id
      }
    });
    if(!_obusinessmen){
      return system.getResult(null,`个体户不存在`);
    }
    if(!_order){
      return system.getResult(null,`订单存在`);
    }
    if(this.ASSIGN_STATUS.indexOf(_order.status.toString())==-1){
      return system.getResult(null,`个体工商户不能签约`);
    }
    
    _obusinessmen.cost_rate = this.trim(params.cost_rate);
    _obusinessmen.add_value_up_type = this.trim(params.add_value_up_type);
    _obusinessmen.tax_up_type = this.trim(params.tax_up_type);
    _obusinessmen.service_begin_time = this.trim(params.service_begin_time);
    _obusinessmen.service_end_time = this.trim(params.service_end_time);
    _obusinessmen.service_rate = this.trim(params.service_rate);
    _obusinessmen.tax_rate = this.trim(params.tax_rate);
    _obusinessmen.sign_time = new Date();
    _obusinessmen.sign_notes = this.trim(params.sign_notes);
    _obusinessmen.special_other_ladder = params.special_other_ladder;
    _obusinessmen.special_tax_ladder  = params.special_tax_ladder;
    _obusinessmen.common_other_ladder  = params.common_other_ladder;
    _obusinessmen.common_tax_ladder  = params.common_tax_ladder;
    _obusinessmen.invoice_content = JSON.stringify(params.invoice_content || []);

    try {
      await _obusinessmen.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息${error}`);
    }
  }

  async signNames(params){
    try {
      return [];
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息:${error}`);
    }
  }

  /**
   * 建账
   * @param {*} params 
   */
  async createAccount(params){
    if (!params.id) {
      return system.getResult(null, `参数错误 个体工商户ID不能为空`);
    }
    
    let _obusinessmen = await this.dao.findById(this.trim(params.id));
    if(!_obusinessmen){
      return system.getResult(null,`个体户不存在`);
    }
    if (_obusinessmen.is_create_account) {
      return system.getResult(null,`该个体户已经建帐`);
    }

    _obusinessmen.is_create_account = true;
    _obusinessmen.province = params.province;
    _obusinessmen.customer_id = params.customer_id;
    _obusinessmen.create_account_time = new Date();
    try {
      await _obusinessmen.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      system.getResult(null,`系统错误 错误信息${error}`);
    }
  }

  async businessmenPage(params) {
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);

    params.startRow = (params.currentPage - 1) * params.pageSize;

    let deliverId = params.deliver_id;
    let orderIds = [];
    if (deliverId) {
      // 查询交付商关联订单id
      let _orderIds = await this.oorderdeliverDao.orderIdsByDeliverId(deliverId);
      if (!_orderIds || _orderIds.length == 0) {
        return system.getResultSuccess({count: 0, rows: []});
      }
      orderIds = orderIds.concat(_orderIds);
    }

    let operatorId = params.operator_id;
    if (operatorId) {
      let _orderIds = await this.oorderdeliverDao.orderIdsByOperatorId(operatorId);
      if (!_orderIds || _orderIds.length == 0) {
        return system.getResultSuccess({count: 0, rows: []});
      }

      if (orderIds.length == 0) {
        orderIds = orderIds.concat(_orderIds);
      } else {
        let tmpIds = [];
        for (let oid of orderIds) {
          if (_orderIds.indexOf(oid) != -1) {
            tmpIds.push(oid);
          }
        }
        if (tmpIds.length == 0) {
          return system.getResultSuccess({count: 0, rows: []});
        }
        orderIds = tmpIds;
      }
    }

    if (orderIds && orderIds.length > 0) {
      params.orderIds = orderIds;
    }

    let total = await this.dao.countByCondition(params);
    if (total == 0) {
      return system.getResultSuccess({count: 0, rows: []});
    }

    let list = await this.dao.listByCondition(params);
    if (list) {
      for (var row of list) {
        this.handleDate(row, ["created_at", "assignTime","reg_date","tax_reg_day","updated_at"], null, -8);
        row.service_rate=system.f2y(row.service_rate);
        row.cost_rate=system.f2y(row.cost_rate);
        row.tax_rate=system.f2y(row.tax_rate);
        if(row.invoice_content) {
          try {
            row.invoice_content = JSON.parse(row.invoice_content);
          } catch (error) {
            row.invoice_content = [];
          }
        } else {
          row.invoice_content = [];
        }
      }
      await this.doSignBtn(list);
      await this.setDeliverId(list);
    }
    return system.getResultSuccess({count: total, rows: list});
  }

  async doSignBtn(list) {
    if (!list || list.length == 0) {
      return;
    }

    let ids = [];
    for (let item of list) {
      ids.push(item.order_id);
    }

    let orderMap = await this.oorderDao.findMapByIds(ids, "id, status");

    for (let item of list) {
      let order = orderMap[item.order_id] || {};
      item.showSign = this.ASSIGN_STATUS.indexOf(order.status.toString()) != -1;
    }
  }

  async setDeliverId(list) {
    if(!list || list.length == 0) {
      return;
    }
    let orderIds = []
    for (let item of list) {
      orderIds.push(item.order_id || 0);
    }

    let map = await this.oorderDao.findMapByIds(orderIds);
    for (let item of list) {
      let order = map[item.order_id || 0] || {};
      item.deliver_id = order.deliver_id || 0;
    }
  }

}

module.exports = ObusinessmenService;