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

class IborderService extends ServiceBase {
  constructor() {
    super("order", ServiceBase.getDaoName(IborderService));

    this.iborderdeliverDao = system.getObject("db.order.iborderdeliverDao");
    this.microsveClient = system.getObject("util.microsve.microsveClient");

    this.businessmenDao = system.getObject("db.business.businessmenDao");
  }

  async api(params) {
    try {
      return await this.saveSign(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiAllList(params) {
    try {
      return await this.allList(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiAdd(params) {
    try {
      return await this.add(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiUpd(params) {
    try {
      return await this.upd(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiInfo(params) {
    try {
      return await this.info(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiAllInfo(params) {
    try {
      return await this.infoAll(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiAssign(params) {
    try {
      return await this.assign(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiEdit(params) {
    try {
      return await this.edit(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiMyPage(params) {
    try {
      return await this.myPage(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiOrderPay(params) {
    try {
      return await this.orderPay(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiByChannelOrderId(params) {
    try {
      return await this.byChannelOrderId(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }


  async apiOrderClose(params) {
    try {
      return await this.orderClose(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiCloseById(params) {
    try {
      return await this.closeById(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiComplete(params) {
    try {
      return await this.complete(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiByDeliverId(params) {
    try {
      return await this.byDeliverId(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiStatTransData(params) {
    try {
      return await this.statTransData(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiStatBusinessData(params) {
    try {
      return await this.statBusinessData(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }


  // -----------------------以此间隔，上面为API下面为service---------------------------------

  async createOrder(params, t) {
    // 产品项
    var order = {};
    // 赋值
    for (var k in params) {
      order[k] = params[k];
    }
    order.productItems = (order.productItems || []).join(",");
    order.status = "1010";

    var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus(order.status);
    if (busiStatus) {
      order.ostatus = busiStatus.ostatus;
    }

    // 三方渠道号
    order.channelOrderNo = this.trim(params.channelOrderNo);

    // 订单资料信息
    order.legalName = this.trim(params.legalName);
    order.legalMobile = this.trim(params.legalMobile);

    order = await this.dao.create(order, t);
    return system.getResultSuccess({
      orderNo: order.id
    });
  }

  async statTransData(params) {
    var result = {
      orderCount: 0,
      orderPrice: 0,
    };
    var type = Number(params.type || 1);

    var begin, end;
    // 取开始时间
    if (type == 1) {
      begin = moment().format("YYYY-MM") + "-01 00:00:00";
    } else if (type == 2) {
      begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
    }

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

    // 处理查询业务
    if (type == 1 || type == 2) { // 取结束时间
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
      days = this.getDays(end);
      // 按天统计
      var dayMap = await this.dao.statDayByTime(begin, end);
      //days = this.getDays(end);
      for (var day of days) {
        var ditem = dayMap[day] || {};
        dayCounts.push(ditem.orderCount || 0);
        priceCounts.push(system.f2y(ditem.orderPrice || 0));
      }
    } else {
      var monthMap = await this.dao.statMonthByTime(begin, end);
      var bm = monthMap.begin || "";
      var em = monthMap.end || "";
      if (bm && em) {
        // 开始月份-结束月份所有月份
        var curMonth = bm;
        while (true) {
          days.push(curMonth);
          if (curMonth == em) {
            break;
          }
          curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
        }
      }
      for (var day of days) {
        var ditem = monthMap[day] || {};
        dayCounts.push(ditem.orderCount || 0);
        priceCounts.push(system.f2y(ditem.orderPrice || 0));
      }
    }

    var orderData = await this.dao.statOrderByTime(begin, end) || {};
    result.orderCount = orderData.orderCount;
    result.orderPrice = system.f2y(orderData.orderPrice);

    result.days = days;
    result.dayCounts = dayCounts;
    result.priceCounts = priceCounts;
    return system.getResultSuccess(result);
  }

  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;
  }

  async statBusinessData(params) {
    var result = {};
    var type = Number(params.type || 1);
    // 查 已完成订单，待分配订单，待审核订单，办理中订单
    var begin, end;
    // 取开始时间
    if (type == 1) {
      begin = moment().format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    } else if (type == 2) {
      begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
      end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    }

    // 先按照订单状态查他妈的
    var statMap = await this.dao.statByStatus(begin, end);
    // 所有状态
    // "1000": "未付款", "1010": "订单关闭", "1020": "待分配", "1030": "待处理", "1040": "交付商关闭", 
    // "1050": "执照办理中", "1060": "已出执照", "1070": "刻章办理中", "1080": "已刻章", "1090": "银行开户中", 
    // "1100": "银行卡已开户", "1110": "税务报道中", "1120": "已税务报道", "1130": "待审核", "1140": "审核失败", 
    // "1150": "审核通过", "1160": "已邮寄", "1170": "已完成",
    // 
    // 已完成 1100
    result.completeCount = this.addStatCount(statMap, ['1100']);
    // 待分配
    result.toApplyCount = this.addStatCount(statMap, ['1020']);
    // 待审核 1130 1140
    result.toAuditCount = this.addStatCount(statMap, ['1130']);
    // 办理中 1030, 1050, 1060, 1070, 1080, 1090, 1100, 1110, 1120, 1130, 1140, 1150, 1160
    result.handlingCount = this.addStatCount(statMap, ["1030", "1050", "1060", "1070", "1080", "1090", "1100", "1110", "1120", "1130", "1140", "1150", "1160"]);
    return system.getResultSuccess(result);
  }

  addStatCount(statusMap, statuses) {
    var count = 0;
    if (!statuses) {
      return count;
    }

    for (var status of statuses) {
      count = count + Number(statusMap[status] || 0);
    }
    return count;
  }

  async byDeliverId(params) {
    var od = await this.dao.findOne({
      orderDeliverId: params.orderDeliverId
    });
    return system.getResultSuccess(od);
  }

  async orderPay(params) {
    var order = await this.findById(params.id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus(order.status);

    if (busiStatus.next != "1020") {
      return system.getResult(null, "当前订单不允许支付");
    }
    var nextBusi = await this.orderBusinessStatus.findOrderBusinessStatus(busiStatus.next);

    order.status = nextBusi.status;
    order.ostatus = nextBusi.ostatus;

    await order.save();
    return system.getResultSuccess();
  }

  async add(params) {
    var order = {};
    order.price = Number(params.price || 300000);
    order.status = "1000";

    var merchantId = params.merchantId || params.merchant_id;
    if (merchantId) {
      var exists = await this.dao.findOne({
        merchant_id: this.trim(merchantId),
        channelOrderNo: this.trim(params.channelOrderNo),
      });
      if (exists) {
        return system.getResult(null, "订单号【" + params.channelOrderNo + "】重复");
      }
      var merchantData = await this.microsveClient.call("merchant", "getById", {
        "id": merchantId
      });
      if (merchantData.status != 0) {
        return merchantData;
      }

      var merchant = merchantData.data;
      if (!merchant.mustPay) {
        order.price = 0;
        order.status = "1020";
      }
    }

    var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus(order.status);
    if (busiStatus) {
      order.ostatus = busiStatus.ostatus;
    }

    // 商户id
    order.merchant_id = this.trim(merchantId);

    // 三方渠道号
    order.channelOrderNo = this.trim(params.channelOrderNo);

    // 订单资料信息
    order.legalName = this.trim(params.legalName);
    order.legalMobile = this.trim(params.legalMobile);
    order.legalImg = this.trim(params.legalImg);
    order.idcard = this.trim(params.idcard);
    order.idcardFront = this.trim(params.idcardFront);
    order.idcardBack = this.trim(params.idcardBack);
    order.bankNo = this.trim(params.bankNo);
    order.bank = this.trim(params.bank);
    order.bankImg = this.trim(params.bankImg);
    order.names = this.trim(params.names);
    order.capital = this.trim(params.capital);

    order.domicile_id = this.trim(params.domicileId);
    order.domicileName = this.trim(params.domicileName);

    // 个体户经营范围
    order.businessScope_id = this.trim(params.businessScopeId);
    order.businessType = this.trim(params.businessType);
    order.businessScope = this.trim(params.businessScope);
    order.bdId = this.trim(params.bdId);
    order.bdPath = this.trim(params.bdId);

    // 邮寄地址
    order.mailAddr = this.trim(params.mailAddr);
    order.mailTo = this.trim(params.mailTo);
    order.mailMobile = this.trim(params.mailMobile);

    order.userId = this.trim(params.userId);

    // var baseOrder = {};
    // baseOrder = await this.baseorderDao.create(baseOrder);
    // order.id = baseOrder.id;

    order = await this.dao.create(order);
    return system.getResultSuccess({
      orderNo: order.id
    });
  }

  async upd(params) {
    var merchantId = params.merchantId || params.merchant_id;

    var order = await this.dao.findOne({
      merchant_id: this.trim(merchantId),
      channelOrderNo: this.trim(params.channelOrderNo),
    });

    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    // 商户id
    order.merchant_id = this.trim(merchantId);

    // 订单资料信息
    order.legalName = this.trim(params.legalName);
    order.legalMobile = this.trim(params.legalMobile);
    order.legalImg = this.trim(params.legalImg);
    order.idcard = this.trim(params.idcard);
    order.idcardFront = this.trim(params.idcardFront);
    order.idcardBack = this.trim(params.idcardBack);
    order.bankNo = this.trim(params.bankNo);
    order.bank = this.trim(params.bank);
    order.bankImg = this.trim(params.bankImg);
    order.names = this.trim(params.names);
    order.capital = this.trim(params.capital);

    order.domicile_id = this.trim(params.domicileId);
    order.domicileName = this.trim(params.domicileName);

    // 个体户经营范围
    order.businessScope_id = this.trim(params.businessScopeId);
    order.businessType = this.trim(params.businessType);
    order.businessScope = this.trim(params.businessScope);

    // 邮寄地址
    order.mailAddr = this.trim(params.mailAddr);
    order.mailTo = this.trim(params.mailTo);
    order.mailMobile = this.trim(params.mailMobile);

    order = await order.save();
    return system.getResultSuccess({
      orderNo: order.id
    });
  }


  // 全部订单
  async allList(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var merchantId = this.trim(params.merchantId);
    var channelOrderNo = this.trim(params.channelOrderNo);
    var orderId = this.trim(params.orderId);
    var status = this.trim(params.status);

    var where = {};

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

    if (merchantId) {
      where.merchant_id = merchantId;
    }
    if (orderId) {
      where.id = orderId;
    }
    if (status) {
      where.status = status
    }

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

    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");
        await this.dao.setRowCodeName(row, "ostatus");
        await this.dao.setRowCodeName(row, "deliverType");


        this.handleDate(row, ["created_at", "assignTime"], null, -8);
      }
      // 设置交付商
      await this.setDeliver(page.rows);
    }

    return system.getResultSuccess(page);
  }

  async setDeliver(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    var orderDeliverIds = [];
    for (var row of rows) {
      orderDeliverIds.push(row.orderDeliverId);
    }

    var deliverMap = await this.iborderdeliverDao.findMapByIds(orderDeliverIds);
    for (var row of rows) {
      row.deliver = deliverMap[row.orderDeliverId] || {};
      this.handleDate(row.deliver, ["created_at", "updated_at"], null, -8);
    }
  }

  async myPage(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var bdId = this.trim(params.bdId);
    var userId = this.trim(params.userId);
    var bdPath = this.trim(params.bdPath);
    var ostatuses = params.ostatuses;

    var where = {};

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

    if (bdId) {
      where.merchant_id = bdId;
    }
    if (bdPath && bdPath.length > 0) {
      where.id = {
        [this.db.Op.like]: bdPath + "%"
      }
    }
    if (userId) {
      where.userId = userId;
    }
    if (ostatuses && ostatuses.length > 0) {
      where.ostatus = {
        [this.db.Op.in]: ostatuses
      }
    }

    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");
        await this.dao.setRowCodeName(row, "ostatus");
        await this.dao.setRowCodeName(row, "deliverType");

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

  async info(params) {
    var row = await this.dao.getById(params.id);
    if (!row) {
      return system.getResult(null, "订单不存在");
    }
    await this.dao.setRowCodeName(row, "status");
    await this.dao.setRowCodeName(row, "deliverType");

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


  async byChannelOrderId(params) {
    var merchantId = params.merchantId || params.merchant_id;
    var row = await this.dao.model.findOne({
      where: {
        merchant_id: merchantId,
        channelOrderNo: this.trim(params.channelOrderNo),
      },
      raw: true
    });

    if (!row) {
      return system.getResult(null, "订单不存在");
    }
    await this.dao.setRowCodeName(row, "status");
    await this.dao.setRowCodeName(row, "ostatus");
    await this.dao.setRowCodeName(row, "deliverType");

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

  async infoAll(params) {
    var row = await this.dao.getById(params.id);
    if (!row) {
      return system.getResult(null, "订单不存在");
    }
    await this.dao.setRowCodeName(row, "status");
    await this.dao.setRowCodeName(row, "deliverType");

    this.handleDate(row, ["created_at", "assignTime"], null, -8);

    // 个体户
    var businessmen = await this.businessmenDao.getByOrderId(params.id);
    if (businessmen) {
      await this.businessmenDao.setRowCodeName(businessmen, "bstatus");
      await this.businessmenDao.setRowCodeName(businessmen, "gstatus");
      await this.businessmenDao.setRowCodeName(businessmen, "dstatus");
      this.handleDate(businessmen, ["created_at", "updated_at"], null, -8);
    }
    row.businessmen = businessmen || {};

    // 交付商
    row.deliver = await this.iborderdeliverDao.getById(row.orderDeliverId) || {};
    await this.iborderdeliverDao.setRowCodeName(row.deliver, "status");
    this.handleDate(row.deliver, ["created_at", "updated_at"], null, -8);

    return system.getResultSuccess(row);
  }

  // 订单编辑，只编辑指定几个字段，暂时只有merchant_id和价格
  async edit(params) {
    var id = params.id;
    var merchantId = this.trim(params.merchantId);
    var price = Number(params.price || 0);

    var order = await this.findById(id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    order.merchant_id = merchantId;
    if ("1000" == order.status) {
      order.price = price;
    }

    order = await order.save();
    return system.getResultSuccess();
  }

  // 订单分配
  async assign(params) {
    var orderId = this.trim(params.id);

    var order = await this.findById(orderId);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    if (order.status != "1020") {
      return system.getResult(null, "该订单状态不允许分配，请刷新重试");
    }

    if (order.orderDeliverId) {
      return system.getResult(null, "该订单已分配，不允许再次分配");
    }

    order.status = "1030";
    order.assignTime = new Date();
    order.assignUcname = this.trim(params.assignUcname);

    var orderDeliver = {};
    orderDeliver.order_id = orderId;
    orderDeliver.status = "1030";
    orderDeliver.deliver_id = this.trim(params.deliverId);
    orderDeliver.deliverName = this.trim(params.deliverName);
    orderDeliver.deliverDivide = Number(params.deliverDivide || 0);

    // 创建交付商订单
    orderDeliver = await this.iborderdeliverDao.create(orderDeliver);
    order.orderDeliverId = orderDeliver.id;
    // 订单更改状态
    await order.save();

    return system.getResultSuccess();
  }

  async updPrice(params) {
    var orderId = this.trim(params.orderId);

    var merchantId = this.trim(params.merchantId);
    var price = Number(params.price || 0);

    var order = await this.findById(orderId);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    order.price = price;
    order.merchant_id = merchant;

    await order.save();
    return system.getResultSuccess();
  }

  async closeById(params) {
    var order = await this.dao.findById(params.id);

    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    if (order.status != 1000) {
      var statusName = await this.dao.getRowCodeName(order, "ostatus");
      return system.getResult(null, "订单状态处于【" + statusName + "】，不允许关闭");
    }

    var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus("1010");
    order.status = busiStatus.status;
    order.ostatus = busiStatus.ostatus;

    await order.save();
    return system.getResultSuccess({
      orderNo: order.id
    });
  }

  async orderClose(params) {
    var order = await this.dao.findOne({
      merchant_id: this.trim(params.merchantId),
      channelOrderNo: this.trim(params.channelOrderNo),
    });

    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    if (order.status != 1000) {
      var statusName = await this.dao.getRowCodeName(order, "ostatus");
      return system.getResult(null, "订单状态处于【" + statusName + "】，不允许关闭");
    }

    var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus("1010");
    order.status = busiStatus.status;
    order.ostatus = busiStatus.ostatus;

    await order.save();
    return system.getResultSuccess({
      orderNo: order.id
    });
  }

  async complete(params) {
    var order = await this.dao.findById(params.id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }

    await this.dao.setRowCodeName(order, "status");
    if (order.status != "1160") {
      return system.getResult(null, "订单状态错误【" + order.statusName + "】，不允许该状态下完成订单");
    }

    var businessmen = await this.businessmenDao.getByOrderId(params.id);

    var self = this;
    await this.db.transaction(async function (t) {
      var orderFields = {
        status: "1170",
        ostatus: "1170",
        id: order.id,
        deliverType: self.trim(params.deliverType),
        deliverNo: self.trim(params.deliverNo),
        deliverImg: self.trim(params.deliverImg),
      }
      await self.dao.update(orderFields, t);
      await self.businessmenDao.update({
        id: businessmen.id,
        bstatus: "2010",
      }, t);
      return 1;
    });

    return system.getResultSuccess();
  }
}

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