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

/**
 * 订单产品表
 */
class OorderService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(OorderService));

    this.oorderinforegDao = system.getObject("db.order.oorderinforegDao");
    this.oorderdeliverDao = system.getObject("db.order.oorderdeliverDao");
    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");
  }

  /**
   *  新增渠道订单
   * @returns {Promise<void>}
   */
  async addSourceOrder(params) {
    // 整理参数
    let order = {
      merchant_id: "",
      channel_order_no: "",
      busi_type: 1,
      busi_id: "",
      price: 0,
    };
    order.product_id = Number(params.product_id);
    order.source_id = Number(params.source_id);
    order.source_no = this.trim(params.source_no);
    order.notes = this.trim(params.notes);
    order.contact_mobile = this.trim(params.contact_mobile);

    // 验证订单是否存在
    let exists = await this.dao.findOne({source_id: order.source_id, source_no: order.source_no});
    if (exists) {
      return system.getResult(null, `订单号${order.source_no}已存在`);
    }

    // 验证来源
    let source = await this.osourceDao.findById(order.source_id);
    if (!source) {
      return system.getResult(null, "来源错误");
    }

    // 验证产品
    let product = await this.oproductDao.findById(order.product_id);
    if (!product) {
      return system.getResult(null, "产品错误");
    }

    // 构建订单流程列表
    let orderProcessList = await this.buildOrderProcess(order.product_id);
    if (!orderProcessList || orderProcessList.length == 0) {
      return system.getResult(null, "产品流程未配置");
    }

    order.status = orderProcessList[0].status;
    // 开启事务
    var self = this;
    await this.db.transaction(async function (t) {
      // 插入订单数据
      order = await self.dao.create(order, t);

      // 插入订单状态数据
      for (let op of orderProcessList) {
        op.order_id = order.id;
      }
      await self.oorderprocessDao.bulkCreate(orderProcessList, t);
      return order;
    });

    return order;
  }

  /**
   * 新建进度
   * @param params
   * @returns {Promise<void>}
   */
  async createProcess(params) {
    // 整理参数 变成这个格式，id, status, params

    // 查询订单

    // 找出订单下个状态，于参数订单状态匹配

    // 调用状态func(order, nextObj, params)
  }

  /**
   * 构建产品流程对象
   * @param productPid
   * @param chooseProductIds
   * @returns {Promise<void>}
   */
  async buildOrderProcess(productPid, chooseProductIds) {
    // 查询所有产品子项
    let productList = await this.oproductDao.findListByPid(productPid);

    // 根据所选产品id, 查询产品流程
    let productIds = [];
    for (let product of productList) {
      // 过滤未选择产品
      if (product.is_choose && chooseProductIds && chooseProductIds.indexOf(product.id) == -1) {
        continue;
      }
      productIds.push(product.id);
    }
    if (productIds.length == 0) {
      return null;
    }

    // 查询产品流程
    let productProcessMap = await this.oproductprocessDao.findMapByProductProductIds(productPid, productIds);
    // 产品流程ids
    let processIds = [];
    for (var idx in productProcessMap) {
      let plist = productProcessMap[idx];
      if (!plist) {
        continue;
      }
      for (let p of plist) {
        processIds.push(p.process_id);
      }
    }

    // 批量查流程
    let processMap = await this.oprocessDao.findMapByIds(processIds);

    let orderProcessList = [];

    for (let productId of productIds) {
      // 产品子项流程列表
      let productProcessList = productProcessMap[productId];
      if (!productProcessList || productProcessList.length == 0) {
        continue;
      }

      for (let idx = 0; idx < productProcessList.length; idx++) {
        // 风还钻该处理每一个子项流程 变为 订单流程对象
        let productProcess = productProcessList[idx];
        let process = processMap[productProcess.process_id];
        let orderProcess = {
          product_id: productPid,
          name: process.name,
          status: process.status,
          func: productProcess.func,
          next_status: productProcess.next_status,
          name1: productProcess.name1,
          name2: productProcess.name2,
          name3: productProcess.name3,
          name4: productProcess.name4,
          sort: productProcess.sort,
          autoIncrement: true
      };
        // 上一个产品流程于当前产品流程连接
        if (idx == 0 && orderProcessList.length > 0) {
          let lastProcess = orderProcessList[orderProcessList.length - 1];
          lastProcess.next_status = productProcess.process_id;
        }
        orderProcessList.push(orderProcess);
      }
    }
    return orderProcessList;
  }

  /**
   * 订单管理列表
   * @param {*} params 
   */
  async orders(params){
    let where = {};
    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);
    }
    if(params.deliver_id){
      where.deliver_id = this.trim(params.deliver_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.ordersCount(where);
      let count = ordersCountRes[0]['orderCount'];
      let rows = await this.dao.findAll(where);
      //格式化订单来源
      this.formateSource(rows);
      //格式化订单产品
      this.formateProduct(rows);
      //格式化交付商
      this.formateDeliver(rows);
      //格式化业务员
      

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

  /**
   * 格式化列表来源数据
   * @param {*} orderList 
   */
  async formateSource(orderList){
    let sourceIdList=[];
    for (let item of orderList) {
      if(item.source_id){
        sourceIdList.push(item.source_id);
      }
    }
    
    let sourceMap = await this.osourceDao.mapByIds(sourceIdList);
    for (let item of orderList) {
      item.osource = sourceMap[item.source_id] || {}
    }
  }

  /**
   * 格式化订单产品
   * @param {*} orderList 
   */
  async formateProduct(orderList){
    let productIdList=[];
    for (let item of orderList) {
      if(item.product_id){
        productIdList.push(item.product_id);
      }
    }
    
    let productMap = await this.oproductDao.mapByIds(productIdList);
    for (let item of productMap) {
      item.oproduct = productMap[item.product_id] || {}
    }
  }

  /**
   * 格式化订单交付商
   * @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.oorderdeliverDao.mapByIds(deliverIdList);
    for (let item of deliverMap) {
      item.odeliver = deliverMap[item.deliver_id] || {}
    }
  }


  /**
   * 分配业务员
   * @param {*} params 
   * @id     String  订单ID
   * @bd_id  String  业务员ID
   * @status String 下一个状态码
   * @bd_path 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 ... 验证下一个状态



      _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 
   * @id  String 订单ID
   * @deliver_id String 交付商ID
   * @deliver_name String 交付商名称
   * @deliver_deliver String 交付商分成
   * @status String 下一个状态码 
   */
  async assignDeliver(params){
    //参数验证
    if(!params.id){
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if(!params.deliver_id){
      return system.getResult(null, `参数错误 交付商ID不能为空`);
    }
    if(!params.hasOwnProperty(`deliver_divide`)){
      return system.getResult(null, `参数错误 交付商分成不能为空`);
    }
    
    try {
      //todo ...  验证状态
      
    
      let _order= await this.findById(params.id);
      if(!_order){
        return system.getResult(null,`订单不存在`);
      }
      let self = this;
      let res = await this.db.transaction(t => {

        //创建orderdeliver记录
        await this.oorderdeliverDao.create({
          order_id: self.trim(params.id),
          deliver_id:self.trim(self.deliver_id),
          deliver_name:self.trim(self.deliver_name),
          deliver_divide:self.trim(self.deliver_divide),
        }, t);
        
        //更新oorder订单记录
        await self.dao.update({
          deliver_id:self.trim(self.deliver_id),
          id:self.trim(params.id),
          status:self.trim(params.status)
        },t);

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



}

module.exports = OorderService;