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

    try {
      await _obusinessmen.save();
      return system.getResultSuccess();
    } 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);
      }
      await this.doSignBtn(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;
    }
  }
}

module.exports = ObusinessmenService;