// 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: [], },
    },
  },
  // 选择日期
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({ today: e.detail.value })
    this.searchDate();
    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) {
    console.log(e);
    const { data, type } = e.target.dataset
    const { detail } = e;
    this.menuNumOpera(type, detail, data._id)
  },
  // 增加
  onePlus: function (e) {
    console.log('增加');
    let data = e.target.dataset.data;
    let type = this.data.infoTab;
    let meal;
    let mw;
    if (type == 0) {//早餐
      mw = 'breakfast';
      meal = this.data.form.breakfast;
      // 计算卡路里
      let reserve = meal.reserve + data.reserve;
      this.setData({ 'form.breakfast.reserve': reserve })
    } else if (type == 1) {//午餐
      mw = 'lunch';
      meal = this.data.form.lunch;
      // 计算卡路里
      let reserve = meal.reserve + data.reserve;
      this.setData({ 'form.lunch.reserve': reserve })
    } else if (type == 2) {//晚餐
      mw = 'dinner';
      meal = this.data.form.dinner;
      // 计算卡路里
      let reserve = meal.reserve + data.reserve;
      this.setData({ 'form.dinner.reserve': 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 {//没有值
      console.log(data)
      let onum = 1;
      let arr = { ...data, num: onum } //id: data.id, title: data.title
      meal.list.push(arr)
    }
  },
  /**
   * 更新菜单的数量
   * @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) {
    console.log('减少');
    let data = e.target.dataset.data;
    let type = this.data.infoTab;
    let meal;
    let mw;
    if (type == 0) {//早餐
      mw = 'breakfast';
      meal = this.data.form.breakfast;
      // 计算减少卡路里
      let reserve = meal.reserve - data.reserve;
      this.setData({ 'form.breakfast.reserve': reserve })
    } else if (type == 1) {//午餐
      mw = 'lunch';
      meal = this.data.form.lunch;
      // 计算减少卡路里
      let reserve = meal.reserve - data.reserve;
      this.setData({ 'form.lunch.reserve': reserve })
    } else if (type == 2) {//晚餐
      mw = 'dinner';
      meal = this.data.form.dinner;
      // 计算减少卡路里
      let reserve = meal.reserve - data.reserve;
      this.setData({ 'form.dinner.reserve': 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)
      }

    }
    // this.menuNumOpera(mw, onum, data._id)
  },
  // 提交
  onSubmit: 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 = `${app.globalData.publicUrl}/api/st/dining/order/update/${data._id}`
    else url = `${app.globalData.publicUrl}/api/st/dining/order`;
    wx.request({
      url,
      method: "post",
      header: {
        'x-tenant': app.globalData.tenant
      },
      data,
      success: res => {
        if (res.data.errcode == 0) {
          wx.showToast({
            title: '完成点餐',
          })
        }

      },
      error: err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.searchST();
    let today = moment().format('YYYY-MM-DD');
    this.setData({ today: today })
    this.searchDate();
    this.searchOrder();
  },
  // 查询时间
  searchDate: function () {
    let today = this.data.today;
    wx.request({
      url: `${app.globalData.publicUrl}/api/st/dining/arrange/getByDate?date=` + today,
      method: "get",
      header: {
        'x-tenant': app.globalData.tenant
      },
      success: res => {
        const { arrange } = res.data.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
        })
      },
      error: err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      }
    })
  },
  dealImg(list) {
    for (let i of list) {
      if (i.img && i.img.length > 0 && i.img[0]) i.url = `${app.globalData.fileUrl}${i.img[0].url}`;
      else i.url = this.data.logo;
    }
    return list;
  },
  searchST: function () {
    wx.request({
      url: `${app.globalData.publicUrl}/api/st/system/tenant/getTenant/${app.globalData.tenant}`,
      method: "get",
      header: { 'x-tenant': app.globalData.tenant },
      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'
        })
      }
    })
  },
  // 查订单
  searchOrder() {
    let today = this.data.today;
    let openid = app.globalData.wxInfo.openid;
    wx.request({
      url: `${app.globalData.publicUrl}/api/st/dining/order/getByOpenid?date=${today}&openid=${openid}`,
      method: "get",
      header: {
        'x-tenant': app.globalData.tenant
      },
      success: res => {
        this.setData({
          form: res.data.data,
        })
        const { breakfast, lunch, dinner } = res.data.data
        this.dealOrderToMenu('breakfast', breakfast.list)
        this.dealOrderToMenu('lunch', lunch.list)
        this.dealOrderToMenu('dinner', dinner.list)
      },
      error: err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      }
    })
  },
  /**
   * 将点过的单还原,继续修改
   * @param {String} type 三餐类型
   * @param {Array} list 某餐的内容
   */
  dealOrderToMenu(type, list) {
    console.log(type, list)
    if (list.length <= 0) return;
    const menu = this.data[`${type}List`]
    if (!menu) 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 () {

  }
})