// nova-tourism/components/template2/homestay/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const compute = require("../../../../utils/compute.js");
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    imgUrls: [
      'https://s1.ax1x.com/2023/04/10/ppqifvF.png',
      'https://s1.ax1x.com/2023/04/10/ppqiWgU.png',
      'https://s1.ax1x.com/2023/04/10/ppqiR3T.png'
    ],
    tabs: [{
        title: '推荐',
        // icon: 'https://s1.ax1x.com/2023/04/10/ppqEqdH.png'
      },
      {
        title: '价格',
        // icon: 'https://s1.ax1x.com/2023/04/10/ppqkh79.png'
      },
    ],
    active: 0,
    tabIndex: 0,
    latitude: 0,
    longitude: 0,
    searchVal:'',
    loadIndex: 1,
  },
  lifetimes: {
    attached() {
      this.getData()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async getData() {
      if (this.data.latitude == 0 && this.data.longitude == 0) {
        let {
          latitude,
          longitude
        } = await this.getLocation()
        this.setData({
          latitude,
          longitude
        })
      }
      this.getBanner()
      this.getRooms()
      await this.getCategory()
      this.getShopRank(this.data.textItem)
    },
    getLocation() {
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            resolve({
              latitude: res.latitude,
              longitude: res.longitude
            })
          },
          fail: () => {
            resolve({
              latitude: 0,
              longitude: 0
            })
          },
          complete: () => {}
        });
      })

    },
    async getBanner() {
      let Banner = new Parse.Query('Banner')
      Banner.notEqualTo('isDeleted', "true")
      Banner.equalTo('company', company)
      Banner.equalTo('isEnabled', "true")
      Banner.equalTo('type', 'gourmet')
      let banner = await Banner.find()
      if (banner && banner.length > 0) {
        let listJSON = []
        banner.forEach(c => {
          listJSON.push(c.toJSON())
        })
        this.setData({
          banner: listJSON
        })
      }
    },
    async getShopStore() {
      let ShopStore = new Parse.Query('ShopStore')
      ShopStore.notEqualTo('isDeleted', "true")
      ShopStore.equalTo('company', company)
      ShopStore.equalTo('type', "stay")
      ShopStore.limit(10)
      if (this.data.active == 0) {
        ShopStore.descending('isShow')
      }
      if (this.data.active == 1) {
        ShopStore.descending('score')
      }
      if (this.data.active == 3) {
        ShopStore.ascending('perCapita')
      }
      if (this.data.value) {
        ShopStore.contains('storeName', this.data.value)
      }
      let shopStores = await ShopStore.find()
      console.log(shopStores);
      if (shopStores) {
        let listJSON = []
        for (let i = 0; i < shopStores.length; i++) {
          let json = shopStores[i].toJSON()
          let distances = compute.computeDistance(
            this.data.latitude,
            this.data.longitude,
            json.location.latitude,
            json.location.longitude
          )
          json.distances = distances.toFixed(2)
          listJSON.push(json)
        }
        //按距离排序
        if (this.data.active == 2) {
          listJSON = listJSON.sort((a, b) => {
            return a.distance - b.distance
          })
        }
        this.setData({
          list: listJSON
        })
      }
    },
    async getRooms () {
      console.log('getRooms');
      let Room = new Parse.Query('ShopRoom')
      Room.equalTo('company', company)
      Room.equalTo('isEnabled', true)
      if(this.data.searchVal != ''){
        Room.contains('name',this.data.searchVal)
      }
      if (this.data.active == 1) {
        Room.ascending('price')
      }
      if(this.data.active == 0){
        Room.equalTo('isRecom',true)
      }
      Room.skip((this.data.loadIndex - 1) * 10)
      Room.select(
        'name',
        'images',
        'price',
        'total',
        'remaining',
        'merber',
        'type',
        'area',
        'tags',
        'address'
      )
      Room.limit(10)
      let rooms = await Room.find()
      rooms = rooms.map((room) => room.toJSON())
      rooms = this.data.loadIndex == 1 ? rooms : this.data.rooms.concat(rooms)
      this.setData({ rooms })
      console.log(rooms)
    },
    async getCategory(){
      let cate = new Parse.Query("Category")
      cate.notEqualTo('isDeleted', "true")
      cate.equalTo("company",company)
      cate.equalTo("type",'stayTag')
      let cateDate = await cate.find()
      let cateList = []
      cateDate.forEach(res=>{
        let item = res.toJSON()
        cateList.push(item)
      })
      if(cateList.length){
        this.setData({
          textItem:cateList[0].objectId,
        })
      }
      this.setData({
        cateList
      })
    },
    async getShopRank(id) {
      let ShopStore = new Parse.Query('ShopStore')
      ShopStore.notEqualTo('isDeleted', "true")
      ShopStore.equalTo('company', company)
      ShopStore.equalTo('type', "stay")
      ShopStore.equalTo('category', id)
      ShopStore.include("category")
      let shopStores = await ShopStore.find()
      if (shopStores) {
        let rankList = []
        for (let i = 0; i < shopStores.length; i++) {
          let json = shopStores[i].toJSON()
          rankList.push(json)
        }
        this.setData({
          rankList
        })
      }
    },
    onTabClick(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({
        tabIndex: index,
        active: index
      })
      this.getRooms()
    },
    changeText(e) {
      let {
        id
      } = e.currentTarget.dataset
      this.setData({
        textItem: id
      })
      this.getShopRank(id)
    },
    goUrl(e) {
      let {
        url
      } = e.currentTarget.dataset
      wx.navigateTo({
        url: url,
      })
    },
  }
})
