const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const moment = require("moment");
/**
 * 订单交付
 */
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 
   * @operator_id 业务员ID
   * @id String 订单号
   * @status String 订单状态
   * @operator_id String 交付商业务员
   */
  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.saas_id){
      where.saas_id = this.trim(params.saas_id);
    }
    //交付商订单表条件
    if (params.createdBegin && params.createdEnd) {
      where.createdBegin = this.trim(params.createdBegin);
      where.createdEnd = this.trim(params.createdEnd);
    }
    if (params.operator_id) {
      where.operator_id = this.trim(params.operator_id);
    }

    //下面是订单条件
    if (params.id) {
      where.id = this.trim(params.id);
    }
    if (params.status) {
      where.status = this.trim(params.status);
    }
    if (params.order_id) {
      where.order_id = this.trim(params.order_id);
    }

    where.currentPage = Number(params.currentPage || 1);
    where.pageSize = Number(params.pageSize || 10);

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

    try {
      let ordersCountRes = await this.dao.ordersdeliverCount(where);
      let count = ordersCountRes[0]['orderCount'];
      if (count == 0) {
        return system.getResult({ count: 0, rows: [] });
      }
      let rows = await this.dao.findOrders(where);
      //格式化订单状态
      await this.formateStatus(rows);

      await this.formateServiceItems(rows);

      for (var row of rows) {
        this.handleDate(row, ["created_at", "completed_at"], "YYYY-MM-DD HH:mm:ss");
      }

      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.name1 = v.name1;
      item.name2 = v.name2;
      item.name3 = v.name3;
      item.name4 = v.name4;
      item.next_status = JSON.parse(v.next_status || "[]");
    }
    console.log(orderList);
  }

  async formateServiceItems(orderList) {
    let ids = [];
    let statuses = [];
    for (let item of orderList) {
      let productIds = this.trim(item.service_items).split(",");
      ids = ids.concat(productIds);
    }

    let productMap = await this.oproductDao.mapByIds(ids);
    for (let item of orderList) {
      let productIds = this.trim(item.service_items).split(",");
      let names = [];
      for (var productId of productIds) {
        let product = productMap[productId];
        if (product) {
          names.push(product.name);
        }
      }
      item.service_items_name = names.join(",");
    }
  }

  /**
   * 平台数据概览（交付商数据）
   * @param {*} params 
   */
  async statDeliverData(params) {

    if (!params.current_date) {
      return system.getResult(null, `参数错误 当前时间不能为空`);
    }
    try {
      let begin, end;
      begin = moment(params.current_date).format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
      let deliverList = await this.dao.deliverList(begin, end);
      let deliverSet = new Set();
      for (let item of deliverList) {
        deliverSet.add(item.deliver_id);
      }
      let _deliverArr = Array.from(deliverSet);

      let orderCompletes = {};
      let orderHanding = {};
      if(_deliverArr.length > 0) {
        orderCompletes = await this.dao.orderCompletesCount(_deliverArr, begin, end) ;
        orderHanding = await this.dao.orderHandingCount(_deliverArr, begin, end) ;
      }

      for (let item of deliverList) {
        item.order_complete_count = orderCompletes[item.deliver_id] || 0;
        item.order_handing_count = orderHanding[item.deliver_id] || 0;
      }

      return system.getResult(deliverList);
    } catch (error) {
      console.log(error);
      return system.getResult(error);
    }
  }

  /**
   * 交付商订单统计
   * @param {*} params 
   */
  async deliverStatTransData(params) {
    if (!params.current_date) {
      return system.getResult(null, `参数错误 当前时间不能为空`);
    }
    if (!params.deliver_id) {
      return system.getResult(null, `参数错误 交付商不能为空`);
    }
    try {
      var result = {
        orderCount: 0,
        orderPrice: 0,
      };
      var begin, end;
      // 取开始时间和结束时间
      begin = moment(params.current_date).format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";

      // echart数据  开始
      var days = [];
      var dayCounts = [];
      var priceCounts = [];

      // 处理查询业务
      days = this.getDays(end);
      // 按天统计
      var dayMap = await this.dao.statDayByTime(begin, end, this.trim(params.deliver_id));
      for (var day of days) {
        var ditem = dayMap[day] || {};
        dayCounts.push(ditem.orderCount || 0);
        priceCounts.push(system.f2y(ditem.orderPrice || 0));
      }

      //echart数据 结束

      //当月订单的数量统计和订单总金额
      var orderData = await this.dao.statOrderByTime(begin, end, this.trim(params.deliver_id)) || {};
      if(!orderData){
        result.orderCount = 0;
        result.orderPrice = 0;
      }else{
        result.orderCount = orderData[orderData.begin]?orderData[orderData.begin]["orderCount"] : 0;
        result.orderPrice = orderData[orderData.begin]?system.f2y(orderData[orderData.begin]["orderPrice"]): 0;  
      }
      result.days = days;
      result.dayCounts = dayCounts;
      result.priceCounts = priceCounts;
      return system.getResult(result);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  getDays(end) {
    var days = [];
    var month = moment(end).format("YYYY-MM");
    var endDay = Number(moment(end).format("DD"));
    for (var i = 1; i <= endDay; i++) {
      if (i < 10) {
        days.push(month + "-0" + i);
      } else {
        days.push(month + "-" + i);
      }
    }
    return days;
  }

  /**
   * 业务办理
   * @param {*} params 
   */
  async businessManagement(params) {
    if (!params.current_date) {
      return system.getResult(null, `参数错误 当前时间不能为空`);
    }
    if (!params.deliver_id) {
      return system.getResult(null, `参数错误 交付商不能为空`);
    }
    try {
      var begin, end;
      // 取开始时间和结束时间
      begin = moment(params.current_date).format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
      //已经完成
      let orderCompleteRes = await this.dao.orderComplete(begin, end,this.trim(params.deliver_id));
      //办理中
      let orderHandlingRes = await this.dao.orderHanding(begin, end,this.trim(params.deliver_id));
      return system.getResult({
        orderCompleteCount:orderCompleteRes[0]['count'],
        orderHandlingCount:orderHandlingRes[0]["count"]
      });

    } catch (error) {
      console.log(error);
      return system.getResult(error);
    }
  }

}

module.exports = OorderdeliverService;