// pages/reserve/index.js
import moment, { parseTwoDigitYear } from '../../utils/moment.min';
moment.locale('en', {
  longDateFormat: {
    l: 'YYYY-MM-DD',
    L: 'YYYY-MM-DD HH:mm:ss',
  },
});
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    height: app.globalData.height * 2 + 25,
    windowHeight: app.globalData.windowHeight,
    navbarData: {
      name: '报餐',
    },
    tenant: '',
    logo: '',
    today: '',
    // 点餐
    currentTab: 0,
    // 早餐，午餐，晚餐
    infoTab: '0',
    // 餐列表
    breakfastList: [],
    lunchList: [],
    dinnerList: [],
    // 餐数量
    oneStepper: 0,
    twoStepper: 0,
    thrStepper: 0,
    // 选餐表单
    form: {
      breakfast: { reserve: 0, list: [] },
      lunch: { reserve: 0, list: [] },
      dinner: { reserve: 0, list: [] },
    },
    // 时间选择范围
    picker: {},
  },
  // 选择日期
  bindDateChange: async function (e) {
    this.setData({ today: e.detail.value });
    await this.searchDate();
    await this.searchOrder();
  },
  // 禁止左右滑动
  stopTab: function (e) {
    return false;
  },
  //点击切换
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      });
    }
  },
  // 点击选择餐食
  infoClickTab: function (e) {
    var that = this;
    let data = e.target.dataset.current;
    if (this.data.infoTab === data) return false;
    else that.setData({ infoTab: data });
  },
  // 选择餐数量
  // 早餐,午餐，晚餐
  oneChange: function (e) {
    const { data, type } = e.target.dataset;
    const { detail } = e;
    this.menuNumOpera(type, detail, data._id);
  },
  // 增加
  onePlus: function (e) {
    let data = e.target.dataset.data;
    let type = this.data.infoTab;
    let initMealData = { list: [], reserve: 0 };
    let meal;
    let mw;
    switch (type) {
      case '0':
        mw = 'breakfast';
        meal = this.data.form.breakfast;
        break;
      case '1':
        mw = 'lunch';
        meal = this.data.form.lunch;
        break;
      case '2':
        mw = 'dinner';
        meal = this.data.form.dinner;
        break;

      default:
        break;
    }
    if (!meal) meal = initMealData;
    // 计算卡路里
    meal.reserve = meal.reserve + data.reserve;
    // 查询下标
    let res = meal.list.findIndex((i) => i._id === data._id);
    // 查询数据
    let arr = meal.list.find((i) => i._id === data._id);
    let onum = 0;
    if (arr) {
      //已有值
      onum = arr.num + 1;
      let qwe = { ...arr, num: onum }; //id: arr.id, title: arr.title
      meal.list.splice(res, 1, qwe);
    } else {
      //没有值
      let onum = 1;
      let arr = { ...data, num: onum }; //id: data.id, title: data.title
      meal.list.push(arr);
    }
    const key = `form.${mw}`;
    this.setData({ [key]: meal });
    this.computedTotalReserve();
  },
  /**
   * 更新菜单的数量
   * @param {String} type 三餐的类型
   * @param {Number} num 当前的数量
   * @param {String} id 指定菜品
   */
  menuNumOpera(type, num, id) {
    let list = this.data[`${type}List`];
    const li = list.findIndex((f) => f._id === id);
    const ld = list.find((f) => f._id === id);
    if (ld) {
      ld.num = num;
      list.splice(li, 1, ld);
      this.setData({
        [`${type}List`]: list,
      });
    }
  },

  // 减少
  oneMinus: function (e) {
    let data = e.target.dataset.data;
    let type = this.data.infoTab;
    let initMealData = { list: [], reserve: 0 };
    let meal;
    let mw;
    switch (type) {
      case '0':
        mw = 'breakfast';
        meal = this.data.form.breakfast;
        break;
      case '1':
        mw = 'lunch';
        meal = this.data.form.lunch;
        break;
      case '2':
        mw = 'dinner';
        meal = this.data.form.dinner;
        break;

      default:
        break;
    }
    if (!meal) meal = initMealData;
    // 计算卡路里
    meal.reserve = meal.reserve - data.reserve;
    // 查询下标
    let res = meal.list.findIndex((i) => i._id === data._id);
    // 查询数据
    let arr = meal.list.find((i) => i._id === data._id);
    if (arr) {
      if (arr.num - 1 <= 0) meal.list.splice(res, 1);
      else {
        let qwe = { ...arr, num: arr.num - 1 };
        meal.list.splice(res, 1, qwe);
      }
    }
    const key = `form.${mw}`;
    this.setData({ [key]: meal });
    this.computedTotalReserve();
  },
  computedTotalReserve() {
    const form = this.data.form;
    const br = form.breakfast && form.breakfast.reserve ? form.breakfast.reserve : 0;
    const lr = form.lunch && form.lunch.reserve ? form.lunch.reserve : 0;
    const dr = form.dinner && form.dinner.reserve ? form.dinner.reserve : 0;
    const total = br + lr + dr;
    this.setData({ totalReserve: total });
  },
  // 提交
  onSubmit: async function () {
    const data = JSON.parse(JSON.stringify(this.data.form));
    if (app.globalData.wxInfo) data.openid = app.globalData.wxInfo.openid;
    if (this.data.today) data.date = this.data.today;
    let url;
    if (data._id) url = `/order/update/${data._id}`;
    else url = `/order`;
    const res = await app.$post(url, data);
    if (res.errcode === 0) wx.showToast({ title: '点餐成功', icon: 'success' });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.searchST();
    let today = moment().add(1, 'days').format('YYYY-MM-DD');
    let endday = moment().add(1, 'months').format('YYYY-MM-DD');
    this.setData({ today: today, picker: { start: today, end: endday } });
    await this.searchDate();
    await this.searchOrder();
  },
  // 查询时间
  searchDate: async function () {
    let today = this.data.today;
    const res = await app.$get(`/arrange/getByDate?date=${today}`);
    const { arrange } = res.data;
    if (!arrange) return;
    let { breakfast, lunch, dinner } = arrange;
    breakfast = this.dealImg(breakfast);
    lunch = this.dealImg(lunch);
    dinner = this.dealImg(dinner);
    this.setData({
      breakfastList: breakfast,
      lunchList: lunch,
      dinnerList: dinner,
    });
  },
  dealImg(list) {
    for (let i of list) {
      if (i.img && i.img.length > 0 && i.img[0]) i.url = `${i.img[0].url}`;
      else i.url = this.data.logo;
    }
    return list;
  },
  searchST: async function () {
    const res = await app.$get('/config');
    const logo = `${res.data.logo[0].url || ''}`;
    this.setData({ logo });
    // wx.request({
    //   url: `${app.globalData.publicUrl}/api/st/system/tenant/getTenant/${app.globalData.tenant}`,
    //   method: "get",
    //   data: {},
    //   success: res => {
    //     const { data } = res.data;
    //     this.setData({ tenant: data.name });
    //     this.setData({ logo: `${app.globalData.fileUrl}` + data.img.logo })
    //   },
    //   error: err => {
    //     wx.showToast({
    //       title: err.msg,
    //       icon: 'error'
    //     })
    //   }
    // })
  },
  // 查订单
  async searchOrder() {
    let today = this.data.today;
    let openid = app.globalData.wxInfo.openid;
    const res = await app.$get(`/order/getByOpenid?date=${today}&openid=${openid}`);
    const { data } = res;
    if (!data) return;
    this.setData({
      form: res.data,
    });
    const robj = res.data;
    if (robj.breakfast && robj.breakfast.list && robj.breakfast.list.length > 0) this.dealOrderToMenu('breakfast', robj.breakfast.list);
    if (robj.lunch && robj.lunch.list && robj.lunch.list.length > 0) this.dealOrderToMenu('lunch', robj.lunch.list);
    if (robj.dinner && robj.dinner.list && robj.dinner.list.length > 0) this.dealOrderToMenu('dinner', robj.dinner.list);
    this.computedTotalReserve();
  },
  /**
   * 将点过的单还原,继续修改
   * @param {String} type 三餐类型
   * @param {Array} list 某餐的内容
   */
  dealOrderToMenu(type, list) {
    if (list.length <= 0) return;
    const menu = this.data[`${type}List`];
    if (!menu) {
      console.error('没找到菜单');
      return;
    }
    for (const o of list) {
      const { num, _id } = o;
      this.menuNumOpera(type, num, _id);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
