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

class SaasOrderService extends ServiceBase {
  constructor() {
    super("saas", ServiceBase.getDaoName(SaasOrderService));

    this.saasorderbminfoDao = system.getObject("db.saas.saasorderbminfoDao");
    this.saasorderpayDao = system.getObject("db.saas.saasorderpayDao");
    this.saasorderdeliverinfoDao = system.getObject("db.saas.saasorderdeliverinfoDao");
    this.saasorderbusinessmenDao = system.getObject("db.saas.saasorderbusinessmenDao");
    this.redisClient = system.getObject("util.redisClient");
  }

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

  async info(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

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

    order.bminfo = await this.saasorderbminfoDao.getById(params.id);
    this.handleDate(order, ["created_at"], null, -8);
    await this.setOrderStatus([order]);
    return system.getResultSuccess(order);
  }

  // 平台订单信息查询
  async platformOrderInfo(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

    let order = await this.dao.getById(params.id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    this.handleDate(order, ["created_at"], null, -8);
    await this.setOrderStatus([order]);
    let bminfo = await this.saasorderbminfoDao.getById(params.id) || {};
    let deliverInfo = await this.saasorderdeliverinfoDao.getById(params.id) || {};

    let payList = await this.saasorderpayDao.findByOrderId(params.id) || [];
    let payInfo = payList.length > 0 ? payList[0] : {};
    this.handleDate(payInfo, ["created_at"], null, -8);

    let result = {
      baseInfo: {
        id: order.id,
        created_at: order.created_at,
        status_name: order.status_name,
        price: system.f2y(order.price),
      },
      regInfo: {
        legal_name: bminfo.legal_name,
        legal_idno: bminfo.legal_idno,
        legal_mobile: bminfo.legal_mobile,
        company_names: bminfo.company_names,
        idcard_front: bminfo.idcard_front,
        idcard_back: bminfo.idcard_back,
      },
      merchantDeliverInfo: {
        merchant_deliver_man: deliverInfo.merchant_deliver_man,
        merchant_deliver_mobile: deliverInfo.merchant_deliver_mobile,
        merchant_deliver_addr: deliverInfo.merchant_deliver_addr,
      },
      payInfo: {
        amount: system.f2y(payInfo.amount),
        created_at: payInfo.created_at,
        trade_no: (payInfo.trade_no || payInfo.id),
        pay_voucher_img: payInfo.pay_voucher_img,
      },
      auditInfo: {
        domicile_name: bminfo.domicile_name,
        business_type: bminfo.business_type,
        business_scope: bminfo.business_scope,
        deliver_man: deliverInfo.deliver_man,
        deliver_mobile: deliverInfo.deliver_mobile,
        deliver_addr: deliverInfo.deliver_addr,
      },
      deliverInfo: {
        deliver_express_no: deliverInfo.deliver_express_no,
        deliver_express_img: deliverInfo.deliver_express_img,
      },
      sveDeliverInfo: {
        sve_deliver_express_no: deliverInfo.sve_deliver_express_no,
        sve_deliver_express_img: deliverInfo.sve_deliver_express_img,
      }
    }
    return system.getResultSuccess(result);
  }

  // 平台订单信息查询
  async merchantOrderInfo(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

    let order = await this.dao.getById(params.id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    this.handleDate(order, ["created_at"], null, -8);
    await this.setOrderStatus([order]);
    let bminfo = await this.saasorderbminfoDao.getById(params.id) || {};
    let deliverInfo = await this.saasorderdeliverinfoDao.getById(params.id) || {};

    let payList = await this.saasorderpayDao.findByOrderId(params.id) || [];
    let payInfo = payList.length > 0 ? payList[0] : {};
    this.handleDate(payInfo, ["created_at"], null, -8);

    let result = {
      baseInfo: {
        id: order.id,
        created_at: order.created_at,
        status_name: order.status_name,
        price: system.f2y(order.price),
      },
      regInfo: {
        legal_name: bminfo.legal_name,
        legal_idno: bminfo.legal_idno,
        legal_mobile: bminfo.legal_mobile,
        company_names: bminfo.company_names,
        idcard_front: bminfo.idcard_front,
        idcard_back: bminfo.idcard_back,
      },
      merchantDeliverInfo: {
        merchant_deliver_man: deliverInfo.merchant_deliver_man,
        merchant_deliver_mobile: deliverInfo.merchant_deliver_mobile,
        merchant_deliver_addr: deliverInfo.merchant_deliver_addr,
      },
      payInfo: {
        amount: system.f2y(payInfo.amount),
        created_at: payInfo.created_at,
        trade_no: (payInfo.trade_no || payInfo.id),
        pay_voucher_img: payInfo.pay_voucher_img,
      },
      deliverInfo: {
        deliver_express_no: deliverInfo.deliver_express_no,
        deliver_express_img: deliverInfo.deliver_express_img,
      },
    }
    return system.getResultSuccess(result);
  }

  async microAdd(params) {
    let saas_id = this.trim(params.saas_id);
    let merchant_id = this.trim(params.merchant_id);
    let product_id = this.trim(params.product_id);
    let merchant_app_user_id = this.trim(params.merchant_app_user_id);
    let price = Number(params.price || 0);
    let bminfo = params.bminfo;

    let order = {
      saas_id: saas_id,
      merchant_id: merchant_id,
      product_id: product_id,
      merchant_app_user_id: merchant_app_user_id,
      price: price,
      pay_status: 10,
      audit_status: 10,
      handle_status: 10,
    }

    let self = this;
    order = await this.db.transaction(async t => {
      //创建orderdeliver记录
      order = await self.dao.create(order, t);

      //更新oorder订单记录
      bminfo.id = order.id;
      bminfo.merchant_id = merchant_id;
      await self.saasorderbminfoDao.create(bminfo, t);
      await self.saasorderdeliverinfoDao.create({
        id: order.id
      }, t);
      return order;
    });
    return system.getResultSuccess(order);
  }

  async updateOrder(params) {
    if (!params.id) {
      return system.getResult("订单id不存在");
    }
    await this.dao.update(params);
    return system.getResultSuccess();
  }

  async sveDeliver(params) {
    if (!params.id) {
      return system.getResult("订单id不存在");
    }
    let self = this;
    await this.db.transaction(async t => {
      //创建orderdeliver记录
      await self.dao.update({
        id: params.id,
        handle_status: 20
      }, t);
      await self.saasorderdeliverinfoDao.update({
        id: params.id,
        sve_deliver_express_no: params.sve_deliver_express_no,
        sve_deliver_express_img: params.sve_deliver_express_img
      }, t);
      return 1;
    });
    return system.getResultSuccess();
  }

  /**
   * fn:  建账、订单完成 推送信息保存
   * @param {*} params 
   */
  async saveSaasOrderBusinessmen(params) {
    try {
      let order = await this.dao.findById(params.source_no);
      if(!order) {
        console.log(`${params.source_no}订单不存在`);
        return system.getResult(null, `订单不存在`);
      }
      let saasorderbusinessmen = await this.saasorderbusinessmenDao.findById(this.trim(order.id));
      if(saasorderbusinessmen) {
        saasorderbusinessmen.saas_id = order.saas_id;
        this.setBusinessmenProperty(saasorderbusinessmen, params);
        await saasorderbusinessmen.save();
      } else {
        saasorderbusinessmen = {id: order.id};
        this.setBusinessmenProperty(saasorderbusinessmen, params);
        saasorderbusinessmen.saas_id = order.saas_id;
        saasorderbusinessmen.merchant_id = order.merchant_id;
        saasorderbusinessmen.product_id = order.product_id;
        saasorderbusinessmen.saas_order_id = order.saas_order_id;
        await this.saasorderbusinessmenDao.create(saasorderbusinessmen);
      }
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

  setBusinessmenProperty(saasorderbusinessmen, params) {
    for(let key in params) {
      if(key == "id" || key == "created_at" || key == "updated_at" || key == "deleted_at"|| key == "version") {
        continue;
      }
      saasorderbusinessmen[key] = params[key];
    }
    return saasorderbusinessmen;
  }

  async pageByCondition(params) {
    let page = {
      count: 0,
      rows: []
    }
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);

    params.startRow = (params.currentPage - 1) * params.pageSize;

    await this.parseStatus(params);
    page.total = await this.dao.countByCondition(params);
    if (page.total == 0) {
      return system.getResultSuccess(page);
    }
    page.count = page.total;

    page.rows = await this.dao.listByCondition(params);
    if (page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"], null, -8);
      }

      await this.setBminfo(page.rows);
      await this.setOrderStatus(page.rows);
    }
    return system.getResultSuccess(page);
  }

  async parseStatus(params) {
    if (!params || !params.status || params.status.length != 4) {
      return;
    }
    let type = params.status.slice(0, 2);
    let status = params.status.slice(2);

    if (type == "10") {
      params.pay_status = status;
    } else if (type == "20") {
      params.audit_status = status;
    } else if (type == "30") {
      params.handle_status = status;
    } else {}
  }

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

    // 订单状态总结   1010 待付款, 2010 待审核, 2030 审核驳回, 3010 业务办理中, 3020待交付, 3030 已交付
    for (let row of rows) {
      let status = "";
      // 支付状态 10待支付 20已支付
      if (row.pay_status === "10") {
        row.status = "1010";
        row.status_name = "待付款";
        continue;
      }

      // 10待审核 20审核通过 30审核驳回
      if (row.audit_status != "20") {
        row.status = row.audit_status == "10" ? "2010" : "2030";
        row.status_name = row.audit_status == "10" ? "待审核" : "审核驳回";
        continue;
      }

      // 审核状态
      if (row.handle_status == "10") {
        row.status = "3010";
        row.status_name = "业务办理中";
      } else if (row.handle_status == "20") {
        row.status = "3020";
        row.status_name = "待交付";
      } else if (row.handle_status == "30") {
        row.status = "3030";
        row.status_name = "已交付";
      }
    }

  }

  async mapByIds(params) {
    if (!params.ids || params.ids.length == 0) {
      return system.getResultSuccess({});
    }
    let rs = await this.dao.mapByIds(params.ids, params.attrs);
    return system.getResultSuccess(rs);
  }

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

    let ids = [];
    for (let row of rows) {
      ids.push(row.id);
    }

    let map = await this.saasorderbminfoDao.mapByIds(ids) || {};
    for (let row of rows) {
      row.bminfo = map[row.id] || {};
    }
  }

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

