// pages/activity/index/index.js
import httpRequestApi from '../../../utils/APIClient';
import {
  formatDate
} from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityReadData: [],
    selectInd: 0,
    selectBg: ['../../../static/activity/right.png', '../../../static/activity/left.png'],
    activityMyReadData: [],
    nextMargin: '400rpx', // 视频下边距
    isSwiper: false,
    noMoreWork: false,
    hotAmountTopData: [],
    sortImg: ['../../../static/activity/1.png', '../../../static/activity/2.png', '../../../static/activity/3.png'],
    grades: '',
    gradeObj: {
      "PRIMARY_FIRST_GRADE": "一年级",
      "PRIMARY_SECOND_GRADE": "二年级",
      "PRIMARY_THREE_GRADE": "三年级",
      "PRIMARY_SENIOR_GRADE": "四年级"
    },
    myHotAmountData: {},
    commentShow: false,
    commentList: [],
    commentNum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 接口调用
    const grade = wx.getStorageSync('grade')
    this.setData({
      grades: this.data.gradeObj[grade]
    })
    httpRequestApi.getActivityRead(grade).success(res => {
      if (res.data.code === 200) {
        const activityReadData = [...res.data.data]
        this.setData({
          activityReadData
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    /**
     * 获取排名信息
     */
    httpRequestApi.getHotAmountTop().success(res => {
      if (res.data.code === 200) {
        const hotAmountTopData = [...res.data.data]
        this.setData({
          hotAmountTopData
        })
      }
    })
    /**
     * 获取我的排名信息
     */
    httpRequestApi.getMyHotAmount().success(res => {
      if (res.data.code === 200) {
        // console.log(res)
        const myHotAmountData = res.data.data
        this.setData({
          myHotAmountData
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 下拉
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    /**
     * 获取排名信息
     */
    httpRequestApi.getHotAmountTop().success(res => {
      if (res.data.code === 200) {
        const hotAmountTopData = [...res.data.data]
        this.setData({
          hotAmountTopData
        })
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })
    /**
     * 获取我的排名信息
     */
    httpRequestApi.getMyHotAmount().success(res => {
      if (res.data.code === 200) {
        // console.log(res)
        const myHotAmountData = res.data.data
        this.setData({
          myHotAmountData
        })
      }
    })
  },
  /**
   *
   * @param {*} res
   * 分享
   */
  onShareAppMessage: function (res) {
    console.log('onShareAppMessage>>>>>>>>>>>>')
    if (res.from === 'button') {
      return {
        title: '请欣赏我的课文朗读作品，点赞+评论。',
        path: `/pages/index/index?readId=${this.data.shareId}&activity=true`,
        imageUrl: this.data.shareImg
      }
    } else {
      return {
        title: '课文朗读，从未如此有趣。',
        path: '/pages/index/index',
      }
    }
  },
  /**
   * 活动页点击切换
   */
  tabSelect({
    currentTarget
  }) {
    const selectInd = currentTarget.dataset.index * 1
    if (selectInd === this.data.selectInd) return;
    this.setData({
      selectInd
    });
    if (selectInd === 1) {
      this.getMyRead();
    }
  },
  /**
   * 去比赛
   */
  goToReading({
    currentTarget
  }) {
    const id = currentTarget.dataset.id
    wx.navigateTo({
      url: `../../reading/reading?id=${id}`
    });
  },
  /**
   * 修改list列表
   * @param {*} 列表
   */
  formatWorksList(list) {
    this.data.activityMyReadData = [];
    list.forEach((item) => {
      const temp = {};
      temp.title = item.userRead.title;
      temp.summary = item.userRead.summary;
      temp.img = item.userRead.iconImg;
      temp.plays = item.userRead.playAmount ? item.userRead.playAmount : 0;
      temp.likes = item.userRead.likeAmount ? item.userRead.likeAmount : 0;
      temp.commentAmount = item.userRead.commentAmount ? item.userRead.commentAmount : 0;
      temp.shareAmount = item.userRead.shareAmount;
      temp.favoritesAmount = item.userRead.favoritesAmount;
      temp.classId = item.userRead.exampleId ? item.userRead.exampleId : 1605097720036046;
      temp.time = formatDate(item.userRead.gmtCreated, 3);
      temp.avatar = item.user.avatar;
      temp.profession = item.user.profession;
      temp.uid = item.user.uid;
      temp.markPath = item.userRead.markPath ? item.userRead.markPath : item.userRead.videoPath;
      temp.url = item.userRead.videoPath ? item.userRead.videoPath : item.userRead.originVideo;
      temp.id = item.userRead.id;
      temp.type = item.userRead.type;
      temp.nickName = item.user.wechatName;
      temp.isLike = item.isLike;
      temp.isFavorite = item.isFavorites;
      temp.showMyBtn = true;
      temp.nickName = item.user.wechatName;
      temp.status = item.userRead.status;
      temp.ifCheck = item.userRead.status === 'CHECK' ? true : false;
      temp.coverImg = item.userRead.coverImg;
      temp.grade = item.userRead.grade
      temp.isFans = true;
      temp.videoShow = false;
      temp.shareImg = item.userRead.shareImg;
      temp.activity = true;
      temp.noReading = true;
      this.data.activityMyReadData.push(temp);
      // tempList.push(temp);
    });
    // if (!notSet) {
    this.setData({
      activityMyReadData: this.data.activityMyReadData
    })
    // }

  },
  /**
   * 获取我的朗读
   */
  getMyRead() {
    httpRequestApi.getActivityMyRead().success(res => {
      if (res.data.code === 200) {
        const recommendRes = res.data.data;
        this.formatWorksList(recommendRes);
      }
    })
  },
  /**
   * 点击删除按钮
   */
  delHideMyWork() {
    this.getMyRead()
  },
  /**
   * 点击收藏按钮
   */
  collectTap(e) {
    const index = e.detail.index;
    let str = `activityMyReadData[${index}].isFavorite`;
    let str2 = `activityMyReadData[${index}].favoritesAmount`;
    let favoritesAmount = e.detail.isCollect ? this.data.activityMyReadData[index].favoritesAmount + 1 : this.data.activityMyReadData[index].favoritesAmount - 1
    this.setData({
      [str]: e.detail.isCollect,
      [str2]: favoritesAmount
    })
  },
  /**
   * 点赞执行事件
   */
  likeTap(e) {
    const index = e.detail.index;
    let likeStr = `activityMyReadData[${index}].isLike`;
    let likeNumStr = `activityMyReadData[${index}].likes`;
    this.setData({
      [likeStr]: true,
      [likeNumStr]: this.data.activityMyReadData[index].likes + 1
    })
    // this.flowerAnimationHandler()
  },
  /**
   * 打开评论
   */
  openComment: function (e) {
    //
    this.setData({
      commentShow: !this.data.commentShow,
      commentId: e.detail.activeId,
      commentIndex: e.detail.activeIndex
    });
  },
  /**
   * 评论区点击
   */
  commentTap: function (e) {
    console.log('点击评论区', e)
    if (e.target.dataset.type === 'blank') {
      if (this.data.commentShow && this.data.commentId) {
        httpRequestApi.getClassDetail(this.data.commentId).success(res => {
          console.log('评论回显', res.data.data.userRead.commentAmount)
          let str = `activityMyReadData[${this.data.commentIndex}].commentAmount`;
          this.setData({
            [str]: res.data.data.userRead.commentAmount
          })
        })
      }
      this.setData({
        commentShow: false
      })
    }
  },
  /**
   * 获取评论信息
   */
  getReply: function (columnId) {
    // let columnId = this.data.id;
    console.log(123123123, columnId)
    // let pageNo = this.data.pageNo;
    // let pageSize = this.data.pageSize;
    httpRequestApi.getReply(this.uid, columnId, 1, 10).success((res) => {
      console.log('reply', res)
      const commentList = res.data.data.list;
      const commentNum = res.data.data.totalSize;
      console.log('评论数量', commentNum)
      commentList.forEach((item) => {
        const temp = {};
        temp.nickName = item.user.wechatName;
        temp.avatar = item.user.avatar;
        temp.uid = item.user.uid;
        temp.text = item.detailDesc;
        temp.id = item.id;
        temp.replyCount = item.replyCount;
        temp.time = formatDate(item.gmtCreated, 3);
        temp.likes = item.postsAttributeInfo.favors || 0;
        temp.isLike = item.isLike;
        temp.replyList = item.replyVOList;
        this.data.commentList.push(temp);
      });
      this.setData({
        commentList: this.data.commentList,
        commentNum: commentNum
      })
    });
  },
  /**
   * 发布回复
   */
  sendReply: function (e) {
    console.log('triger', e.detail.content);
    let data = {
      columnId: this.data.commentId,
      colunmNames: 'what',
      detailDesc: e.detail.content,
      // productId: this.data.productId
    }
    httpRequestApi.postReply(this.uid, data).success(res => {
      console.log(res)
      this.setData({
        pageNo: 1,
        commentList: []
      }, () => {
        this.getReply(this.data.commentId);
      })
    });
  },
  /**
   * 点击分享
   */
  openShare(e) {
    this.setData({
      shareTitle: e.detail.currentTarget.dataset.title,
      shareId: e.detail.currentTarget.dataset.id,
      shareImg: e.detail.currentTarget.dataset.shareimg,
      goToShare: true
    })
  },
  /**
   * 点击活动
   */
  rule() {
    wx.navigateTo({
      url: `../rule/rule`
    });
  },
  /**
   * 点击攻略
   */
  strategy() {
    wx.navigateTo({
      url: `../strategy/strategy`
    });
  },
  /**
   * 点击头像
   */
  headTap(e) {
    if (!wx.getStorageSync('user').wechatName) {
      wx.navigateTo({
        url: `../../pages/login/login`
      });
      return;
    }
    let uid = e.target.dataset.uid ? e.target.dataset.uid : e.currentTarget.dataset.uid;
    // this.trigger(e, 'headTap')
    console.log('点击头像', e)
    wx.navigateTo({
      url: `../../pages/myworks/myworks?uid=${uid}`,
      fail: (err) => {
        console.log('跳转错误', err)
        wx.navigateTo({
          url: `../../../pages/myworks/myworks?uid=${uid}`
        });
      }
    });

  },
  /**
   * 点击关注
   */
  follow(e) {
    const followUid = e.target.dataset.uid ? e.target.dataset.uid : e.currentTarget.dataset.uid;
    const uid = wx.getStorageSync('uid');
    httpRequestApi.followUser(uid, followUid).success((res) => {
      // this.setData({
      //   isFans: true
      // })
      wx.showToast({
        title: '关注啦',
        icon: 'success',
        duration: 1000
      })
    });
    httpRequestApi.getHotAmountTop().success(res => {
      if (res.data.code === 200) {
        const hotAmountTopData = [...res.data.data]
        this.setData({
          hotAmountTopData
        })
      }
    })
  }
})