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

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

    this.iborderDao = system.getObject("db.order.iborderDao");

    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 apiPage(params) {
    try {
      return await this.page(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 apiEdit(params) {
    try {
      return await this.edit(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

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

  async apiHandle(params) {
    try {
      var id = params.id;
      var status = params.status;

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

      var order = await this.iborderDao.findById(dorder.order_id);
      await this.iborderDao.setRowCodeName(order, "status");

      var busiStatus = await this.orderBusinessStatus.findOrderBusinessStatus(order.status);
      var nextObj = await this.orderBusinessStatus.findOrderBusinessStatus(busiStatus.next);

      if (status == '1130') {
        if (order.status != '1120' && order.status != '1140') {
          return system.getResult(null, "订单状态【" + order.statusName + "】，不允许提交审核");
        }
        nextObj = await this.orderBusinessStatus.findOrderBusinessStatus("1130");
      } else if (status != busiStatus.next && busiStatus.next) {
        if (!nextObj) {
          return system.getResult(null, "订单进度错误");
        }
        return system.getResult(null, "订单状态错误，应该新建【" + nextObj.name + "】进度");
      }

      params.nextObj = nextObj;
      // "1050": "执照办理中",      "1060": "已出执照",
      // "1070": "刻章办理中",      "1080": "已刻章",
      // "1090": "银行开户中",      "1100": "银行卡已开户",
      // "1110": "税务报道中",      "1120": "已税务报道",
      // "1130": "提交审核",      "1140": "审核失败",      "1150": "审核通过",
      // "1160": "已邮寄",
      switch (params.status) {
        case "1050": // 执照办理中
        case "1070": // 刻章办理中
        case "1090": // 银行开户中
        case "1110": // 税务报道中
          return await this.changeStatus(params, dorder, order);
        case "1060": { // 已出执照
          return await this.status1060(params, dorder, order);
        }
        case "1080": { // 已刻章
          return await this.status1080(params, dorder, order);
        }
        case "1100": { // 银行已开户
          return await this.status1100(params, dorder, order);
        }
        case "1120": { // 已税务报道
          return await this.status1120(params, dorder, order);
        }
        case "1130": { // 提交审核
          return await this.status1130(params, dorder, order);
        }

        case "1160": { // 已邮寄
          return await this.status1160(params, dorder, order);
        }

        default:
          return system.getResult(null, "无法识别订单状态");
      }
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

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

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

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

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

    // 处理时间
    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 condition = {
      begin: begin,
      end: end,
    }

    // 查总数
    var total = await this.dao.countStat(condition);
    if (total == 0) {
      return system.getResultSuccess({
        count: 0,
        rows: []
      });
    }

    // 查条数
    var startRow = (currentPage - 1) * pageSize;
    var list = await this.dao.queryStat(condition, startRow, pageSize);

    // 设置已完成数量、办理中数量
    var deliverIds = [];
    for (var item of list) {
      deliverIds.push(item.deliver_id);
    }
    var dstatusMap = await this.dao.statDeliverByStatus({
      begin: begin,
      end: end,
      deliverIds: deliverIds
    });

    for (var item of list) {
      item.completeCount = this.addStatCount(dstatusMap, item.deliver_id, ['1160']);
      item.handlingCount = this.addStatCount(dstatusMap, item.deliver_id, ["1030", "1050", "1060", "1070", "1080", "1090", "1100", "1110", "1120", "1130", "1140", "1150"]);
    }
    return system.getResultSuccess({
      count: total,
      rows: list
    });
  }

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

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

  async info(params) {
    var id = params.id;

    var deliverOrder = await this.dao.getById(id);
    var order = await this.iborderDao.getById(deliverOrder.order_id);
    var businessmen = await this.businessmenDao.getByOrderId(deliverOrder.order_id);

    await this.dao.setRowCodeName(deliverOrder, "status");
    await this.iborderDao.setRowCodeName(order, "status");
    await this.businessmenDao.setRowCodeName(businessmen, "status");

    this.handleDate(deliverOrder, ["created_at", "updated_at"], null, -8);
    this.handleDate(order, ["created_at", "updated_at", "assignTime"], null, -8);
    this.handleDate(businessmen, ["created_at", "updated_at"], null, -8);
    this.handleDate(businessmen, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);

    system.f2y4list([order], ["price"]);
    system.f2y4list([deliverOrder], ["deliverDivide"]);

    return system.getResultSuccess({
      deliverOrder: deliverOrder,
      order: order,
      businessmen: businessmen,
    });
  }

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

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

    var where = {};

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

    if (deliverId) {
      where.deliver_id = deliverId;
    }

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

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);
    var page = await this.getPageList(currentPage, pageSize, where, orderby);
    if (page && page.rows) {
      await this.setOrder(page.rows, "`id`, `legalName`, `legalMobile`, `price`, `idcard`, `productItems` ");

      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "status");

        // 下一个状态
        await this.setNextStatus(row);
        // var nextObj = await this.orderBusinessStatus.findOrderNextBusinessStatus(row.status);
        // row.nextStatus = nextObj.status;
        // row.nextStatusName = nextObj.name;

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

  async setNextStatus(row) {
    if (!row) {
      return;
    }
    let items = this.trim(row.productItems);
    if (items) {
      let itemArr = items.split(",");

      // 当前订单状态
      let curStatus = row.status;
      let nextStatus = "";

      if (curStatus == "1030") {
        if(itemArr.indexOf("1050") != -1) {
          nextStatus = "1050";
        } else if (itemArr.indexOf("1070") != -1) {
          nextStatus = "1070";
        } else if (itemArr.indexOf("1090") != -1) {
          nextStatus = "1090";
        } else if (itemArr.indexOf("1110") != -1) {
          nextStatus = "1110";
        } else {
          nextStatus = await this.orderBusinessStatus.findOrderNextBusinessStatus(curStatus);
        }
      } else if(curStatus == "1050") {
        if (itemArr.indexOf("1070") != -1) {
          nextStatus = "1070";
        } else if (itemArr.indexOf("1090") != -1) {
          nextStatus = "1090";
        } else if (itemArr.indexOf("1110") != -1) {
          nextStatus = "1110";
        } else {
          nextStatus = await this.orderBusinessStatus.findOrderNextBusinessStatus(curStatus);
        }
      } else if (curStatus == "1070") {
        if (itemArr.indexOf("1090") != -1) {
          nextStatus = "1090";
        } else if (itemArr.indexOf("1110") != -1) {
          nextStatus = "1110";
        } else {
          nextStatus = await this.orderBusinessStatus.findOrderNextBusinessStatus(curStatus);
        }
      } else if (curStatus == "1090") {
        if (itemArr.indexOf("1110") != -1) {
          nextStatus = "1110";
        } else {
          nextStatus = await this.orderBusinessStatus.findOrderNextBusinessStatus(curStatus);
        }
      } else {
        nextStatus = await this.orderBusinessStatus.findOrderNextBusinessStatus(curStatus);
      }
      var nextObj = await this.orderBusinessStatus.findOrderBusinessStatus(nextStatus);
      row.nextStatus = nextObj.status;
      row.nextStatusName = nextObj.name;
      return;
    }

    var nextObj = await this.orderBusinessStatus.findOrderNextBusinessStatus(row.status);
    row.nextStatus = nextObj.status;
    row.nextStatusName = nextObj.name;
  }

  async setOrder(rows, attrs) {
    if (!rows || rows.length == 0) {
      return;
    }
    var ids = [];
    for (var row of rows) {
      ids.push(row.order_id);
    }

    var map = await this.iborderDao.getMapByIds(ids, attrs);

    for (var row of rows) {
      row.order = map[row.order_id] || {}
    }
  }

  async changeStatus(params, dorder, order) {
    var nextObj = params.nextObj;
    order.status = nextObj.status;
    order.ostatus = nextObj.ostatus;

    dorder.status = nextObj.dstatus;
    await order.save();
    await dorder.save();
    return system.getResultSuccess();
  }

  async status1060(params, dorder, order) {
    var current = "1060";

    if (!params.name) {
      return system.getResult(null, "请输入个体工商户名称");
    }
    if (!params.creditCode) {
      return system.getResult(null, "请输入统一社会信用代码");
    }
    if (!params.businessPlace) {
      return system.getResult(null, "请输入经营场所");
    }
    if (!params.businessScope) {
      return system.getResult(null, "请输入经营范围");
    }
    if (!params.regDate) {
      return system.getResult(null, "请输入注册日期");
    }
    if (!params.businessImg) {
      return system.getResult(null, "请上传执照照片");
    }

    var businessmen = await this.businessmenDao.findOne({
      order_id: order.id
    });
    if (!businessmen) {
      businessmen = {};
    }
    var self = this;
    var v = await this.db.transaction(async function (t) {
      var updateFields = {};

      updateFields.name = self.trim(params.name);
      updateFields.creditCode = self.trim(params.creditCode);
      updateFields.businessPlace = self.trim(params.businessPlace);
      updateFields.businessScope = self.trim(params.businessScope);
      updateFields.regDate = params.regDate;
      updateFields.businessImg = self.trim(params.businessImg);
      updateFields.order_id = self.trim(order.id);
      updateFields.merchant_id = self.trim(order.merchant_id);
      updateFields.channelOrderNo = self.trim(order.channelOrderNo);
      updateFields.legalName = self.trim(order.legalName);
      updateFields.legalMobile = self.trim(order.legalMobile);
      updateFields.legalIdcard = self.trim(order.idcard);
      updateFields.gongshangFile = self.trim(params.gongshangFile);

      if (businessmen.id) {
        updateFields.id = businessmen.id;
        await self.businessmenDao.update(updateFields, t);
      } else {
        updateFields.bstatus = "2000";
        updateFields.gstatus = "2000";
        updateFields.dstatus = "2000";
        await self.businessmenDao.create(updateFields, t);
      }

      await self.updateOrderStatusTranscation(dorder, params.nextObj, t);
      return 1;
    });
    return system.getResultSuccess(v);
  }

  async status1080(params, dorder, order) {
    var current = "1080";
    var businessmen = await this.businessmenDao.findOne({
      order_id: order.id
    });
    if (!businessmen) {
      return system.getResult(null, "个体户订单不存在");
    }
    var self = this;
    var v = await this.db.transaction(async function (t) {
      var updateFields = {};

      updateFields.id = businessmen.id;

      updateFields.gongzhang = self.trim(params.gongzhang);
      updateFields.caiwuzhang = self.trim(params.caiwuzhang);
      updateFields.businessImg = self.trim(params.businessImg);
      updateFields.fapiaozhang = self.trim(params.fapiaozhang);
      updateFields.hetongzhang = self.trim(params.hetongzhang);
      updateFields.farenzhang = self.trim(params.farenzhang);
      updateFields.kezhangFile = self.trim(params.kezhangFile);

      await self.businessmenDao.update(updateFields, t);
      await self.updateOrderStatusTranscation(dorder, params.nextObj, t);

      return 1;
    });
    return system.getResultSuccess(v);
  }

  async status1100(params, dorder, order) {
    var businessmen = await this.businessmenDao.findOne({
      order_id: order.id
    });
    if (!businessmen) {
      return system.getResult(null, "个体户订单那不存在");
    }

    var self = this;
    var v = await this.db.transaction(async function (t) {
      var updateFields = {};
      updateFields.id = businessmen.id;
      updateFields.isBank = params.isBank ? true : fasle;
      updateFields.bankName = self.trim(params.bankName);
      updateFields.bankNo = self.trim(params.bankNo);
      updateFields.bank = self.trim(params.bank);
      updateFields.bankImg = self.trim(params.bankImg);

      updateFields.kaihuFile = self.trim(params.kaihuFile);

      await self.businessmenDao.update(updateFields, t);
      await self.updateOrderStatusTranscation(dorder, params.nextObj, t);
      return 1;
    });
    return system.getResultSuccess(v);
  }

  async status1120(params, dorder, order) {
    var businessmen = await this.businessmenDao.findOne({
      order_id: order.id
    });
    if (!businessmen) {
      return system.getResult(null, "个体户订单那不存在");
    }

    var self = this;
    var v = await this.db.transaction(async function (t) {
      var updateFields = {};

      updateFields.id = businessmen.id;

      updateFields.caImg = params.caImg;
      updateFields.taxRegDay = params.taxRegDay;
      updateFields.taxOrg = params.taxOrg;
      updateFields.shuiwuFile = self.trim(params.shuiwuFile);

      await self.businessmenDao.update(updateFields, t);
      await self.updateOrderStatusTranscation(dorder, params.nextObj, t);
      return 1;
    });
    //推送    
    return system.getResultSuccess(v);
  }

  // 提交审核
  async status1130(params, dorder, order) {
    var self = this;
    var v = await this.db.transaction(async function (t) {
      await self.updateOrderStatusTranscation(dorder, params.nextObj, t);
      return 1;
    });
    return system.getResultSuccess(v);
  }

  async status1160(params, dorder, order) {
    var businessmen = await this.businessmenDao.findOne({
      order_id: order.id
    });
    if (!businessmen) {
      return system.getResult(null, "个体户订单不存在");
    }
    var nextObj = params.nextObj;
    var self = this;
    var v = await this.db.transaction(async function (t) {
      var updateFields = {};

      updateFields.id = businessmen.id;
      updateFields.dstatus = "2020";

      updateFields.courierNo = params.courierNo;
      updateFields.courierImg = params.courierImg;

      await self.businessmenDao.update(updateFields, t);
      await self.iborderDao.update({
        id: dorder.order_id,
        status: "1160",
      }, t);
      await self.dao.update({
        id: dorder.id,
        status: "1160"
      });
      return 1;
    });
    return system.getResultSuccess(v);
  }

  async audit(params) {
    if (params.status != "1140" && params.status != "1150") {
      return system.getResult(null, "订单审核状态填写错误");
    }

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

    await this.dao.setRowCodeName(dorder, "status");
    if (dorder.status != "1130") {
      return system.getResult(null, "订单状态【" + dorder.statusName + "】，不允许审核");
    }

    var self = this;
    await this.db.transaction(async function (t) {
      var updateFields = {};

      updateFields.id = params.id;
      updateFields.status = params.status;

      updateFields.auditRemark = self.trim(params.auditRemark);
      updateFields.content = self.trim(params.content);
      updateFields.addressee = self.trim(params.addressee);
      updateFields.mobile = self.trim(params.mobile);
      updateFields.addr = self.trim(params.addr);
      updateFields.auditUser = self.trim(params.auditUser);
      updateFields.auditResult = params.status == "1140" ? "审核失败" : "审核成功";

      await self.dao.update(updateFields, t);
      await self.iborderDao.update({
        id: dorder.order_id,
        status: params.status
      }, t);
    });
    return system.getResultSuccess();
  }



  async updateOrderStatusTranscation(dorder, statusObj, t) {
    if (!statusObj) {
      return;
    }
    var orderFields = {
      id: dorder.order_id
    };
    if (statusObj.status) {
      orderFields.status = statusObj.status;
    }
    if (statusObj.ostatus) {
      orderFields.ostatus = statusObj.ostatus;
    }

    await this.iborderDao.update(orderFields, t);

    var dorderFileds = {
      id: dorder.id
    };
    if (statusObj.dstatus) {
      dorderFileds.status = statusObj.dstatus;
      await this.dao.update(dorderFileds, t);
    }
  }

  async updateBusiness(status, businessmen, border, t) {
    await this.businessmenDao.update(businessmen, t);
    await this.iborderDao.update({
      status: status,
      id: border.order_id
    }, t);
    await this.dao.update({
      status: status,
      id: border.id
    }, t);
  }

  async edit(params) {
    var orderParams = params.order;
    var bmParams = params.businessmen;

    var orderEdit = {};
    var bmEdit = {};

    orderEdit.id = orderParams.id;
    orderEdit.legalName = this.trim(orderParams.legalName);
    orderEdit.idcard = this.trim(orderParams.idcard);
    orderEdit.legalMobile = this.trim(orderParams.legalMobile);
    orderEdit.bankNo = this.trim(orderParams.bankNo);
    orderEdit.capital = this.trim(orderParams.capital);
    orderEdit.names = this.trim(orderParams.names);
    orderEdit.businessType = this.trim(orderParams.businessType);
    orderEdit.businessScope = this.trim(orderParams.businessScope);
    orderEdit.idcardFront = this.trim(orderParams.idcardFront);
    orderEdit.idcardBack = this.trim(orderParams.idcardBack);


    bmEdit.id = this.trim(bmParams.id);
    // 执照信息
    bmEdit.name = this.trim(bmParams.name);
    bmEdit.creditCode = this.trim(bmParams.creditCode);
    bmEdit.businessPlace = this.trim(bmParams.businessPlace);
    bmEdit.legalName = this.trim(bmParams.legalName);
    bmEdit.legalMobile = this.trim(bmParams.legalMobile);
    bmEdit.legalIdcard = this.trim(bmParams.legalIdcard);
    bmEdit.regDate = this.trim(bmParams.regDate);
    bmEdit.businessScope = this.trim(bmParams.businessScope);
    bmEdit.businessImg = this.trim(bmParams.businessImg);

    // 刻章
    bmEdit.gongzhang = this.trim(bmParams.gongzhang);
    bmEdit.caiwuzhang = this.trim(bmParams.caiwuzhang);
    bmEdit.fapiaozhang = this.trim(bmParams.fapiaozhang);
    bmEdit.hetongzhang = this.trim(bmParams.hetongzhang);
    bmEdit.farenzhang = this.trim(bmParams.farenzhang);

    // 开户信息
    bmEdit.isBank = bmParams.isBank ? true : false;
    bmEdit.bankName = this.trim(bmParams.bankName);
    bmEdit.bankNo = this.trim(bmParams.bankNo);
    bmEdit.bank = this.trim(bmParams.bank);
    bmEdit.bankImg = this.trim(bmParams.bankImg);

    // 税务报道
    bmEdit.caImg = this.trim(bmParams.caImg);
    bmEdit.taxRegDay = this.trim(bmParams.taxRegDay);
    bmEdit.taxOrg = this.trim(bmParams.taxOrg);

    // 邮寄信息
    bmEdit.courierNo = this.trim(bmParams.courierNo);
    bmEdit.courierImg = this.trim(bmParams.courierImg);

    var self = this;
    await this.db.transaction(async function (t) {
      await self.iborderDao.update(orderEdit, t);
      await self.businessmenDao.update(bmEdit, t);
      return 1;
    });
    return system.getResultSuccess();
  }

  async close(params) {
    var od = await this.findById(params.id);
    var order = await this.iborderDao.findById(od.order_id);
    if (!od) {
      return system.getResult(null, od);
    }
    if (od.status == "1040") {
      return system.getResultSuccess();
    }
    await this.dao.setRowCodeName(od, "status");
    if (od.status != "1030") {
      return system.getResult(null, "订单处于【" + od.statusName + "】状态, 不允许关闭");
    }

    od.status = "1040";
    od.breakReason = this.trim(params.breakReason);
    await od.save();

    order.orderDeliverId = "";
    order.status = "1020";
    await order.save();

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