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);
      let attributes = ["source_no","saas_deliver_api"];
      let order = await this.oorderDao.model.findOne({
        where:{
          id:obj.order_id
        },
        attributes
      });
      obj.dataValues.order = order;
      return system.getResult(obj);
    } catch (error) {
      console.log(error);
      return system.getResult(`系统错误 错误信息 ${error}`);
    }
  }

  async businessmenByOrderId(params) {
    let obusinessmen = await this.dao.findOne({order_id: params.order_id});
    return system.getResultSuccess(obusinessmen);
  }

  /**
   * 查询 saas推送 相关的信息
   * @param {*} params 
   */
  async queryObusinessmenInfo(params){
    if(!params.id){
      return system.getResult(null,`参数错误 订单ID不能为空`);
    }
    try {
      let businessmenBean = await this.dao.queryObusinessmenInfo(params);
      return system.getResult(businessmenBean);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }

  /**
   * 根据统一社会信用代码查记录
   * @param {*} params 
   * @Id 个体户ID
   * @Saas_id
   */
  async queryObusinessmenByCreditCode(params) {
    let credit_code = this.trim(params.credit_code) || "";
    let saas_id = this.trim(params.saas_id) || "";
    try {
      let obj = await this.dao.findByCreditCode(credit_code,saas_id);
      if(obj && obj.length>0){
        this.handleDate(obj[0], ["created_at", "assignTime","reg_date","tax_reg_day","updated_at"], null);
      }else{
        obj = {};
      }
      return system.getResult(obj[0]);
    } 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));
    // if(_obusinessmen.saas_id != this.trim(params.saas_id)){
    //   return system.getResult(null, `【${saas_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);
        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] || {};
      if(order.hasOwnProperty("status")){
        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;
    }
  }

  /**
   * fn:推送财税系统建账
   * @param {*} params 
   * @id 个体户id
   */
  async updateOBusinessmenProinvce(params){
    let where = {};
    if(!params.id){
      return system.getResult(null,`参数错误 个体户ID非法`);
    }else{
      where.id = this.trim(params.id);
    }
    // if(params.saas_id){
    //   where.saas_id = this.trim(params.saas_id);
    // }
    let bean = await this.dao.model.findOne({
      where:where
    });
    
    if(!bean){
      return system.getResult(null,`个体户不存在`);
    }
    let _obusinessmen={};
    _obusinessmen.id=bean.id;
    if(params.name){
      _obusinessmen.name = this.trim(params.name);
    }
    if(params.credit_code){
      _obusinessmen.credit_code = this.trim(params.credit_code).toUpperCase();
    }
    if(params.legal_name){
      _obusinessmen.legal_name = this.trim(params.legal_name);
    }
    if(params.reg_date){
      _obusinessmen.reg_date = params.reg_date;
    }
    if(params.business_place){
      _obusinessmen.business_place = this.trim(params.business_place);
    }
    if(params.business_scope){
      _obusinessmen.business_scope = JSON.stringify(params.business_scope);
    }
    if(params.business_img){
      _obusinessmen.business_img = this.trim(params.business_img);
    }
    if(params.business_gov_file){
      _obusinessmen.business_gov_file = this.trim(params.business_gov_file);
    }

    if(params.gongzhang){
      _obusinessmen.gongzhang = this.trim(params.gongzhang);
    }
    if(params.caiwuzhang){
      _obusinessmen.caiwuzhang = this.trim(params.caiwuzhang);
    }
    if(params.fapiaozhang){
      _obusinessmen.fapiaozhang = this.trim(params.fapiaozhang);
    }
    if(params.hetongzhang){
      _obusinessmen.hetongzhang = this.trim(params.hetongzhang);
    }
    if(params.farenzhang){
      _obusinessmen.farenzhang = this.trim(params.farenzhang);
    }
    if(params.zhang_gov_file){
      _obusinessmen.zhang_gov_file = this.trim(params.zhang_gov_file);
    }

    if(params.is_bank){
      _obusinessmen.is_bank = params.is_bank;
    }
    if(params.bank_name){
      _obusinessmen.bank_name = this.trim(params.bank_name);
    }
    if(params.bank_no){
      _obusinessmen.bank_no = this.trim(params.bank_no);
    }
    if(params.bank){
      _obusinessmen.bank = this.trim(params.bank);
    }
    if(params.bank_gov_file){
      _obusinessmen.bank_gov_file = this.trim(params.bank_gov_file);
    }

    if(params.tax_reg_day){
      _obusinessmen.tax_reg_day = params.tax_reg_day;
    }
    if(params.tax_org){
      _obusinessmen.tax_org = this.trim(params.tax_org);
    }
    if(params.tax_gov_file){
      _obusinessmen.tax_gov_file = this.trim(params.tax_gov_file);
    }
    if(params.ca_img){
      _obusinessmen.ca_img = this.trim(params.ca_img);
    }

    try {
      await this.dao.update(_obusinessmen);
      let res = await this.dao.getById(_obusinessmen.id);
      this.handleDate(res, ["created_at", "reg_date","tax_reg_day","updated_at"], null);
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }

  async mapByCreditCodes(params) {
    let rs = await this.dao.mapByCreditCodes(params.creditCodes, params.attrs) || {};
    return system.getResultSuccess(rs);
  }


}

module.exports = ObusinessmenService;