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

class IborderdzService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(IborderdzService));
    this.iborderbaseDao = system.getObject("db.order.iborderbaseDao");
    this.businessmenDao = system.getObject("db.business.businessmenDao");
  }

  /**
   * 创建订单
   * @param {*} params
   */
  async createOrder(params, t) {
    try {
      if (!params.merchantId) {
        return system.getResult(null, `参数错误 商户ID不能为空`);
      }
      if (!params.businessmentId) {
        return system.getResult(null, `参数错误 个体户ID不能为空`);
      }
      if (!params.orderpayId) {
        return system.getResult(null, `参数错误 支付ID不能为空`);
      }
      if (!Number(params.price) < 0) {
        return system.getResult(null, `参数错误 订单金额格式错误`);
      }
      this.trimObject(params);
      let _ibOrderDk = await this.dao.create(params, t);
      return system.getResult(_ibOrderDk);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 更新数据
   * @param {*} params
   * @param {*} t
   */
  async updateOrder(params, t) {
    try {
      if (!params.id) {
        return system.getResult(null, `参数错误 ID 不能为空`);
      }
      this.trimObject(params);
      return await this.dao.update(params, t);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 完善信息
   * @param {*} params
   *   legalName
   *   legalMobile
   *   names
   *   creditCode
   *   isBank
   *   businessScope
   */
  async completedOrder(params) {
    try {
      //1 检查个体户是否存在 （根据统一社会信用代码查个体工商户是否存在）
      this.trimObject(params);
      if (!params.id) {
        return system.getResult(null, `参数错误 ID 不能为空`);
      }
      if (!params.legalName) {
        return system.getResult(null, `参数错误 法人姓名不能为空`);
      }
      if (!params.legalMobile) {
        return system.getResult(null, `参数错误 法人电话不能为空`);
      }
      if (!params.creditCode) {
        return system.getResult(null, `参数错误 法人统一社会信用代码不能为空`);
      }
      if (!params.names) {
        return system.getResult(null, `参数错误 个体户名称不能为空`);
      }
      if (!params.businessScope) {
        return system.getResult(null, `参数错误 经营范围不能为空`);
      }
      params.order_id = params.id;
      //2 如果不存在添加保存个体户  完善信息
      let _businessmen = await this.businessmenDao.findOne({creditCode: this.trim(params.creditCode)});
      if (_businessmen) {
        //如果用户存在 直接更新
        let _iborderbase = await this.iborderbaseDao.findById(this.trim(params.id));
        if (!_iborderbase) {
          return system.getResult(null, `参数错误 订单不存在`);
        }
        let self = this;
        //向参数中添加 是否完善信息标识
        params.isInfoComplete = 1;
        var updateFields = {
          businessmen_id: self.trim(_businessmen.id),
          id: self.trim(params.id),
          isInfoComplete: 1
        };
        if (!_businessmen || !_businessmen.order_id) {
          updateFields.order_id = _iborderbase.id;
        }
        await this.db.transaction(async t => {
          //更新主表
          await self.iborderbaseDao.update(updateFields, t);
          //更新子表
          await this.dao.update(params, t);
        });
      } else {
        delete params.id;
        let self = this;
        await this.db.transaction(async t => {
          //如果不存在id 创建后更新
          let _businessment = await this.businessmenDao.create(params, t);
          //更新主表
          await self.iborderbaseDao.update({
            businessmen_id: self.trim(_businessment.id), id: self.trim(params.id),
            isInfoComplete: 1
          }, t);
          //更新子表
          await this.dao.update(params, t);
        });
      }
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单办理
   * @param {} params
   * businessmenId  个体户ID
   * id             订单ID
   */
  async handing(params) {
    try {
      let id = Number(params.id);
      let baseOrder = this.iborderbaseDao.findById(id);
      if (!baseOrder.isInfoComplete != 1) {
        return system.getResult(null, `请完善信息再注册`);
      }

      //1 检查个体户是否签约
      let _businessmen = await this.businessmenDao.findById(this.trim(params.businessmenId));
      if (!_businessmen.signTime) {
        return system.getResultFail(-2, "个体户未签约",-2);
      }

      let order = this.dao.findById(id);

      baseOrder.status = "1020";
      order.status = "1020";
      await baseOrder.save();
      await order.save();
      return system.getResultSuccess();
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息${error}`);
    }
  }

  async orderPage(params) {
    let currentPage = Number(params.currentPage || 1);
    let pageSize = Number(params.pageSize || 10);

    let statuses = params.statuses;

    var where = {};

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

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

    if (statuses && statuses.length > 0) {
      where.status = {
        [this.db.Op.in]: statuses
      }
    }

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);

    var page = await this.getPageList(currentPage, pageSize, where, orderby, null);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "status");

        this.handleDate(row, ["created_at"], null, -8);
      }
    }
    return system.getResultSuccess(page);
  }
}

module.exports = IborderdzService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });