let Parse = getApp().Parse;
const company = getApp().globalData.company
const uid = Parse.User.current()?.id

const {
  getStores
} = require(".././../service/request")
let sev = require('../../service/request')
const dateF = require('../../../utils/date')
Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    statusBarHeight: 0,
    screenHeight: 0,
    customHeight: 0,
    bottomNavHeight: 0,
    contentHeight: 0,
    topheight: 0,



    date_start: '',
    date_end: '',
    date_start1: '',
    date_end1: '',
    istoday: true,
    daysBetween: 1,
    show: false,
    //店铺数据
    storeList: [],
    oddList: [], //单数列-两列布局用到
    evenList: [], //双数列-两列布局用到
    //价格
    price: 211,

    value: '', //搜索
    valueTimeout: null, //搜索框计时器
    start: '',
    end: '',

    //触底加载
    loadedItems: 0,
    pageSize: 5,
    noMoreItems: false,
    specDateMap: {}, //今日-明日 日期对应
    showRoom: [], //首页推荐店铺
  },
  lifetimes: {
    detached: function () {},
    attached: async function () {
      const systemInfo = wx.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight || 0;
      const screenHeight = systemInfo.screenHeight || 0;
      const custom = wx.getMenuButtonBoundingClientRect();
      const customHeight = custom.height + 10 + 2 || 0;
      const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;

      const contentHeight = (screenHeight - bottomNavHeight - 50 - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
      const topheight = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth
      this.setData({
        statusBarHeight,
        screenHeight,
        customHeight,
        bottomNavHeight,
        contentHeight,
        topheight
      });
      this.getcurrentdate();
      this.getShopStore()
      this.getShowRoom()
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /** 初始日期-今日明日*/
    getcurrentdate() {
      const today = new Date();
      const tomorrow = new Date();
      tomorrow.setDate(today.getDate() + 1);
      let date_start = this.formatDate(today)
      let date_end = this.formatDate(tomorrow)
      let specDateMap = {}
      specDateMap[date_start] = '今天'
      specDateMap[date_end] = '明天'
      this.setData({
        date_start,
        date_end,
        specDateMap,
        start: today,
        end: tomorrow
      });
    },

    /**日历-开*/
    onDisplay() {
      this.setData({
        show: true
      });
    },
    /**日历-关*/
    onClose() {
      this.setData({
        show: false
      });
    },

    /** 选好日期点击完成后*/
    async onConfirm(event) {
      const [start, end] = event.detail;
      const daysBetween = sev.getDays(start, end); // 计算天数差
      this.setData({
        show: false,
        start,
        end,
        date_start: `${this.formatDate(start)}`,
        date_end: `${this.formatDate(end)}`,
        daysBetween
      });
    },
    /**获取店铺 */
    async getShopStore() {
      let {
        value,
        storeList,
        oddList,
        evenList
      } = this.data
      let d = await sev.getStores({
        val: value || '',
        uid: uid,
        skip: storeList?.length || 0,
        limit: 10
      })
      let odd = d?.filter((item, index) => index % 2 != 0) || []//奇
      let even = d?.filter((item, index) => index % 2 == 0) || []//偶
      oddList = [...oddList, ...odd]
      evenList = [...evenList, ...even]
      storeList = [...(evenList || []), ...(oddList || [])]
      // console.log(storeList)
      this.setData({
        storeList,
        oddList,
        evenList
      })
    },
    /**获取首页推荐 */
    async getShowRoom() {
      let d = await sev.getStores({
        uid: uid,
        skip: 0,
        limit: 3,
        isShow: true
      })
      this.setData({
        showRoom: d || []
      })
    },
    /**关键字搜索 */
    changeValue() {
      let {
        valueTimeout
      } = this.data
      clearTimeout(valueTimeout)
      let that = this
      valueTimeout = setTimeout(() => {
        that.setData({
          storeList: [],
          oddList: [],
          evenList: []
        })
        that.getShopStore()
      }, 2000);
      this.setData({
        valueTimeout
      })
    },


    toStore(e) {
      let {store_id} = e.currentTarget.dataset
      let {start,end}=this.data
      let url = `/nova-tourism/pages/homestay/homestay-detail/index?store_id=${store_id}&start=${dateF.formatTime("YYYY-mm-dd", start)}&end=${dateF.formatTime("YYYY-mm-dd", end)}`
      console.log(url)
      wx.navigateTo({
        url: url,
      })
    },

    /**收藏/取消收藏 */
    async collect(e) {
      let {
        storeList
      } = this.data
      let index = e.currentTarget.dataset.index
      let store = storeList[index]
      let query = new Parse.Query('DramaShopCollect');
      query.equalTo('company', company);
      query.equalTo('user', uid);
      query.equalTo('homestayStore', store?.objectId);
      query.notEqualTo('isDeleted', "true");
      let collect = await query.first();
      if (!collect?.id) {
        let DramaShopCollect = Parse.Object.extend('DramaShopCollect')
        collect = new DramaShopCollect()
        collect.set('company', {
          __type: 'Pointer',
          className: 'Company',
          objectId: company
        });
        collect.set('homestayStore', {
          __type: 'Pointer',
          className: 'ShopStore',
          objectId: store?.objectId
        });
        collect.set('user', {
          __type: 'Pointer',
          className: '_User',
          objectId: uid
        });
        collect.set('isCollect', true);
      }
      collect.set('isCollect', !(store.iscollect || false))
      await collect.save()
      storeList[index].iscollect = !(storeList[index].iscollect || false)
      this.setData({
        storeList
      })
    },
    /**搜索框距顶部距离 */
    onScroll(event) {
      this.setData({scrollTop: event.detail.scrollTop,})
    },

    /** 转换日期 MM月dd日*/
    formatDate(date) {
      date = new Date(date);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
  }
});