/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-18 11:03:36
 * @LastEditors: lvdexin
 * @LastEditTime: 2022-10-20 17:19:02
 */
const { Tips } = getApp();
const baseUrl = require("../../../api/index.js").config;
const order = require("../../../api/order.js");

// 请求成功,不使用箭头函数的原因是需要改变this的指向
function submiSuccess(res, resolve, reject) {
  const { code, results, message, mobile } = res || {};

  if (code !== 200) {
    console.log("sbumit error:", message);
    Tips(message || "您的网络开了个小差，请重新进入小程序后重试");
    this.setData({
      payflag: false,
    });
    reject();
    // 这里之所有还要return 是因为这个函数不是Promise函数
    return;
  }

  const { orderId } = results;
  this.setData(
    {
      orderid: orderId,
    },
    () => {
      wx.setStorageSync("couponindex", "fo");
      wx.setStorageSync("foodflag", "");
      wx.setStorageSync("orderflag", "");
      wx.setStorageSync("phonenumber", mobile);
      // 积分？
      wx.setStorageSync("trueindex", "fail");
      wx.setStorageSync("mentionlist", "");
      wx.setStorageSync("selectCouponlist", []);
      resolve();
    }
  );
}

// 请求失败，不使用箭头函数的原因是需要改变this的指向
function submiFail(rej, resolve, reject) {
  this.setData({
    payflag:false
  })
}

// 处理不允许提交的情况
const handlerIntercept = (self) => {
  const { currentflag, address, tableflag, tableselct } = self.data;
  let flag = true;
  // 外卖情况下是否有收货地址
  if (currentflag === 1 && !address) {
    Tips("请添加收货地址");
    flag = false;
  }

  // 判断是否选择餐具
  if (!tableflag) {
    tableselct[0].num = "无需餐具";
    self.setData({
      showcover: true,
      payflag: false,
      tableselct,
    });
    flag = false;
  }
  return flag;
};

// 处理菜品
const handlerFoods = (self) => {
  const { orderfood } = self.data;
  // 获取当前的菜品
  const foods = self.computedActivityGroup()
    ? wx.getStorageSync("groupFood")
    : orderfood;

  // 构建发送的菜品数据
  return foods.map((ele) => {
    const { num, id, storeFoodId, foodType, attributes } = ele;
    return Object.assign(
      {},
      {
        num,
        skuId: id,
        storeFoodId,
        foodType,
      },
      attributes
        ? {
            attributes,
          }
        : {}
    );
  });
};

// 构建发送的数据
const creatPostData = (self) =>
  new Promise((resolve) => {
    // 订单类型 1：外卖 2: 自提
    const {
      currentflag,
      address,
      appointexpect,
      scheduleflag,
      remarker,
      shareCode,
      coverindex,
      extraInfo = {},
      canUseCoupons = [],
      orderlist,
      // TODO 后端给出接口后这个字段需要相对应地进行替换变量名
      needHelp,
    } = self.data;

    let { tableselct } = self.data;

    const { name, phone } = orderlist;

    // 处理菜品
    const foodForms = handlerFoods(self);

    // 处理收货地址
    const addressId = address ? address.id : null;

    // 获取活动相关的信息
    const groupFlag = self.computedActivityGroup();
    let groupId = null;
    if (groupFlag) {
      const { focusGroupId } = extraInfo;
      groupId = focusGroupId;
    }

    // 获取优惠券信息
    // const couponindex = wx.getStorageSync("couponindex");
    const couponList = wx.getStorageSync("selectCouponlist");
    const couponObj = {};
    couponList.forEach((i) => {
      const { couponType, id } = i;
      if (couponType === 1) {
        couponObj.commonCouponId = id;
      } else {
        couponObj.platformCouponId = id;
      }
    });

    // 优惠券id
    // const commonCouponId = canUseCoupons[couponindex]
    //   ? canUseCoupons[couponindex].id
    //   : null;

    // 分佣引流相关
    const sourceObj = {};
    const enterType = wx.getStorageSync("enterType");
    const sourceMerchantId = wx.getStorageSync("sourceMerchantId");
    enterType && (sourceObj.enterType = enterType);
    sourceMerchantId && (sourceObj.sourceMerchantId = sourceMerchantId);

    // 判断餐具
    if (coverindex == 0) {
      tableselct[0].num = 0;
      self.setData({
        tablelist: tableselct,
      });
    }

    // 请求数据
    resolve({
      foodForms,
      name,
      phone,
      orderType: currentflag,
      addressId,
      expectedTime: appointexpect,
      // 预订单标志
      appointFlag: scheduleflag,
      // 餐具份数
      tablewareNum: tableselct[coverindex].num,
      // 备注
      remark: remarker,
      // 分享code
      shareCode: +shareCode || -1,
      // 是否需要请求护工取货
      nurseDeliveryStatus: needHelp,
      // 引流
      ...sourceObj,
      // 优惠券
      ...couponObj,
      // 分众活动
      ...extraInfo,
    });
  });

export function submitOrder() {
  return new Promise(async (resolve, reject) => {
    // 订单类型 1：外卖 2: 自提
    const { currentflag } = this.data;
    const { tableflag } = this.data
    const that = this, index = 0
    // 如果没有选择餐具，默认选中无需餐具
    if (!tableflag) {
      await new Promise(resolve => {
        for (var i = 0; i < that.data.tableselct.length; i++) {
          if (i == index) {
            that.data.tableselct[i].cover = true
          } else {
            that.data.tableselct[i].cover = false
          }
        }
        that.setData({
          huanbaoflag: true,
          tableselct: that.data.tableselct,
          coverindex: index,
          showcover: false,
          tableflag: true
        }, resolve)
      })
    }
    // 拦截情况
    const flag = handlerIntercept(this);
    if (!flag) return;

    // 提交的数据
    const submitData = await creatPostData(this);

    // 提交的函数
    const submitFn = [1, "1"].includes(currentflag)
      ? order.takeOrder
      : order.takeZitiorder;

    // 用户ID
    const memberId = wx.getStorageSync("memberId");
    // 门店ID
    const storeid = wx.getStorageSync("storeid");

    // 提交的路径
    const type = [1, "1"].includes(currentflag) ? "take-out" : "ziti";
    const submitUrl = `${baseUrl.waimaiUrl}/client/${memberId}/order/${storeid}/${type}/submit`;

    this.setData(
      {
        payflag: true,
      },
      () => {
        submitFn(
          submitUrl,
          {},
          submitData,
          "加载中...",
          (res) => submiSuccess.bind(this, res, resolve, reject)(),
          (err) => submiFail.bind(this, err, resolve, reject)()
        );
      }
    );
  });
}
