const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
class OrderService extends ServiceBase {
  constructor() {
    super();
    this.pushapiSve = system.getObject("service.push.pushapiSve");
  }

  async addOrder(params) {
    var merchantId = params.merchant_id;

    var rs = await this.callms("merchant", "getById", {
      id: merchantId
    });
    if (!rs || rs.status != 0 || !rs.data) {
      return system.getResult(null, rs.msg || "商户不存在");
    }

    var merchant = rs.data;

    // 处理参数
    var order = {};
    order.merchantId = merchantId;
    order.channelOrderNo = this.trim(params.channelOrderNo);
    order.legalName = this.trim(params.legalName);
    order.legalMobile = this.trim(params.legalMobile);
    order.legalImg = this.trim(params.legalImg);
    order.idcard = this.trim(params.idcard);
    order.idcardFront = this.trim(params.idcardFront);
    order.idcardBack = this.trim(params.idcardBack);
    order.bankNo = this.trim(params.bankNo);
    order.bank = this.trim(params.bank);
    order.names = this.trim(params.names);
    order.capital = this.trim(params.capital);
    order.domicileId = this.trim(params.domicileId);
    order.businessScopeId = this.trim(params.businessScopeId);
    order.businesssScope = this.trim(params.businesssScope);

    order.bdId = this.trim(merchant.ownerId);
    order.bdPath = this.trim(merchant.ownerPath);

    return await this.callms("order", "addOrder", params);
  }

  async putOrder(params) {
    var merchantId = params.merchant_id;

    var rs = await this.callms("merchant", "getById", {
      id: merchantId
    });
    if (!rs || rs.status != 0 || !rs.data) {
      return system.getResult(null, rs.msg || "商户不存在");
    }

    var merchant = rs.data;

    // 处理参数
    var order = {};
    order.merchantId = merchantId;
    order.channelOrderNo = this.trim(params.channelOrderNo);
    order.legalName = this.trim(params.legalName);
    order.legalMobile = this.trim(params.legalMobile);
    order.legalImg = this.trim(params.legalImg);
    order.idcard = this.trim(params.idcard);
    order.idcardFront = this.trim(params.idcardFront);
    order.idcardBack = this.trim(params.idcardBack);
    order.bankNo = this.trim(params.bankNo);
    order.bank = this.trim(params.bank);
    order.names = this.trim(params.names);
    order.capital = this.trim(params.capital);
    order.domicileId = this.trim(params.domicileId);
    order.businessScopeId = this.trim(params.businessScopeId);
    order.businessScope = this.trim(params.businessScope);

    return await this.callms("order", "updOrder", params);
  }

  async queryOrder(params) {
    var condition = {
      merchantId: this.trim(params.merchant_id),
      channelOrderNo: this.trim(params.channelOrderNo),
    }

    var rs = await this.callms("order", "byChannelOrderId", condition);
    if (rs.status != 0) {
      return rs;
    }

    var order = rs.data;

    var dto = {};
    dto.orderNo = order.id;
    dto.channelOrderNo = order.channelOrderNo;
    dto.legalName = order.legalName;
    dto.legalMobile = order.legalMobile;
    dto.legalImg = order.legalImg;
    dto.idcard = order.idcard;
    dto.idcardFront = order.idcardFront;
    dto.idcardBack = order.idcardBack;
    dto.bankNo = order.bankNo;
    dto.bank = order.bank;
    dto.bankImg = order.bankImg;
    dto.names = order.names;
    dto.businessScope = order.businessScope;
    dto.capital = order.capital;
    dto.status = order.ostatus;
    dto.opNotes = order.opNotes;

    dto.domicileId = order.domicile_id;
    dto.businessScopeId = order.businessScope_id;
    dto.businessScope = order.businessScope;

    return system.getResultSuccess(dto);
  }

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

    await this.transfield(rs.data.rows);
    await this.setMerchant(rs.data.rows);
    return rs;
  }

  async orderClose(params) {
    var p = {
      merchantId: params.merchantId || params.merchant_id,
      channelOrderNo: params.channelOrderNo
    };
    var rs = await this.callms("order", "orderClose", p);
    return rs;
  }

  async closeById(params) {
    var rs = await this.callms("order", "closeOrderById", {
      id: params.id
    });
    return rs;
  }

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

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

  async orderComplete(params) {
    var rs = await this.callms("order", "orderComplete", params);
    if (rs.status == 0) {
      this.pushDeliver(params);
    }
    return rs;
  }

  async orderInfoAll(params, isMerchant) {
    var rs = await this.callms("order", "orderInfoAll", params);
    await this.transfield([rs.data]);
    if (rs.data) {
      if (rs.data.deliver) {
        rs.data.deliverDivide = system.f2y(rs.data.deliver.deliverDivide);
      }
      if (rs.data.businessmen) {
        rs.data.businessmen.costRate = system.f2y(rs.data.businessmen.costRate);
        rs.data.businessmen.taxRate = system.f2y(rs.data.businessmen.taxRate);
        rs.data.businessmen.serviceRate = system.f2y(rs.data.businessmen.serviceRate);
      }
      if (isMerchant) {
        var merchant = await this.callms("merchant", "getById", {
          id: rs.data.merchant_id
        }) || {};
        rs.data.merchant = merchant.data || {};
      }
    }
    return rs;
  }

  // 订单办理
  async handlePage(params) {
    var rs = await this.callms("order", "orderDeliverList", params);
    if (rs.status === 0 && rs.data && rs.data.rows) {
      for (var row of rs.data.rows) {
        row.deliverDivide = system.f2y(row.deliverDivide);
        row.order.price = system.f2y(row.order.price);
      }
    }
    return rs;
  }

  async deliverEdit(params) {
    var obj = {
      order: params.order,
      businessmen: params.businessmen
    };
    return await this.callms("order", "orderDeliverEdit", obj);
  }

  async deliverClose(params) {
    var obj = {
      id: params.id,
      breakReason: params.breakReason,
    };
    return await this.callms("order", "orderDeliverClose", obj);
  }

  async deliverHandle(obj) {
    var rs = await this.callms("order", "orderDeliverHandle", obj);
    // var rs = {status: 0};
    if (rs.status === 0) {
      // 推送数据
      this.pushDeliver(obj);
    }
    return rs;
  }

  async deliverAudit(obj) {
    return await this.callms("order", "orderDeliverAudit", obj);
  }

  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 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 transfield(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    for (var row of rows) {
      row.price = system.f2y(row.price);
    }
    return rows;
  }

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

    var merchantIds = [];
    for (var row of rows) {
      merchantIds.push(row.merchant_id);
    }

    var mmap = await this.callms("merchant", "getMapByIds", {
      ids: merchantIds,
      attrs: "id, name"
    });
    mmap = mmap.data || {};
    for (var row of rows) {
      row.merchant = mmap[row.merchant_id] || {};
    }
  }

  /**
   * 创建订单
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async createOrder(pobj, pobj2, req){
    try {
      var res = await this.callms("order", "createOrder", pobj);
      return res;
    } catch (error) {
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }
  /**
   * 完善信息接口
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async completedOrder(pobj, pobj2, req){
    try {
      var res = await this.callms("order", "completedOrder", pobj);
      return res;
    } catch (error) {
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单列表
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async orders(pobj, pobj2, req){
    try {
      return await this.callms("order", "orders", pobj);
    } catch (error) {
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }
}
module.exports = OrderService;