    let ids = [];
    for (let row of rows) {
      ids.push(row.id);
    }

    let map = await this.saasorderdeliverinfoDao.mapByIds(ids) || {};
    for (let row of rows) {
      row.deliverInfo = map[row.id] || {};
    }
  }

  async bulkAudit(params) {
    let ids = params.ids || [];
    for (let id of ids) {
      try {
        params.id = id;
        await this.audit(params);
        console.log(id);
      } catch (e) {
        console.log(e);
      }
    }
    return system.getResultSuccess();
  }

  async audit(params) {
    let id = this.trim(params.id);
    let audit_status = this.trim(params.audit_status);

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

    let order = await this.dao.findById(id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    if (order.pay_status != "20") {
      return system.getResult(null, "订单未支付");
    }
    if (order.audit_status != "10") {
      return system.getResult(null, "订单已审核");
    }

    let _order = {
      id: id
    };
    _order.audit_status = audit_status;
    _order.handle_status = "10";
    _order.audit_remark = this.trim(params.audit_remark);

    let _deliverInfo;
    let _bminfo;
    if (audit_status == "20") {

      _deliverInfo = {
        id: id
      };
      _deliverInfo.deliver_man = this.trim(params.deliver_man);
      _deliverInfo.deliver_mobile = this.trim(params.deliver_mobile);
      _deliverInfo.deliver_addr = this.trim(params.deliver_addr);

      _bminfo = {
        id: id
      };
      _bminfo.domicile_id = this.trim(params.domicile_id);
      _bminfo.domicile_name = this.trim(params.domicile_name);
      _bminfo.business_scope_id = this.trim(params.business_scope_id);
      _bminfo.business_type = this.trim(params.business_type);
      _bminfo.business_scope = this.trim(params.business_scope);
    }
    let self = this;
    this.db.transaction(async t => {
      await self.dao.update(_order, t);
      if (_bminfo) {
        await self.saasorderbminfoDao.update(_bminfo, t);
      }
      if (_deliverInfo) {
        await self.saasorderdeliverinfoDao.update(_deliverInfo, t);
      }
      return 1;
    });
    return system.getResultSuccess();
  }

  async bulkDeliver(params) {
    let ids = params.ids || [];
    for (let id of ids) {
      try {
        params.id = id;
        await this.deliver(params);
        console.log(id);
      } catch (e) {
        console.log(e);
      }
    }
    return system.getResultSuccess();
  }

  async deliver(params) {
    let id = this.trim(params.id);
    let deliver_express_no = this.trim(params.deliver_express_no);
    let deliver_express_img = this.trim(params.deliver_express_img);
    if (!deliver_express_no) {
      return system.getResult(null, "请填写快递单号");
    }
    if (!deliver_express_img) {
      return system.getResult(null, "请上传交接单");
    }

    let order = await this.dao.findById(id);
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    if (order.handle_status != "20") {
      return system.getResult(null, "该订单不允许交付");
    }

    let _order = {
      id: id
    };
    _order.handle_status = "30";

    let _deliverInfo = {
      id: id
    };
    _deliverInfo.deliver_express_no = deliver_express_no;
    _deliverInfo.deliver_express_img = deliver_express_img;
    let self = this;
    this.db.transaction(async t => {
      await self.dao.update(_order, t);
      await self.saasorderdeliverinfoDao.update(_deliverInfo, t);
      return 1;
    });
    return system.getResultSuccess();
  }

  async bulkOfflinePay(params) {
    let ids = params.ids || [];
    for (let id of ids) {
      try {
        params.id = id;
        await this.offlinePay(params);
        console.log(id);
      } catch (e) {
        console.log(e);
      }
    }
    return system.getResultSuccess();
  }

  async offlinePay(params) {
    let id = this.trim(params.id);
    let order = await this.dao.findById(id);
    if (order.pay_status != "10") {
      return;
    }

    let _order = {
      id: id
    };
    _order.pay_status = "20";
    _order.audit_status = "10";

    let _deliverInfo = {
      id: id
    };
    _deliverInfo.merchant_deliver_man = this.trim(params.merchant_deliver_man);
    _deliverInfo.merchant_deliver_mobile = this.trim(params.merchant_deliver_mobile);
    _deliverInfo.merchant_deliver_addr = this.trim(params.merchant_deliver_addr);

    let _pay = {
      order_id: id,
      pay_type: 1,
      amount: order.price,
      pay_status: "20",
      pay_voucher_img: this.trim(params.pay_voucher_img),
    };
    _pay.trade_no = await this.redisClient.genrateId("saas_order_trade_no");

    let self = this;
    this.db.transaction(async t => {
      await self.dao.update(_order, t);
      await self.saasorderdeliverinfoDao.update(_deliverInfo, t);
      await self.saasorderpayDao.create(_pay, t);
      return 1;
    });
  }

  async mapByCreditCodes(params) {
    let rs = await this.saasorderbusinessmenDao.mapByCreditCodes(params) || {};
    return system.getResultSuccess(rs);
  }

  async businessmenPage(params) {
    let page = {
      count: 0,
      rows: []
    }
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);

    params.startRow = (params.currentPage - 1) * params.pageSize;

    // 只查询已经建账的个体户
    params.isBusinessmenCreated = true;

    page.count = await this.saasorderdeliverinfoDao.countByCondition(params);
    if (page.count == 0) {
      return system.getResultSuccess(page);
    }
    params.attrs = ["id", "sve_businessmen_company_id", "sve_businessmen_customer_id", "sve_businessmen_name", "sve_businessmen_credit_code"];
    page.rows = await this.saasorderdeliverinfoDao.listByCondition(params);
    if (page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"], null, -8);
      }
    }
    return system.getResultSuccess(page);
  }

  async byIds(params) {
    let list = await this.dao.byIds(params);
    return system.getResultSuccess(list);
  }
  async updateInvoice(params) {
    let rs = await this.dao.updateInvoice(params);
    return system.getResult(rs);
  }
}

module.exports = SaasOrderService;