// pages/zhanxun/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 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: {
    tabs: ['线上看展', '线下展讯'],
    activeIndex: 0,
    loading: false,
    imgServer,
    defaultImg,
    noExhibitionImg,
    // 线上看展数据
    onlineExhibitionList: [],
    onlineCurrentPage: 1,
    onlineLastPage: false,
    onlineLikes: {},
    // 线下展讯数据
    offlineExhibitionList: [],
    offlineCurrentPage: 1,
    offlineLastPage: false,
    navItem: distItems,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    locationName: "珠海",
    locationNameDesp: "",
    isLike: false,
    showConfirm: false,
    tag: "",
    commodityImgs: [
      '../../imgs/testImg/thumbSmallImg.jpg',
      '../../imgs/testImg/thumbSmallImg.jpg',
    ],
    type: 5,
    testImg: '../../imgs/testImg/fdkz.png',
    getLocationBtn: false,
    isShow: false,
    exhiNum: 0,
    activeDist: '距离排序',
    activeType: '展览中'
  },

  onLoad: function () {
    this.setData({
      serverName,
      defaultImg,
      noExhibitionImg,
      imgServer
    });
    
    this.getLocationName();
    // 初始加载线上看展数据
    this.getOnlineExhibitionList(1);
  },

  tabClick: function (e) {
    const index = e.currentTarget.id;
    this.setData({
      activeIndex: index
    });
    
    // 切换到线上看展
    if (index == 0) {
      if (this.data.onlineExhibitionList.length === 0) {
        this.getOnlineExhibitionList(1);
      }
    } 
    // 切换到线下展讯
    else {
      if (this.data.offlineExhibitionList.length === 0) {
        this.getOfflineExhibitionList(1);
      }
    }
  },

  // 获取线上看展数据
  getOnlineExhibitionList: function (page) {
    this.setData({
      loading: true
    });
    
    request["getExhibitionList"]({
      page: page,
      type: 1 // 线上看展类型
    }, '', res => {
      let tempContent = this.data.onlineExhibitionList || [];
      let { last: lastPage, content: exhibitionList } = res.data.data;
      
      exhibitionList.forEach((currentValue) => {
        currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
        currentValue.product ? currentValue.product.imageUrl = escape(currentValue.product.imageUrl) : '';
      });
      
      this.setData({
        onlineCurrentPage: page,
        onlineLastPage: lastPage,
        loading: false,
        onlineExhibitionList: page === 1 ? exhibitionList : tempContent.concat(exhibitionList),
      });
      
      wx.stopPullDownRefresh();
    }, err => {
      this.setData({
        loading: false
      });
    });
  },

  // 获取线下展讯数据
  getOfflineExhibitionList: function (page) {
    let { locationName, 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,
      loginSessionKey,
      city: locationName,
      sort: sort,
      type: type,
      lng: this.data.longitude,
      lat: this.data.latitude,
    }, '', res => {
      let tempContent = this.data.offlineExhibitionList || [];
      let { last: lastPage, totalElements, content: exhibitionList } = res.data.data;
      
      exhibitionList.forEach((currentValue) => {
        currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
      });
      
      this.setData({
        offlineCurrentPage: page,
        offlineLastPage: lastPage,
        loading: false,
        offlineExhibitionList: page === 1 ? exhibitionList : tempContent.concat(exhibitionList),
        exhiNum: totalElements
      });
      
      wx.stopPullDownRefresh();
      
      if (this.data.exhiNum <= 3) {
        this.offlineRecommend();
      }
    }, err => {
      this.setData({
        loading: false
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    if (this.data.activeIndex == 0) {
      this.setData({
        onlineExhibitionList: [],
        onlineCurrentPage: 1
      });
      this.getOnlineExhibitionList(1);
    } else {
      this.setData({
        offlineExhibitionList: [],
        offlineCurrentPage: 1
      });
      this.getOfflineExhibitionList(1);
    }
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (this.data.loading) return;
    
    if (this.data.activeIndex == 0) {
      if (!this.data.onlineLastPage) {
        this.getOnlineExhibitionList(this.data.onlineCurrentPage + 1);
      }
    } else {
      if (!this.data.offlineLastPage) {
        this.getOfflineExhibitionList(this.data.offlineCurrentPage + 1);
      }
    }
  },

  // 收藏/取消收藏展览
  addLike: function (e) {
    let { type, id, idx, listType } = e.currentTarget.dataset;
    let exhibitionList = listType === 'online' ? this.data.onlineExhibitionList : this.data.offlineExhibitionList;
    let { collectedArr } = app.globalData;
    let hasItem = true;

    if (listType === 'online') {
      let onlineLikes = this.data.onlineLikes;
      onlineLikes[id] = !onlineLikes[id];
      this.setData({
        onlineLikes: onlineLikes
      });
    }

    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    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;
        
        if (listType === 'online') {
          this.setData({
            onlineExhibitionList: exhibitionList
          });
        } else {
          this.setData({
            offlineExhibitionList: exhibitionList
          });
        }
      }
    }, err => {
      // 错误处理
    }, complete => {
      Toast.hideLoading();
    });
  },
  
  // 获取位置名称
  getLocationName: function() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        
        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
            });
          },
          fail: function (res) {
            this.setData({
              locationName: ""
            });
          }
        });
      },
      fail: () => {
        this.setData({
          getLocationBtn: true
        });
      }
    });
  },
  
  // 线下推荐
  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 => {
      // 错误处理
    });
  },
  
  // 前往搜索页面
  to_search: function() {
    wx.navigateTo({
      url: '../tongcheng/search/index'
    });
  },
  
  // 展览搜索
  to_search_exhibition: function () {
    wx.navigateTo({
      url: '../yuezhan/search/index'
    });
  },
  
  // 显示下拉菜单
  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
      });
    }
  },
  
  // 关闭下拉菜单
  onIsclose: function(e) {
    this.setData({
      isShow: e.detail
    });
  },
  
  // 选择下拉菜单项
  getActiveItem: function(e) {
    let { activeDist, activeType } = e.detail;
    
    this.setData({
      activeDist,
      activeType,
      offlineExhibitionList: []
    });
    
    this.getOfflineExhibitionList(1);
  },
  
  // 关闭确认对话框
  closeDialog: function() {
    this.setData({
      showConfirm: false
    });
  },
  
  // 获取附近列表
  getNearByList: function (page) {
    let { 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 = res.longitude;
                let latitude = res.latitude;
                
                request["getNearByList"]({
                  page: page,
                  loginSessionKey,
                  city: locationName,
                  lng: longitude,
                  lat: latitude
                }, '', res => {
                  let tempContent = this.data.offlineExhibitionList || [];
                  let { last: lastPage, content: exhibitionList } = res.data.data;

                  this.setData({
                    offlineCurrentPage: page,
                    offlineLastPage: lastPage,
                    loading: false,
                    longitude,
                    latitude,
                    offlineExhibitionList: page === 1 ? exhibitionList : tempContent.concat(exhibitionList),
                  });
                  
                  wx.stopPullDownRefresh();
                }, err => {
                  // 错误处理
                });
              }
            });
          } else {
            request["getNearByList"]({
              page: page,
              loginSessionKey,
              city: locationName,
              lng: longitude,
              lat: latitude
            }, '', res => {
              let tempContent = this.data.offlineExhibitionList || [];
              let { last: lastPage, content: exhibitionList } = res.data.data;

              this.setData({
                offlineCurrentPage: page,
                offlineLastPage: lastPage,
                loading: false,
                offlineExhibitionList: page === 1 ? exhibitionList : tempContent.concat(exhibitionList),
              });
              
              wx.stopPullDownRefresh();
            }, err => {
              // 错误处理
            });
          }
        }
      }
    });
  },
  
  onShow: function() {
    let { city, clickToSelect, collectedArr, collectedChange } = app.globalData;
    
    if (clickToSelect) {
      this.setData({
        locationName: city || "珠海",
        offlineExhibitionList: [],
        offlineCurrentPage: 1
      });
      
      if (this.data.activeIndex == 1) {
        this.getOfflineExhibitionList(1);
      }
    }
    
    if (collectedChange) {
      // 更新线上看展收藏状态
      if (this.data.onlineExhibitionList.length > 0) {
        let onlineExhibitionList = this.data.onlineExhibitionList;
        for (let i = 0; i < onlineExhibitionList.length; i++) {
          for (let j = 0; j < collectedArr.length; j++) {
            if (collectedArr[j].collectedId == onlineExhibitionList[i].id) {
              onlineExhibitionList[i].hasCollect = collectedArr[j].status;
              if (onlineExhibitionList[i].hasCollect) {
                onlineExhibitionList[i].collectionsCount += 1;
              } else {
                onlineExhibitionList[i].collectionsCount -= 1;
              }
              if (onlineExhibitionList[i].collectionsCount < 0) {
                onlineExhibitionList[i].collectionsCount = 0;
              }
            }
          }
        }
        this.setData({ onlineExhibitionList });
      }
      
      // 更新线下展讯收藏状态
      if (this.data.offlineExhibitionList.length > 0) {
        let offlineExhibitionList = this.data.offlineExhibitionList;
        for (let i = 0; i < offlineExhibitionList.length; i++) {
          for (let j = 0; j < collectedArr.length; j++) {
            if (collectedArr[j].collectedId == offlineExhibitionList[i].id) {
              offlineExhibitionList[i].hasCollect = collectedArr[j].status;
              if (offlineExhibitionList[i].hasCollect) {
                offlineExhibitionList[i].collectionsCount += 1;
              } else {
                offlineExhibitionList[i].collectionsCount -= 1;
              }
              if (offlineExhibitionList[i].collectionsCount < 0) {
                offlineExhibitionList[i].collectionsCount = 0;
              }
            }
          }
        }
        this.setData({ offlineExhibitionList });
      }
    }
    
    app.globalData.clickToSelect = false;
    app.globalData.collectedChange = false;
  },
  
  onShareAppMessage: function () {
    // 分享功能
  }
})