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

class IborderbaseService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(IborderbaseService));
    this.iborderSve = system.getObject("service.order.iborderSve");
    this.iborderdkSve = system.getObject("service.order.iborderdkSve");
    this.iborderdzSve = system.getObject("service.order.iborderdzSve");
    this.businessmenSve = system.getObject("service.business.businessmenSve");
    this.channelSve = system.getObject("service.order.channelSve");
    this.paymentSve = system.getObject("service.order.paymentSve");
    this.services = {
      "1000": this.iborderSve,   // 注册订单
      "1010": this.iborderdkSve, // 代开订单
      "1030": this.iborderdzSve, // 代账订单
      "1040": this.iborderSve,   // 增值服务
    }
    this.verifyProductType=["1010","1030"];
  }


  getService(productType) {
    return this.services[productType];
  }

  /**
   * 创建基类订单
   * @param {*} params
   */
  async apiCreateOrder(params) {
    this.trimObject(params);
    if (!params.thirdNo) {
      return system.getResult(null, `请传入订单号`);
    }
    let productType = this.trim(params.productType);
    let childSve = this.getService(productType);
    if (!childSve) {
      return system.getResult(null, `暂不支持此种产品类型：${productType}`);
    }

    try {
      let exists = await this.dao.findOne({thirdNo: params.thirdNo});
      if(exists) {
        return system.getResult(null, `订单号【${params.thirdNo}】已存在`);
      }

      let channel =await this.channelSve.findOne({channelNo: params.channelNo});
      if (!channel) {
        return system.getResult(null, `渠道${params.channelNo}不存在`);
      }

      params.channelNo = this.trim(params.channelNo);
      params.thirdNo = this.trim(params.thirdNo);
      params.notes = this.trim(params.notes);
      params.legalName = this.trim(params.legalName);
      params.legalMobile = this.trim(params.legalMobile);
      params.legalEmail = this.trim(params.legalEmail);
      params.payType = Number(params.payType || 1);
      params.productType = productType;
      params.price = Number(params.price || 0);
      params.status = "1000"; // 待处理
      params.payStatus = "10"; // 支付状态
      params.channelOrderNo = params.channelNo;
      params.payType = this.trim(params.payType);
      let self = this;
      //1 保存基类的信息
      await this.db.transaction(async t => {
        //创建基类表
        let _baseOrder = await self.create(params, t);
        var payment = {
          order_id: _baseOrder.id,
          price: params.price,
          channelName: channel.channelName,
          companyName: "",
          payType: params.payType,
          payStatus: "10",
        };
        payment = await this.paymentSve.create(payment, t);
        params.orderpay_id = payment.id;
        // 将id赋值
        params.id = _baseOrder.id;

        // 创建订单
        await childSve.createOrder(params, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 完善信息
   * @param {*} params
   */
  async apiCompletedOrder(params) {
    try {
      let baseorder = await this.dao.findById(params.id);
      let childSve = this.getService(baseorder.productType);
      return await childSve.completedOrder(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单办理
   * @param {} params
   */
  async apiHandling(params) {
    try {
      let _baseOrder = this.dao.findById({id:this.trim(params.id),productType:this.trim(params.productType)});
      if(!_baseOrder){
        return system.getResult(null,`参数错误 订单不存在`);
      }
      let childSve = this.getService(params.productType);
      return await childSve.handling(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单列表
   * @param {*} params
   * @param {*} params.productType  //产品类型 
   */
  async apiOrders(params){
    try {
      let childSve = this.getService(params.productType);
      let page = await childSve.orderPage(params);
      if(page && page.data && page.data.rows) {
        await this.setBaseOrder(page.data.rows);
      }
      for(let item of page.data.rows){
        if(item.baseInfo && item.baseInfo.productType!="1000"){
          this.changeStatus(item.baseInfo,item);
          this.changePayStatus(item.baseInfo,item);
        }    
      }
      return page;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  changeStatus (baseInfo,orderInfo){
    // 1000待处理 1010办理中 1020办理完成  2000已取消
    if(baseInfo.status=="1000"){
      orderInfo.ostatusName = "待处理";
    }else if(baseInfo.status=="1010"){
      orderInfo.ostatusName = "办理中";
    }else if(baseInfo.status=="1020"){
      orderInfo.ostatusName = "办理完成";
    }else if(baseInfo.status=="2000"){
      orderInfo.ostatusName = "已取消";
    }else{
      orderInfo.ostatusName = "";
    }
  }

  changePayStatus (baseInfo,orderInfo){
    //支付状态 10待支付 20已支付
    if(baseInfo.payStatus=="10"){
      orderInfo.payStatusName = "待支付";
    }else if(baseInfo.payStatus=="20"){
      orderInfo.payStatusName = "已支付";
    }else{
      orderInfo.payStatusName = "";
    }
  }

  /**
   * 企服通 推送支付信息接口
   * @param {*} params
   * id           //订单ID
   * price        //支付金额
   * orderpayId   //支付id
   * 
   * 所有主表的信息和子表的信息更新 都必须在子实现类中更新
   */
  async completedOrderInfo(params, t) {
    try {
      
      if(!params.id){
        return system.getResult(null,`参数错误 ID不能为空`);
      }else{
        params.id = this.trim(params.id);
      }
      if(params.price<0){
        return system.getResult(null, `参数错误 支付金额非法`);
      }else{
        params.price= Number(params.price);
      }

      if(params.orderpayId){
        return system.getResult(null,`参数错误 支付ID非法`);
      }else{
        params.orderpay_id = orderpayId;
      }

      let _iborderbase = await this.dao.findById(this.trim(params.id));
      if(!_iborderbase){
        return system.getResult(null,`订单不存在`);
      }
      // 产品类型 1000注册订单 1010代开订单 1030代账订单
      if(_iborderbase.productType=="1000"){
        // await this.iborderdkSve.updateOrder()
        return system.getResult(null,`暂不支持 此类型商品`);
      }else if(_iborderbase.productType=="1010"){
        //业务状态 1000待分配  1010办理中  1020办理完成
        params.payStatus = params.payStatus?this.trim(params.payStatus):"20";
        params.status=params.status?this.trim(params.status):"1010";
        //更新订单
        await this.iborderdkSve.updateOrder(params);
      }else if(_iborderbase.productType=="1030"){
        //await this.iborderdkSve.updateOrder()
        return system.getResult(null,`暂不支持 此类型商品`);
      }else {
        return system.getResult(null,`当前订单类型不存在 请联系管理员`);
      }
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async apiAdd(params) {
    try {
      let sve = this.getService(params.productType);
      if (!sve) {
        return system.getResult(null, `产品类型错误${params.productType}`);
      }
      return sve.addOrder(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiSaveInfo() {
    try {
      let sve = this.getService(params.productType);
      if (!sve) {
        return system.getResult(null, `产品类型错误${params.productType}`);
      }
      return sve.saveInfo(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

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

    var ids = [];
    for (var row of rows) {
      ids.push(row.id);
    }
    let map = await this.dao.findMapByIds(ids);

    for (var row of rows) {
      row.baseInfo = map[row.id];
    }
  }
}

module.exports = IborderbaseService;