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

class OrderService extends ServiceBase {

  constructor() {
    super();
    this.pushapiSve = system.getObject("service.push.pushapiSve");
    this.userSve = system.getObject("service.uc.userSve");
  }

  async addSourceOrder(params) {
    try {
      return await this.callms("order", "addSourceOrder", params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async allProcess(params) {
    try {
      return await this.callms("order", "allProcess", params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async orders(params) {
    var rs = await this.callms("order", "orders", params);
    await this.setUcUser(rs.data.rows);
    return rs;
  }

  async handleStatus(params) {
    let rs = await this.callms("order", "handleStatus", params);
    if(rs && rs.status === 0) {
      this.pushOrderInfo(params);
    }
    return rs;
  }

  async pushOrderInfo(params) {
    if(params.status == 1190) {
      let order = await this.callms("order", "orderInfo", params) || {};
      order = order.data;
      if (!order) {
        return;
      }
      if(!order.saas_deliver_api) {
        return;
      }
      let data = {
        source_no: order.source_no,
        status: order.status,
        guest_mail_no: params.guest_mail_no,
        guest_mail_img: params.guest_mail_img
      }
      axios({
        method: 'post',
        url: order.saas_deliver_api,
        data: data
      });
    }
  }

  async orderInfo(params) {
    var rs = await this.callms("order", "orderInfo", params);
    if (rs.data) {
      if (rs.data.orderDeliver && rs.data.orderDeliver.deliver_divide) {
        rs.data.orderDeliver.deliver_divide = system.f2y(rs.data.orderDeliver.deliver_divide);
      }
    }
    return rs;
  }

  async orderInfoAll(params) {
    var rs = await this.callms("order", "orderInfoAll", params);
    await this.setUcUser([rs.data.order]);
    return rs;
  }

  async productDics(params) {
    var rs = await this.callms("order", "productDics", params);
    return rs;
  }

  async statManageData(params) {
    var res = await this.callms("order", "statTransData", params);
    return res;
  }
  async statBusinessData(params) {
    var res = await this.callms("order", "statBusinessData", params);
    return res;
  }

  // async statDeliverData(params) {
  //   var res = await this.callms("order", "statDeliverData", params);
  //   return res;
  // }

  async setUcUser(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    let ids = [];
    for (let row of rows) {
      if (row.bd_id) {
        ids.push(row.bd_id);
      }
      if (row.assign_user_id) {
        ids.push(row.assign_user_id);
      }
    }

    let userRs = await this.userSve.mapByIds({ ids: ids });
    let userMap = userRs.data || {};

    for (let row of rows) {
      let user = userMap[row.bd_id] || {};
      row.bd_name = user.realName || "";

      let assignUser = userMap[row.assign_user_id] || {};
      row.assign_user_name = assignUser.realName || "";
    }
  }

  async pushDeliver(obj) {
    var status = obj.status;
    if (!status) {
      return;
    }
    var order = await this.callms("order", "orderByDeliverId", {
      orderDeliverId: obj.id
    });
    order = order.data;
    if (!order) {
      console.log("推送信息失败[" + JSON.stringify(obj) + "]，订单不存在 ------------------------");
      return;
    }

    var merchant = await this.callms("merchant", "secretById", {
      id: order.merchant_id
    });
    merchant = merchant.data;
    if (!merchant) {
      console.log("推送信息失败[" + JSON.stringify(obj) + "]，商户不存在 ------------------------");
      return;
    }

    var options = {
      merchantId: merchant.id,
      appKey: merchant.appSecret,
      dataType: 1,
      dataId: order.id,
      field: "orderStatus",
    };

    var params = {
      merchantId: merchant.id,
      status: status,
      channelOrderNo: order.channelOrderNo,
    }
    var handlingStatus = ["1050", "1070", "1090", "1110"];

    if (status == "1060") {
      // 已出执照
      params.name = this.trim(obj.name);
      params.creditCode = this.trim(obj.creditCode);
      params.businessPlace = this.trim(obj.businessPlace);
      params.businessScope = this.trim(obj.businessScope);
      params.regDate = this.trim(obj.regDate);
      params.businessImg = this.trim(obj.businessImg);
      params.orderNo = this.trim(obj.orderNo);
      params.legalName = this.trim(obj.legalName);
      params.legalMobile = this.trim(obj.legalMobile);

    } else if (status == "1080") {
      // 已刻章
      params.gongzhang = this.trim(obj.gongzhang);
      params.caiwuzhang = this.trim(obj.caiwuzhang);
      params.businessImg = this.trim(obj.businessImg);
      params.fapiaozhang = this.trim(obj.fapiaozhang);
      params.hetongzhang = this.trim(obj.hetongzhang);
      params.farenzhang = this.trim(obj.farenzhang);
    } else if (status == "1100") {
      // 银行卡已开户
      params.isBank = obj.isBank ? 1 : 0;
      params.bankName = this.trim(obj.bankName);
      params.bankNo = this.trim(obj.bankNo);
      params.bank = this.trim(obj.bank);
      params.bankImg = this.trim(obj.bankImg);
    } else if (status == "1120") {
      // 已税务报道
      params.caImg = this.trim(obj.caImg);
      params.taxRegDay = this.trim(obj.taxRegDay);
      params.taxOrg = this.trim(obj.taxOrg);
    } else if (status == "1170") {
      // 已完成
      params.courierNo = this.trim(obj.deliverNo);
      params.courierImg = this.trim(obj.deliverImg);
    } else if (handlingStatus.indexOf(status) != -1) { } else {
      return;
    }
    options.params = params;

    await this.pushapiSve.push(options);
  }
  // 数据简报（本月交易数据）
  async statTransData(params) {
    if (!params.current_date) {
      return system.getResult(null, `参数错误 当前时间不能为空`);
    }
    try {
      return await this.callms("order", "statTransData", params);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }
  //待办事项
  async needToBeDealtWith(params) {
    if (!params.current_date) {
      return system.getResult(null, `参数错误 当前时间不能为空`);
    }
    try {
      return await this.callms("order", "needToBeDealtWith", params);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }

  //交付商统计
  async statDeliverData(params) {
    if(!params.current_date){
      return system.getResult(null,`参数错误 当前时间不能为空`);
    }
    try {
      let res = await this.callms("order", "statDeliverData", params);
      if(res.status==0 && res.data && res.data.length>0){
        for(let item of res.data){
          item.serivce_price=system.f2y(item.serivce_price);
        }
      }
      return res;
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 获取用户账簿信息
   * @param {*} params 
   * id  个体工商户ID
   */
  async getCustomerById(params){
    try {
      let businessmen = await this.callms("order", "queryObusinessmen", {id:params.id});
      if(!businessmen || !businessmen.data){
        return system.getResult(null,`个体工商户不存在`);
      }
      let url = settings.ntapi().getCustomerById;
      let res = await this.callApi(url, {id:businessmen.customer_id}, "获取用户账簿信息");
      return res;  
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }
}
module.exports = OrderService;