const system = require("../../../system");
const ServiceBase = require("../../sve.base")
/**
 * 订单交付
 */
class OorderdeliverService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(OorderdeliverService));
    this.oorderinforegDao = system.getObject("db.order.oorderinforegDao");
    this.oorderDao = system.getObject("db.order.oorderDao");
    this.oorderprocessDao = system.getObject("db.order.oorderprocessDao");

    this.osourceDao = system.getObject("db.common.osourceDao");

    this.oproductDao = system.getObject("db.product.oproductDao");
    this.oprocessDao = system.getObject("db.product.oprocessDao");
    this.oproductprocessDao = system.getObject("db.product.oproductprocessDao");
  }

  /**
   * 交付商订单管理列表
   * @param {*} params 
   */
  async orderDelivers(params){
    let where = {};
    if(params.deliver_id){
      where.deliver_id = this.trim(params.deliver_id);
    }else{
      return system.getResult(null,`参数错误 交付商ID不能为空`);
    }
    if(params.id){
      where.id = this.trim(params.id);
    }
    if(params.status){
      where.status = this.trim(params.status);
    }
    if(params.beginDate && params.endDate){
      where.beginDate = this.trim(params.beginDate);
      where.endDate = this.trim(params.endDate);
    }
  
    where.currentPage = Number(params.currentPage || 1);
    where.pageSize = Number(params.pageSize || 10);

    where.startRow = (where.currentPage-1)*where.pageSize;

    try {
      let ordersCountRes = await this.oorderDao.ordersCount(where);
      let count = ordersCountRes[0]['orderCount'];
      if(count==0){
        return system.getResult({count:0,rows:[]});
      }
      let rows = await this.oorderDao.findAll(where);
      //格式化交付商
      await this.formateDeliver(rows);
      //格式化订单状态
      await this.formateStatus(rows);
      let res = {
        count,rows
      };
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 格式化订单交付商
   * @param {*} orderList
   */
  async formateDeliver(orderList) {
    let deliverIdList = [];
    for (let item of orderList) {
      if (item.deliver_id) {
        deliverIdList.push(item.deliver_id);
      }
    }

    let deliverMap = await this.dao.mapByIds(deliverIdList);
    for (let item of orderList) {
      item.odeliver = deliverMap[item.deliver_id] || {}
    }
  }

  /**
   * 处理订单状态数据
   * @param orderList
   * @returns {Promise<void>}
   */
  async formateStatus(orderList) {
    let ids = [];
    let statuses = [];
    for (let item of orderList) {
      ids.push(item.id);
      statuses.push(item.status);
    }

    let map = await this.oorderprocessDao.mapByOrderIdsAndStatus(ids, statuses);

    for (let item of orderList) {
      let key = item.id + "_" + item.status;
      let v = map[key] || {};
      item.statusName = v.name;
      item.next_status = JSON.parse(v.next_status || "[]");
    }
    console.log(orderList);
  }

  /**
   * 分配业务员(交付商)
   * @param {*} params
   * @id     String  订单ID
   * @operator_id  String  业务员ID
   * @status String 下一个状态码
   */
  async assignSalesman(params) {
    if (!params.bd_id) {
      return system.getResult(null, `参数错误 业务员ID不能为空`);
    }
    try {
      //更新订单业务员
      let _order = await this.findById(params.id);
      if (!_order) {
        return system.getResult(null, `订单不存在`);
      }
      //to do ... 验证下一个状态
      await this.statusAction(params);

      _order.bd_id = this.trim(params.bd_id);
      _order.status = this.trim(params.status);
      _order.bd_path = this.trim(params.bd_path);

      let res = await _order.save();
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 验证订单状态
   * @param params
   * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
   */
  async statusAction(params) {
    let _order = await this.oorderDao.findById(params.id);
    if (!_order) {
      return system.getResult(null, `订单不存在`);
    }
    //todo ...  验证状态
    let _orderStatus = await this.getOrderProcessStatus(_order.id, _order.status);
    let nextStatus = JSON.parse(_orderStatus.next_status);
    if (params.status != nextStatus.next_status) {
      return system.getResult(null, `订单状态错误，下一订单状态应该是${nextStatus.next_name}`);
    }
  }

  
}

module.exports = OorderdeliverService;