//index.js
const {
  request,
  serverName,
  imgServer
} = require('../../utils/services');
const {
  Toast
} = require('../../utils/util.js');
const {
  defaultImg,
  noExhibitionImg,
  closeImg
} = require('../../utils/images');


const WxParse = require('../../common/component/wxParse/wxParse.js');
const app = getApp();


Page({
  data: {
    // navItem: [{ title: '热门', tag: 0 },  { title: '即将开始', tag: 2 }, { title: '展览中', tag: 4 }, { title: '已结束', tag: 6 }],
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 1000,
    activeIndex: 0,
    animationData: {},
    loading: false,
    isLike: true,
    commodityImgs: [],
    testImg: '../../imgs/testImg/fdkz.png',
    currentPage: 1,
    exhibitionList: [],
    likes: {},
    tag: 0,
    latitude: null,
    longitude: null,
    showRecommend:false
  },

  onLoad: function() {
    this.setData({
      serverName,
      defaultImg,
      noExhibitionImg,
      imgServer,
      closeImg,
      showRecommend:true
      // isLogin
    })

    this.getBanner();
    this.getList(1);
    wx.hideTabBar()
  },

  loadMore: function() {
    if (!this.data.lastPage) {
      console.log(this.data.currentPage + 1)
      this.getList(this.data.currentPage + 1);
    } else {
      return;
    }
  },

  onReachBottom: function() {
    if (!this.data.loading) {
      this.loadMore();
      console.log('reach Bottom');
    }
  },

  onShow: function() {
    let {
      collectedArr,
      collectedChange
    } = app.globalData;
    let {
      exhibitionList
    } = this.data
    let isLogin = app.globalData.isLogin;
    this.setData({
      isLogin
    })

    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
            }
          }
        }
        // console.log(collectedArr.status, collectedArr.collectedId)

      }
      this.setData({
        exhibitionList,

      })
    }
    // app.globalData.clickToSelect = false;
    app.globalData.collectedChange = false;

  },
  onPullDownRefresh: function() {
    this.setData({
      exhibitionList: [],
      currentPage: 1
    });
    this.getBanner();
    this.getList(1);
  },

  hideRecommend:function(){
    this.setData({
      showRecommend:false
    })
    wx.showTabBar()
  },

  fetchData: function (page){
    request["getExhibitionList"]({
      page: page,
      type: 0,
      lat: this.data.latitude,
      lng: this.data.longitude
    }, '', res => {

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

      let {
        openTime
      } = exhibitionList;
      console.log(res)
      exhibitionList.forEach((currentValue) => {
        currentValue.distance = Math.ceil(currentValue.distance);
        if (currentValue.product){
          currentValue.product.link = escape(currentValue.product.link);
          currentValue.product.imageUrl = escape(currentValue.product.imageUrl);
        }
      })
      this.setData({
        currentPage: res.data.data.number + 1,
        lastPage,
        loading: false,
        exhibitionList: tempContent.concat(exhibitionList),
      });
      console.log(exhibitionList)
      // WxParse.wxParseTemArray("replyTemArray", 'reply', replyArr.length, that)

    }, err => {

    }, complete => {
      wx.stopPullDownRefresh();
    })
  },


  getList: function(page) {
    let type = this.data.tag;
    this.setData({
      loading: true
    })
    if (this.data.latitude||this.data.longitude) {
      this.fetchData(page)
    } else {
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.setData({
            latitude: res.latitude,
            longitude: res.longitude
          })
          this.fetchData(page)
        },
        fail: (res) => {
          this.fetchData(page)
        }
      })
    }
  },

  getBanner: function() {
    request["getBannerList"]({}, '', res => {
      let {
        content: commodityImgs
      } = res.data.data;
      // console.log("wdwdwd",commodityImgs)
      this.setData({
        commodityImgs: commodityImgs || []
      });
      console.log('banner', commodityImgs)
    }, err => {

    }, complete => {
      wx.stopPullDownRefresh()
    })
  },

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

    let likes = this.data.likes;
    likes[id] = !likes[id];
    let exhibitionList = this.data.exhibitionList;
    let {
      collectedArr,
      collectedChange
    } = app.globalData, hasItem = true;


    console.log('type', type)
    this.setData({
      likes: likes
    })
    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) {
            console.log("true")
            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();
    })
    // }

    console.log(this.data.exhibitionList)
  },

  tabClick: function(e) {
    // console.log(e.currentTarget.dataset)

    // if (e.currentTarget.id == 1) {

    //   wx.switchTab({
    //     url: '../swkz/index',
    //     success: function (res) { },
    //     fail: function (res) { },
    //     complete: function (res) { },
    //   })
    // }
    // else {
    this.setData({
      exhibitionList: [],
      activeIndex: e.currentTarget.id,
      tag: e.currentTarget.dataset.tag,
      currentPage: 1
    });
    this.getList(1);
    // }
  },
  onShareAppMessage: function() {

  },


  to_pay: function(e) {
    // console.log('dwdwdw', e.currentTarget.dataset)

    let {
      url,
      pagetype,
      urltype,
      hasproduct,
      haspay,
      productlink,
      id,
      description,
      imageurl,
      relayUrl
    } = e.currentTarget.dataset;


    // app.globalData.currentUrl = url
    // console.log('dwdwdw', app.globalData.currentUrl)

    // console.log('dwdwdwd',wx.getStorageSync('url'))

    switch (urltype) {
      case 0:
        wx.navigateTo({
          url: `../wv_page/index`,
          success: function(res) {},
          fail: function(res) {},
          complete: function(res) {},
        })
        break;
      case 1:
        switch (pagetype) {
          case 0:
            wx.navigateTo({
              url: `../cg_detail/index?id=${url}`,
              success: function(res) {},
              fail: function(res) {},
              complete: function(res) {},
            })
            break;
          case 1:
            if (hasproduct) {
              wx.navigateTo({
                url: `../wv_page/index?&id=${url}`,
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {},
              })
            } else {
              wx.navigateTo({
                url: `../zl_detail/index?id=${url}`,
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {},
              })
            }

            break;
          default:
            break;
        }
        break;
      case 2:
        app.globalData.bannerHtml = description;
        wx.navigateTo({
          url: `./html_detail/index?id=${id}&imageUrl=${imageurl}&relayUrl=${relayUrl||''}`,
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })
        break;
      default:
        break;
    }
  }
})