// pages/reserveProject/reserveProject.js
let date = new Date()
let times = []
var weekday = new Array(7)
weekday[0] = '周日'
weekday[1] = '周一'
weekday[2] = '周二'
weekday[3] = '周三'
weekday[4] = '周四'
weekday[5] = '周五'
weekday[6] = '周六'
for (let i = 0; i < 15; i++) {
  let stamp = date.setDate(date.getDate() + (i == 0 ? 0 : 1))
  let year = new Date(stamp).getFullYear()
  let month =
    new Date(stamp).getMonth() + 1 < 10 ?
    '0' + (new Date(stamp).getMonth() + 1) :
    new Date(stamp).getMonth() + 1
  let day =
    new Date(stamp).getDate() < 10 ?
    '0' + new Date(stamp).getDate() :
    new Date(stamp).getDate()
  let week = weekday[new Date(stamp).getDay()]
  times.push({
    date: `${year + '-' + month + '-' + day}`,
    day: `${month + '-' + day}`,
    week: week
  })
}
// let _hour = ( 10 > date.getHours() ) ? '0' + date.getHours() : date.getHours();
// let _minute = ( 10 > date.getMinutes() ) ? '0' + date.getMinutes() : date.getMinutes();

const app = getApp()
import {
  get,
  post
} from '../../utils/http'
import {
  timestampToDate
} from '../../utils/time'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    times,
    time: '', // 选中的时间（小时：分钟）
    currentTimestamp: 0, // 选中的时间戳
    currentDateIndex: 0,
    currentSwiperIndex: 0,
    currentTimeIndex: -2,
    currentDeviceIndex: -1,
    money: 0,
    projectTime: [],
    projectData: {},
    projectList: [],
    deviceList: [],
    currentChangeTime: null,
    currentChangeDevice: null,
    source: 'project', // 来源
    inFirstIn: false,
    inSecIn: false,
    ids: '',
    needTime: 0,
    showStore: false, //选择店铺开关
    storeList: [], //店铺列表
  },

  // 预约数据包，json字符，其中id为项目ID，product_id为耗材ID，如：[{id:10,product_id:11},{id:12}]
  // v2/api/order/add
  toBuyNow: function () {
    // 判断是否是预约的益田店
    // if(this.data.projectData.store_id==17){
    //   this.setData({
    //     showStore:true
    //   })
    //   wx.showToast({
    //     title: '请您切换店铺',
    //     icon:'none'
    //   })
    //   return
    // }
    let {
      projectData,
      currentDateIndex,
      projectList,
      time
    } = this.data

    let dataIds = []
    if (this.data.onType == 'one') {
      dataIds = [{
        id: this.data.keyData.id
      }]
    } else {
      for (let i = 0; i < projectList.length; i++) {
        let ins = {}
        ins.id = projectList[i].id
        if (projectList[i].selectMaterial) {
          ins.product_id = projectList[i].selectMaterial.id
        }
        dataIds.push(ins)
      }
    }


    console.log(dataIds)
    // 预约数据包，json字符，其中id为项目ID（一站式项目不需要），product_id为耗材ID或一站式ID，如：[{id:10,product_id:11},{id:12}]
    wx.showLoading({
      title: '预约中',
      mask: true
    });
    post(
      'v2/api/order/add', {
        order_data: JSON.stringify(dataIds),
        store_id: projectData.store_id,
        order_day: times[currentDateIndex].date,
        order_time: time,
        type: this.data.onType,
        share_user_id: app.globalData.shareUserId || '',
      },
      (res) => {
        console.log('xxxxxx')
        console.log(res.data)

        let currentPage = getCurrentPages(); // 获取当前页的数据，
        let previousPage = currentPage[currentPage.length - 2]; // 上一页的数据，

        previousPage.setData({ //对上一个页面data中的参数进行赋值（上一个页面的数据是在当前页面进行赋值的），就变相实现了向上一个页面传值
          selectProductCar: []
        })
        // previousPage.showCarMoney()

        wx.hideLoading();
        // 获取下发权限
        wx.requestSubscribeMessage({
          tmplIds: ['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'],
          success(res) {
            console.log(res);
            let status = ''
            if (res['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'] == 'reject') {
              status = 2
            } else {
              status = 1
            }
            get('/v2/api/activity/push', {
              type: 2,
              status,
            }, res => {})
          },
        })
        // 推荐方案 测肤 埋点
        if (app.globalData.isSkinPlan || app.globalData.isTestSkin) {
          let url = app.globalData.isTestSkin ? '/v2/api/order/skin' : 'v2/api/order/recommend'
          get(url, {
            type: 2
          }, (res) => {
            if (res.code == 200) {
              this.globalData.isSkinPlan = false
              this.globalData.isTestSkin = false
            }
          })
        }
        wx.redirectTo({
          url: `/pages/orderBySuccess/orderBySuccess?&store_id=${this.data.projectData.store_id}&&orderdata=` + JSON.stringify(res.data),
        })
      })

  },

  knowSubmit: function () {
    this.setData({
      inFirstIn: false,
      inSecIn: false
    })

    let version3 = wx.getStorageSync('version3')
    if (!version3 || version3 != 1) {
      this.setData({
        inSecIn: true
      })
      wx.setStorageSync('version3', 1)
    }

  },

  noneEnoughPeople() {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let date = new Date()
    let currentTimestamp = date.getTime() / 1000 + 60 * 2
    let _time = timestampToDate(currentTimestamp, 'H:i')

    let projectList = {}
    if (options.type == 'one') {
      projectList = JSON.parse(options.data).items
      this.setData({
        keyData: JSON.parse(options.data)
      })
    } else {
      projectList = JSON.parse(options.data)
    }

    let ids = ''
    let needTime = 0
    for (let i = 0; i < projectList.length; i++) {
      ids = ids + ',' + projectList[i].id
      needTime = needTime + projectList[i].use_time
    }

    // let source = options.source || 'project'
    // console.log(JSON.parse(options.data))
    let projectData = {}
    // if (options.projectData) { 
    //   let projectData = decodeURIComponent(options.projectData)
    //   projectData = JSON.parse(projectData)
    console.log('app.globalData.storeData')
    console.log(app.globalData.storeData)
    console.log('app.globalData.storeData')

    projectData.store_id = app.globalData.storeData.id
    projectData.storeData = app.globalData.storeData
    this.setData({
      onType: options.type,
      money: options.money,
      ids: ids.substring(1, ids.length),
      projectList: projectList,
      projectData: projectData,
      source: 'project',
      currentTimestamp: currentTimestamp,
      time: _time,
      needTime: needTime,
    })
    this.getHourDate()
    //获取店铺列表
    if (projectData.store_id == 17) {
      this.getStoreList()
    }
    // 项目预约 - 获取可选时间
    this.getTime()
    let lat1 = app.address.latitude
    let lng1 = app.address.longitude
    this.setData({
      lat1: lat1,
      lng1: lng1,
    })
  },

  getHourDate() {
    let dataTime = this.data.time.split(':')
    let needTime = this.data.needTime

    let minHour = parseInt((dataTime[1] * 1 + needTime * 1) / 60)

    let dataHour = Number(minHour) + Number(dataTime[0])

    let min = null
    if ((Number(dataTime[1]) + needTime) > 60) {
      min = (Number(dataTime[1]) + needTime) % 60
    } else if ((Number(dataTime[1]) + needTime) === 60) {
      min = 0
    } else {
      min = (Number(dataTime[1]) + needTime)
    }

    let dataHourShow = dataHour > 23 ? '(明天)' + (dataHour * 1 - 24) : dataHour

    this.setData({
      showTimes: dataHourShow + ":" + (min < 10 ? `0${min}` : min)
    })
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let version2 = wx.getStorageSync('version2')
    if (!version2 || version2 != 1) {
      this.setData({
        inFirstIn: true
      })
      wx.setStorageSync('version2', 1)
    } else {
      let version3 = wx.getStorageSync('version3')
      if (!version3 || version3 != 1) {
        this.setData({
          inSecIn: true
        })
        wx.setStorageSync('version3', 1)
      }
    }
  },

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

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

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

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

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

  /**
   * 日期选择
   */
  onChangeDate(e) {
    let {
      currentDateIndex
    } = this.data
    if (currentDateIndex != e.currentTarget.dataset.index) {
      this.setData({
          currentDateIndex: e.currentTarget.dataset.index,
          currentChangeDevice: null,
          currentChangeTime: null,
          currentTimeIndex: -2,
          currentSwiperIndex: 0,
          currentDeviceIndex: -1,
          deviceList: []
        },
        () => {
          this.getTime()
        }
      )
    }
  },

  /**
   * 时间段切换
   */
  onChangeSwiper(e) {
    this.setData({
      currentSwiperIndex: e.currentTarget.dataset.index
    })
  },

  /**
   * 时间段切换
   */
  changeSwiper(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    })
  },

  /**
   * 时间选择
   */
  onChangeTime(e) {
    console.log('eeeee')
    let {
      projectTime,
      currentSwiperIndex,
      currentChangeTime,
      currentTimeIndex
    } = this.data
    projectTime[currentSwiperIndex].list.forEach((item, index) => {
      if (item.index == e.currentTarget.dataset.index) {
        currentChangeTime = item
      }
    })
    if (currentTimeIndex != e.currentTarget.dataset.index) {
      console.log('asdasdasdasd')
      console.log(currentChangeTime)
      this.setData({
        currentTimeIndex: e.currentTarget.dataset.index,
        currentChangeTime,
        time: currentChangeTime.order_time,
        currentChangeDevice: null,
        currentDeviceIndex: -1
      })

      // this.bindTimeChange({
      //   detail: {
      //     value: currentChangeTime.order_time
      //   }
      // })
      this.getHourDate()


      // this.getProjectDevice()
    }
  },


  /**
   * 点击自定义时间
   * v2/api/product/check_time
   */
  bindTimeChange(e) {
    let that = this
    let {
      projectData,
      currentDateIndex,
      projectTime,
      currentSwiperIndex,
      time
    } = this.data
    get(
      'v2/api/product/check_time', {
        ids: this.data.ids,
        store_id: projectData.store_id,
        order_day: times[currentDateIndex].date,
        order_time: e.detail.value
      },
      (res) => {
        console.log(res)
        if (res.data.status == 1) {
          that.setData({
            time: e.detail.value,
            currentTimeIndex: -1
          })
          that.getHourDate()
        } else {

        }
      }
    )


    // let {
    //   currentDateIndex,
    //   currentChangeTime
    // } = this.data
    // currentChangeTime = {
    //   order_day: times[currentDateIndex].date,
    //   time_id: e.detail.value
    // }
    // this.setData({
    //   time: e.detail.value,
    //   currentTimeIndex: -1,
    //   currentChangeTime,
    //   currentChangeDevice: null,
    //   currentDeviceIndex: -1
    // })
    // this.getProjectDevice()
  },

  // /**
  //  * 点击自定义时间
  //  */
  // bindTimeChange(e) {
  //   let {
  //     currentDateIndex,
  //     currentChangeTime
  //   } = this.data
  //   currentChangeTime = {
  //     order_day: times[currentDateIndex].date,
  //     time_id: e.detail.value
  //   }
  //   this.setData({
  //     time: e.detail.value,
  //     currentTimeIndex: -1,
  //     currentChangeTime,
  //     currentChangeDevice: null,
  //     currentDeviceIndex: -1
  //   })
  //   this.getProjectDevice()
  // },

  /**
   * 选择设备
   */
  onChangeDevice(e) {
    let {
      deviceList
    } = this.data
    this.setData({
      currentDeviceIndex: e.currentTarget.dataset.index,
      currentChangeDevice: deviceList[e.currentTarget.dataset.index]
    })
  },

  /**
   * 获取可预约时间
   */
  getTime() {
    let {
      projectData,
      currentDateIndex,
      projectTime,
      currentSwiperIndex,
      time
    } = this.data
    get(
      'v2/api/product/order_time', {
        ids: this.data.ids,
        store_id: projectData.store_id,
        order_day: times[currentDateIndex].date,
      },
      (res) => {
        projectTime[0] = res.data.day
        projectTime[1] = res.data.night
        let sum = 0
        let defaultTimeIndex = -1
        projectTime.forEach((item, index) => {
          if (item.active == 1) {
            currentSwiperIndex = index
          }
          item.list.forEach((item, index) => {
            item.index = sum
            sum++
            // 默认选中第一个可预约时间（用于后面的默认绑定设备）
            if (item.status == 1 && defaultTimeIndex == -1) {
              defaultTimeIndex = item.index
            }
          })
        })
        this.setData({
          projectTime,
          currentSwiperIndex
        }, () => {
          // 默认选中第一个可预约时间
          // TODO 产品调整需求默认选中自定义时间
          // if (defaultTimeIndex != -1) {
          //   this.onChangeTime({
          //     currentTarget: { dataset: { index: defaultTimeIndex } }
          //   })
          // }
          this.bindTimeChange({
            detail: {
              value: time
            }
          })
        })
      }
    )
  },

  /**
   * 获取项目可预约的设备
   * /api/project/device
   */
  getProjectDevice() {
    let {
      currentTimeIndex,
      time,
      projectTime,
      currentSwiperIndex,
      projectData,
      currentDateIndex
    } = this.data
    let order_time_id
    if (currentTimeIndex != -1) {
      projectTime[currentSwiperIndex].list.forEach((item, index) => {
        if (item.index == currentTimeIndex) {
          order_time_id = item.time_id
        }
      })
    } else {
      order_time_id = time
    }
    console.log(projectData)
    console.log(order_time_id)
    return new Promise((resolve, reject) => {
      get(
        'api/project/device', {
          store_id: projectData.store_id,
          project_id: projectData.id,
          order_day: times[currentDateIndex].date,
          order_time_id: order_time_id,
          use_time: projectData.use_time
        },
        (res) => {
          this.setData({
              deviceList: res.data
            },
            () => {
              this.onChangeDevice({
                currentTarget: {
                  dataset: {
                    index: 0
                  }
                }
              })
            }
          )
          resolve()
          console.log(res)
        },
        (rej) => {
          this.setData({
            currentTimeIndex: -2,
            currentChangeTime: null
          })
          console.log(rej)
        }
      )
    })
  },

  /**
   * 提交订单
   */
  addOrder() {
    let {
      projectData,
      currentTimeIndex,
      time,
      currentDateIndex,
      currentChangeTime,
      currentChangeDevice,
      deviceList
    } = this.data

    if (currentTimeIndex == -1) {
      currentChangeTime = {
        order_day: times[currentDateIndex].date,
        time_id: time,
        order_time: time
      }
    }
    console.log(currentChangeTime)
    if (currentChangeTime == null) {
      wx.showToast({
        title: '请选择预约时间',
        icon: 'none'
      })
    } else if (
      new Date(
        `${currentChangeTime.order_day} ${currentChangeTime.order_time}`
      ) <= new Date()
    ) {
      wx.showToast({
        title: '所选时间已超时，请重新选择',
        icon: 'none'
      })
    } else if (currentChangeDevice == null) {
      let _title = '请选择设备'
      if (deviceList.length == 0) {
        _title = '当前所选时间无可用设备'
      }
      wx.showToast({
        title: _title,
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: `/pages/orderConfirm/orderConfirm?source=${
          this.data.source
        }&data=${JSON.stringify(projectData)}&deviceData=${JSON.stringify(
          currentChangeDevice
        )}&timeData=${JSON.stringify(currentChangeTime)}`
      })
    }
  },
  // 切换店铺
  changeStore() {
    console.log(this.data.projectData.storeData);
    wx.navigateTo({
      url: `/pages/store/store?isSelectProduct=true&&project_id=${JSON.stringify(this.data.ids)}&&defaultStore=${JSON.stringify(this.data.projectData.storeData)}`,
    })
  },
  /**
   * 店铺信息
   * /api/store/info
   */
  getStoreInfo(store_id) {
    get(
      'api/store/info', {
        store_id
      },
      (res) => {
        let projectData = this.data.projectData
        projectData.store_id = res.data.id
        projectData.storeData = res.data
        this.setData({
          projectData,
          // showStore:false
        })
        this.getTime()
        //获取店铺列表
        if (res.data.id == 17) {
          this.getStoreList()
        }
      }
    )
  },
  // 获取店铺列表
  getStoreList() {
    get(
      'api/store', {
        page: 1,
        limit: 10,
      },
      (res) => {
        // res.data.list.forEach((item, index) => {
        //   if (item.id == 17) {
        //     this.setData({
        //       showStore: true
        //     })
        //   }
        //   if (item.id == 17 || item.id == 1) {
        //     res.data.list.splice(index, 1)
        //   }
        // })
        this.setData({
          storeList: res.data.list
        })
      }
    )
  },
    /**
   * 选中店铺
   */
  onChangeStore(e) {
    let storeId = e.currentTarget.dataset.item.id
    this.getStoreInfo(storeId)
  },
  // 关闭选择店铺弹窗
  // onCloseLandscape() {
  //   this.setData({
  //     showStore: false
  //   })
  // }
})