const util = require('../../utils/util.js');
const app = getApp();
// var crypto = require('../../utils/crypto.js');//注意路径是否正确
Page({
  data: {
    region: '',
    showVideoColumn: 0,
    pageIndex: 1, //当前页
    activeData: [], //活动列表
    historyData: [], //往期活动列表
    bottom: false,
    imgPath: '',
    showBack: false,
    screenHid: true,
    info: {},
    openTips: wx.getStorageSync("safeTips") || {
      "num": 0,
      "oldDate": util.getNowFormatDate('yyyy-MM-dd')
    },
    screen: [{
      id: 0,
      txt: '全部'
    }, {
      id: 1,
      txt: '周末单日'
    }, {
      id: 2,
      txt: '小长假'
    }, {
      id: 3,
      txt: '冬夏令营'
    }, {
      id: 4,
      txt: '往期活动'
    }],
    days: 0,
    default: [{
      id: 0,
      txt: '默认排序'
    }, {
      id: 1,
      txt: '开始时间由近到远'
    }, {
      id: 2,
      txt: '人气从高到低'
    }],
    sort: 0,
    defaultHid: true,
    activityStatus: true, // true - 上架活动可继续查询  false - 不可继续查询
    HistorypageIndex: 1,
    tabbar: {}
  },
  openServicePopup() {
    this.setData({
      showChat: true
    })
  },
  closeChat(e) {
    this.setData({
      showChat: e.detail
    })
  },
  // 获取弹窗广告信息
  safetyTip() {
    let that = this,
      safeTips = wx.getStorageSync("safeTips"),
      getInfo = {};
    util.ajax({
      func: '/v2/index/advert/popup',
      load: false
    }, function (res) {
      if (res.code == 0) {
        // 不使用接口返回，展示默认
        // getInfo.data = res.data;
        getInfo.entryPage = 'homePage';
        getInfo.showPopup = true;
        that.safeTip = that.selectComponent('#safeTip');
        that.safeTip.getSafeTips(getInfo);
      }
    })
    this.setData({
      isShow: safeTips.show
    });
  },
  onLoad(options) {
    console.log(options)
    app.editTabbar();
    let that = this;
    // this.safetyTip();
    this.setData({
      imgPath: util.config.imgPath
    });
    if (!util.isEmpty(options.scene)) {
      // 调用渠道访问记录接口
      let channelParam = options.scene.replace("channel%3D", "").replace("channel=", ""),
        that = this;
      // wx.setStorageSync("channelCode",{channel:channelParam,channelTimes:1});
      util.config.channelInfo = {
        channel: channelParam,
        channelTimes: 1
      }
      util.getChannelMsg(channelParam).then((res) => {
        console.log('是否创建渠道记录', res)
      });
    }
    this.safetyTip();
    if (options.invite) {
      wx.setStorageSync("WX-invite", options.invite);
    }
    if (options.channel) {
      util.config.channelInfo = {
        channel: options.channel,
        channelTimes: 1
      }
      util.getChannelMsg(options.channel)
    }
  },
  info() {
    let that = this;
    util.ajax({
      func: "v2/categoryHomePageChallenge/info",
      data: {},
      load: false
    }, function (res) {
      if (res.code == 0) {
        that.setData({
          info: res.data
        });
      }
    });
  },
  comfun() {
    this.setData({
      region: app.globalData.city.city || '',
      activityStatus: true
    });
    this.info();
    this.getHotActivity(1, 0, false, this.data.days, this.data.sort);
    this.reportAnalytics(app.globalData.city.city); //上报定位城市
  },
  onShow() {
    let that = this;
    // util.promise().then(function (value) {
    that.comfun();
    var previous = app.globalData.previous; //选择前城市
    console.log(previous, 68686)
    var region = '永康';
    that.setData({
      region,
      activityStatus: true
    });
    if (previous && region && previous != region) {
      app.globalData.previous = region;
      that.info();
      that.getHotActivity(1, 0, false, this.data.days, this.data.sort);
    }
    // });
  },
  reportAnalytics(city) {
    wx.reportAnalytics('location', {
      city
    });
  },
  onReachBottom() {
    if (!this.data.bottom) {
      wx.showNavigationBarLoading();
      this.getHotActivity((this.data.days == 4 || !this.data.activityStatus) ? (this.data.HistorypageIndex + 1) : (this.data.pageIndex + 1), 1, false, this.data.days, this.data.sort)
    }
  },
  onPageScroll(e) {
    var showBack = this.data.showBack;
    if (e.scrollTop > 800 && !showBack) {
      this.setData({
        showBack: true
      })
    } else if (e.scrollTop <= 800 && showBack) {
      this.setData({
        showBack: false
      })
    }
    // 筛选
    let screenHid = this.data.screenHid,
      that = this;
    var query = wx.createSelectorQuery();
    query.select('#screen').boundingClientRect();
    query.exec(function (res) {
      // if (screenHid && res && res[0].top <= 50) {
      //   that.setData({
      //     screenHid: false
      //   })
      // } else if (!screenHid && res && res[0].top > 50) {
      //   that.setData({
      //     screenHid: true
      //   })
      // }
    })
  },
  onPullDownRefresh() {
    let that = this;
    if (!util.isObjEmpty(app.globalData.city)) {
      wx.showNavigationBarLoading();
      // that.setData({ region: app.globalData.city.city });
      setTimeout(function () {
        that.info();
        that.getHotActivity(1, 2, true, that.data.days, that.data.sort);
      }, 1000);
    } else {
      wx.stopPullDownRefresh();
    }
  },
  // 获取当前活动
  getHotActivity(pageIndex, status, PullDown, days, sort) {
    let that = this;
    if (days != 4 && this.data.activityStatus) {
      util.ajax({
        func: "v2/article/recom_list",
        data: {
          "pageIndex": pageIndex,
          "pageSize": 10,
          'type': days || 0,
          'sort': sort || 0
        },
        load: false
      }, function (res) {
        console.log(res);
        if (res.code == 0) {
          res.data.list.map(el => {
            if (!util.isEmpty(el.discount)) {
              let arr = [];
              if (el.discount.indexOf('+') == -1) {
                arr.push(el.discount);
              } else {
                arr = el.discount.split('+');
              }
              el.discount = arr;
            }
          });
          let datas = res.data.list,
            activeData = that.data.activeData,
            bottom = false,
            imgPath = that.data.imgPath;
          if (datas.length < 10) {
            // bottom = true;
            that.data.activityStatus = false;
            that.getHistoryActive(1, days, status)
          }
          activeData = pageIndex == 1 ? datas : [...activeData, ...datas];
          that.setData({
            activeData,
            pageIndex,
            bottom,
            days,
            sort,
            activityStatus: that.data.activityStatus
          })
          wx.hideNavigationBarLoading()
        } else {
          util.showTips(res.reason);
        }
        // if (status == '0') {//onshow
        // } else if (status == '1') {//onReachBottom
        //   wx.hideNavigationBarLoading();
        // } else if (status == '2') {//onPullDownRefresh
        //   wx.stopPullDownRefresh();
        //   wx.hideNavigationBarLoading();
        // }
      });
    } else {
      this.getHistoryActive(pageIndex, days, status)
    }
  },
  // 获取往期活动
  getHistoryActive(pageIndex, days, status) {
    let that = this;
    util.ajax({
      func: "v2/article/history_list",
      data: {
        "pageIndex": pageIndex,
        "pageSize": 10
      },
      load: false
    }, function (res) {
      if (res.code == 0) {
        res.data.list.map(el => {
          if (!util.isEmpty(el.discount)) {
            let arr = [];
            if (el.discount.indexOf('+') == -1) {
              arr.push(el.discount);
            } else {
              arr = el.discount.split('+');
            }
            el.discount = arr;
          }
        });
        let datas = res.data.list,
          historyData = that.data.historyData,
          bottom = false,
          imgPath = that.data.imgPath;
        if (datas.length < 10) bottom = true;
        historyData = pageIndex == 1 ? datas : [...historyData, ...datas];
        that.setData({
          historyData,
          HistorypageIndex: pageIndex,
          bottom,
          days
        })
      } else {
        util.showTips(res.reason);
      }
      if (status == '0') { //onshow
      } else if (status == '1') { //onReachBottom
        wx.hideNavigationBarLoading();
      } else if (status == '2') { //onPullDownRefresh
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }
    });
  },
  navigator(e) {
    util.navigator(e.currentTarget.dataset.url);
  },
  navigatorCols(e) {

    let data = e.currentTarget.dataset,
      info = this.data.info[data.type][data.index],
      url = '';
    console.log(data, info)
    if (data.type == 'cyclePositions') {
      wx.reportAnalytics('swipe', {
        aid: data.id,
        title: data.title,
      });
    }
    // 类目类型 0 公众号推文 1 活动视频 2 指定活动合集 
    let canJump = true;
    switch (info.categoryType) {
      case 2:
        url = '/pages/public/swiper/list?id=' + info.id + '&title=' + info.title;
        break;
      case 1:
        url = '/pages/public/video/video';
        break;
      case 0:
        url = '/pages/public/swiper/web?url=' + encodeURIComponent(info.url) + '&title=' + encodeURIComponent(info.title)
        break;
    }
    console.log(url)
    if (canJump) {
      wx.navigateTo({
        url: url
      });
    }
  },
  navigatorLive() {
    wx.navigateTo({
      url: '/pages/public/live/list'
    });
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 500
    })
  },
  // 选择活动类型
  chooseScreen(e) {
    wx.showNavigationBarLoading();
    let days = e.currentTarget.dataset.id;
    if (days == 4) {
      this.setData({
        activeData: []
      })
    }
    this.setData({
      days,
      defaultHid: true,
      activityStatus: true,
      historyData: []
    })
    this.getHotActivity(1, 1, false, days, this.data.sort)
  },
  defaultScreen(e) {
    wx.showNavigationBarLoading();
    let sort = e.currentTarget.dataset.id;
    this.getHotActivity(1, 1, false, this.data.days, sort)
    this.setData({
      sort,
      defaultHid: true
    })
  },
  defaultShow() {
    this.setData({
      defaultHid: !this.data.defaultHid
    })
  },
  onShareAppMessage() {
    var inviteCode = '',
      channelInfo = util.config.channelInfo;
    inviteCode = app.globalData.userInfo ? app.globalData.userInfo.code : '';
    return {
      title: '挑战家族',
      path: '/pages/home/index?' +
        ('&invite=' + inviteCode) + ((channelInfo.channel != 0 && !util.isEmpty(channelInfo.channel) && channelInfo.channelTimes == 1) ? ('&channel=' + channelInfo.channel) : '') +
        ((channelInfo.channel != 0 && channelInfo.channelTimes == 1) ? ('&channelTimes=' + (parseInt(channelInfo.channelTimes) + 1)) : '')
    }
  },
  // 分享到朋友圈 不支持自定义
  onShareTimeline() {
    var inviteCode = '',
      channelInfo = util.config.channelInfo;
    inviteCode = app.globalData.userInfo ? app.globalData.userInfo.code : '';
    return {
      title: '挑战家族',
      path: '/pages/home/index?' +
        ('&invite=' + inviteCode) + ((channelInfo.channel != 0 && !util.isEmpty(channelInfo.channel) && channelInfo.channelTimes == 1) ? ('&channel=' + channelInfo.channel) : '') +
        ((channelInfo.channel != 0 && channelInfo.channelTimes == 1) ? ('&channelTimes=' + (parseInt(channelInfo.channelTimes) + 1)) : '')
    }
  },
})