//index.js
//获取应用实例
const { request, serverName,imgServer } = require('../../utils/services');
const { Toast, qqmapsdk } = require('../../utils/util.js');
const { defaultImg, noExhibitionImg } = require('../../utils/images');
const WxParse = require('../../common/component/wxParse/wxParse.js');

// const QQMapWX = require('../../common/component/mapSDK/qqmap-wx-jssdk.min.js');

const app = getApp();
const distItems = [
  {
    name: '按距离排序',
    id: '距离排序',
    idx: 1
  },
  {
    name: '按热度排序',
    id: '热度排序',
    idx: 2
  }
]
const typeItems = [
  {
    name: '展览中',
    id: '展览中',
    idx: 1
  },
  {
    name: '即将开始',
    id: '即将开始',
    idx: 2
  },
  {
    name: '已结束',
    id: '已结束',
    idx: 3
  },
  {
    name: '全部状态',
    id: '全部状态',
    idx: 0
  }
]

Page({
  data: {
    navItem: distItems,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    activeIndex: 0,
    locationName: "珠海",
    locationNameDesp:"",
    isLike: false,
    showConfirm: false,
    tag: "",
    exhibitionList: [],
    commodityImgs: [
      '../../imgs/testImg/thumbSmallImg.jpg',
      '../../imgs/testImg/thumbSmallImg.jpg',
    ],
    type: 5,
    testImg: '../../imgs/testImg/fdkz.png',
    getLocationBtn: false,
    isShow: false,
    exhiNum:0,
    activeDist:'距离排序',
    activeType:'展览中'
  },

  to_search_exhibition: function () {
    wx.navigateTo({
      url: '../yuezhan/search/index',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  onLoad: function () {
    
    this.getLocationName();
    // this.getList(1)

    this.setData({
      serverName,
      noExhibitionImg,
      defaultImg,
      imgServer
    });
  },
  onShareAppMessage: function () {

  },
  onShow: function () {
    let { city, clickToSelect, collectedArr, collectedChange } = app.globalData;
    let { activeIndex, exhibitionList } = this.data
    if (clickToSelect) {
      this.setData({
        locationName: city || "珠海",
        exhibitionList: [],
        activeIndex: 0,
        type: 5
      });

      if (activeIndex == 1) {
        this.getNearByList(1);
      }
      else {
        this.getList(1);
      }

    }
    if (collectedChange) {
      for (let i = 0; i < exhibitionList.length; i++) {
        for (let j = 0; j < collectedArr.length; j++) {
          if (collectedArr[j].collectedId == exhibitionList[i].id) {
            exhibitionList[i].hasCollect = collectedArr[j].status
            if (exhibitionList[i].hasCollect) {
              exhibitionList[i].collectionsCount += 1;
            }
            else {
              exhibitionList[i].collectionsCount -= 1;
            }
            if (exhibitionList[i].collectionsCount < 0) {
              exhibitionList[i].collectionsCount = 0
            }
          }
        }

      }
      this.setData({
        exhibitionList
      })
    }
    app.globalData.clickToSelect = false;
    // app.globalData.collectedChange = false;
  },

  addLike: function (e) {
    let { type, id, idx } = e.currentTarget.dataset;

    let exhibitionList = this.data.exhibitionList;
    let { collectedArr, collectedChange } = app.globalData, hasItem = true;



    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    // if (loginSessionKey){
    request['isCollect']({
      loginSessionKey,
      exhibitionId: id,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        for (let i = 0; i < collectedArr.length; i++) {
          if (collectedArr[i].collectedId && id == collectedArr[i].collectedId) {
            collectedArr[i] = {
              collectedId: id,
              status: res.data.data.hasCollect,
            }
            hasItem = false;
          }
        }
        if (hasItem) {
          collectedArr.push({
            collectedId: id,
            status: res.data.data.hasCollect,
          })
        }

        app.globalData.collectedArr = collectedArr;
        app.globalData.collectedChange = true;

        exhibitionList[idx].hasCollect = res.data.data.hasCollect
        this.setData({
          exhibitionList: exhibitionList
        })
      }

    }, err => {

    }, complete => {

      Toast.hideLoading();
    })
    // }

  },

  showDrop: function (e) {
    let tag = e.target.dataset.id
    let name = e.target.dataset.test
    if (tag==='type'){
      this.setData({
        navItem: {
          type: tag,
          name: name,
          arr: typeItems
        },
        isShow: !this.data.isShow
      })
    }
    else{
      this.setData({
        navItem: {
          type: tag,
          name: name,
          arr: distItems
        },
        isShow: !this.data.isShow
      })
    }
  },

  getLocationName: function () {
    // 调用接口
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            let { city: locationName } = res.result.address_component;
            locationName = locationName.substring(0, 2);
            app.globalData.city = locationName;

            this.setData({
              locationName,
              locationNameDesp: locationName
            })
            this.getList(1)
          },
          fail: function (res) {
            this.setData({
              locationName: ""
            })
          },
          complete: function (res) {
          }
        });
      }
    })
  },

  offlineRecommend: function () {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })
    let { latitude: lat, longitude: lng } = this.data;
    request["offlineRecommend"]({
      lat,
      lng,
    }, "", res => {
      this.setData({
        ExhibitionPopular: res.data.data
      })
    }, err => {

    }, complete => {

    })
  },

  getList: function (page) {
    let { locationNameDesp, locationName, latitude, longitude, activeDist, activeType } = this.data;
    let loginSessionKey = wx.getStorageSync("token");
    let sort = distItems.find(item => item.id === activeDist).idx
    let type = typeItems.find(item => item.id === activeType).idx
    
    this.setData({
      loading: true
    })
    request["getExhibitionListOffline"]({
      page: page,
      type: type,
      loginSessionKey,
      city: locationName,
      sort,
      type,
      lng: longitude,
      lat: latitude
    }, '', res => {
      let tempContent = this.data.exhibitionList
        ? this.data.exhibitionList
        : [];
      let { last: lastPage, totalPages, totalElements, content: exhibitionList } = res.data.data;


      exhibitionList.forEach((currentValue) => {
        currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
      })

      let { openTime } = exhibitionList;
      this.setData({
        currentPage: res.data.data.number + 1,
        lastPage,
        loading: false,
        exhibitionList: tempContent.concat(exhibitionList),
        exhiNum: totalElements
      });
      wx.stopPullDownRefresh();
      // WxParse.wxParseTemArray("replyTemArray", 'reply', replyArr.length, that)

      if (this.data.exhiNum <= 3){
        this.offlineRecommend();
      }

    }, err => {

    }, complete => {

    })
  },

  getNearByList: function (page) {
    let { type, locationName, latitude, longitude } = this.data;
    let loginSessionKey = wx.getStorageSync("token");

    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          Toast.showToast('tip', "无法获取用户位置", () => {
            return;
          })
          this.setData({
            getLocationBtn: true
          })
        }
        else {
          this.setData({
            loading: true,
            getLocationBtn: false
          })
          if (!longitude && !latitude) {
            wx.getLocation({
              success: res => {
                let longitude = (this.longitude = res.longitude);
                let latitude = (this.latitude = res.latitude);
                request["getNearByList"]({
                  page: page,
                  loginSessionKey,
                  city: locationName,
                  lng: longitude,
                  lat: latitude
                }, '', res => {

                  let tempContent = this.data.exhibitionList
                    ? this.data.exhibitionList
                    : [];
                  let { last: lastPage, totalPages, content: exhibitionList } = res.data.data;

                  let { openTime } = exhibitionList;
                  this.setData({
                    currentPage: res.data.data.number + 1,
                    lastPage,
                    loading: false,
                    longitude,
                    latitude,
                    exhibitionList: tempContent.concat(exhibitionList),
                  });
                  wx.stopPullDownRefresh();

                  // WxParse.wxParseTemArray("replyTemArray", 'reply', replyArr.length, that)

                }, err => {

                }, complete => {

                })
              },
            })
          } else {
            request["getNearByList"]({
              page: page,
              loginSessionKey,
              city: locationName,
              lng: longitude,
              lat: latitude
            }, '', res => {

              let tempContent = this.data.exhibitionList
                ? this.data.exhibitionList
                : [];
              let { last: lastPage, totalPages, content: exhibitionList } = res.data.data;

              let { openTime } = exhibitionList;
              this.setData({
                currentPage: res.data.data.number + 1,
                lastPage,
                loading: false,
                exhibitionList: tempContent.concat(exhibitionList),
              });
              wx.stopPullDownRefresh();
            }, err => {
            }, complete => {

            })
          }

        }
      }
    })
  },

  closeDialog: function () {
    this.setData({
      showConfirm: false
    })
  },

  loadMore: function () {
    let { activeIndex } = this.data
    if (!this.data.lastPage) {
      if (activeIndex == 1) {
        this.getNearByList(this.data.currentPage + 1);
      }
      else {
        this.getList(this.data.currentPage + 1);
      }
    } else {
      return;
    }
  },

  onReachBottom: function () {
    if (!this.data.loading) {
      this.loadMore();
    }

  },

  tabClick: function (e) {
    this.setData({
      exhibitionList: [],
      activeIndex: e.currentTarget.id,
      type: e.currentTarget.dataset.tag,
      currentPage: 1
    });
    if (e.currentTarget.id == 1) {
      this.getNearByList(1);
    }
    else {
      this.getList(1);
    }
  },

  onIsclose: function (e) {
    this.setData({
      isShow: e.detail
    })
  },

  getActiveItem:function(e){
    let { activeDist, activeType} = e.detail
    
    this.setData({
      activeDist,
      activeType,
      exhibitionList:[]
    })
    this.getList(1)
  },
  to_search: function () {
    wx.navigateTo({
      url: './search/index',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  }
})
