const system = require("../../system");
const ServiceBase = require("../sve.base");
class BmorderService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(BmorderService));
    //this.appDao=system.getObject("db.appDao");
    this.bmuserbizDao = system.getObject("db.bmuserbizDao");
    this.statusMap = {
      0: "待审核", 1: "审核通过", 2: "审核驳回",
    };
  }

  async saveOrderBiz(orderData) {
    var order = orderData.order;
    var userbiz = orderData.userbiz;

    var self = this;
    return this.db.transaction(async function (t) {
      // 创建订单
      order = await self.dao.create(order, t);
      userbiz.orderId = order.id;

      // 创建用户材料
      userbiz = await self.bmuserbizDao.create(userbiz, t);
      return order;
    });
  }


  async pageByCondition(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    if (params.userId) {
      where.userId = params.userId;
    }

    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "merchantId", "companyId", "userId", "orderNo", "status", "auditStatus", "auditId", "rejectReason", "ownerId", "created_at", "updated_at"];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      await this.setBizs(page.rows);
      await this.setStatusName(page.rows);
      for (var row of page.rows) {
        this.handleDate(row, ["created_at", "updated_at"], null, -8);
      }
    }
    return page;
  }


  /**
   * 根据状态查询订单列表  0待审核 1审核通过 2审核驳回
   * @param {*} params 
   */
  async unauditOrders(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {
      auditStatus: params.auditStatus,
      merchantId: params.merchantId,
    }

    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "merchantId", "companyId", "userId", "orderNo", "status", "auditStatus", "auditId", "rejectReason", "ownerId", "created_at", "updated_at"];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      await this.setBizs(page.rows);
      await this.setStatusName(page.rows);
      for (var row of page.rows) {
        this.handleDate(row, ["created_at", "updated_at"], null, -8);
      }
    }
    return page;
  }

  /**
   * 审核
   */
  async audit(params) {
    try {
      await this.dao.model.update({
        auditId: params.auditId,
        rejectReason: params.rejectReason,
        auditStatus: params.auditStatus
      }, {
        where: {
          id: params.id
        }
      });
      return {
        code: 1,
        msg: "success"
      };
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息${error}`);
    }
  }

  /**
   * 更新订单
   * @param {*} params 
   */
  async updateOrder(params) {
    try {
      let { order, userbiz, loginUser } = params;
      let self = this;
      let res = await this.db.transaction(async function (t) {
        // 创建订单
        await self.dao.model.update(order, { where: { id: order.id } }, t);

        // 创建用户材料
        await self.bmuserbizDao.model.update(userbiz, {
          where: {
            orderId: order.id
          }
        }, t);
      });
      return {
        code: 1,
        msg: "success",
        data: res
      };
    } catch (error) {
      console.log(error);
      return system.getResult(null, error);
    }
  }
  /**
   * 查询明细
   * @param {*} params 
   */
  async queryOrderInfo(params) {
    if (!params.id) {
      return system.getResult(null, `参数错误 订单ID 不能为空`);
    }

    try {
      let order = await this.findById(params.id);
      if (!order) {
        return system.getResult(null, `订单不存在`);
      }
      order.dataValues.auditStatusName = this.statusMap[order.auditStatus];
      order.dataValues.statusName = order.dataValues.auditStatusName;
      let child = await this.bmuserbizDao.findOne({ orderId: params.id });
      order.dataValues.child = child || {};
      return {
        code: 1,
        msg: "success",
        orderInfo: order
      };
    } catch (error) {
      console.log(error);
      return system.getResult(null, error);
    }
  }


  async setBizs(list) {
    if (!list || list.length == 0) {
      return;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.id || 0);
    }
    var bizMap = await this.bmuserbizDao.findMapByOrderIds(ids);
    for (var item of list) {
      item.userbiz = bizMap["id_" + (item.id || 0)];
    }
  }

  async setStatusName(list) {
    if (!list || list.length == 0) {
      return;
    }

    for (var item of list) {
      item.auditStatusName = this.statusMap[item.auditStatus];
    }
  }

}
module.exports = BmorderService;
