import {
  getComment,
  postReply,
  ReplyComment,
  likeReply,
  delPost,
  getLikeNotes,
  getLikeNote,
  getCommentNote
} from '~/api/video'
import {
  setFans
} from '~/api/user'
import reachBottom from '~/mixins/reachBottom'
Component({
  behaviors: [reachBottom],
  properties: {
    // 是否在tabbar页面使用，是的话就给个padding
    tabBarPadding: {
      type: Boolean,
      value: false
    }
  },
  data: {
    show: false,
    quickShow: true,
    type: 'comment',
    commentId: '',
    firstData: {},
    list: [],
    count: {},
    detailDesc: '',
    onceId: '',
    postId: '',
    postIndex: '',
    ifGetFocus: false,
    replyType: 'works', // 回复类型，works是回复作品，comment是回复评论
    animation: {},
    author: '',
    uid: wx.getStorageSync('uid')
  },
  methods: {
    async open(author, columnId, type = 'comment', onceId) {
      // 背景遮罩层
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: "linear",
        delay: 0
      })
      animation.translateY(1000).step()
      this.setData({
        animationData: animation.export(),
        columnId,
        type,
        onceId,
        author,
        show: true,
        uid: wx.getStorageSync('uid')
      })
      setTimeout(() => {
        animation.translateY(0).step()
        this.setData({
          animationData: animation.export()
        })
      }, 100)
      if (onceId) {
        this.topping(onceId)
      } else {
        this.resetData()
      }
      let r1 = await getComment({
        columnId: this.data.columnId,
        pageSize: 1
      })
      let r2 = await getLikeNotes({
        userReadId: this.data.columnId,
        pageSize: 1
      })
      this.setData({
        count: {
          commentNum: r1.totalSize,
          likeNum: r2.totalSize
        }
      })
    },
    changeType({
      currentTarget
    }) {
      let type = currentTarget.dataset.type
      this.setData({
        type,
        firstData: {},
        onceId: ''
      })
      this.resetData()
    },
    close() {
      this.setData({
        show: false,
        quickShow: true,
        commentId: '',
        detailDesc: '',
        replyType: 'works',
        postId: null,
        postIndex: null,
        ifGetFocus: false,
        firstData: {},
        onceId: ''
      })
    },
    quickClose() {
      this.setData({
        quickShow: false
      })
    },
    loadMore() {
      this.getData((data) => {
        return new Promise(async (reslove) => {
          let res
          if (this.data.type == 'comment') {
            res = await getComment(data)
            this.setData({
              'count.commentNum': res.totalSize
            })
          } else if (this.data.type == 'like') {
            res = await getLikeNotes(data)
            this.setData({
              'count.likeNum': res.totalSize
            })
          }
          if (this.data.firstData.id) {
            res.list = res.list.filter(item => {
              return item.id != this.data.firstData.id
            })
            res.list.unshift(this.data.firstData)
          }
          reslove(res)
        })
      }, this.data.type == 'comment' ? {
        columnId: this.data.columnId,
        isUpdateRead: !this.data.onceId
      } : {
        userReadId: this.data.columnId,
        isUpdateRead: !this.data.onceId
      })
    },
    bindKeyInput(e) {
      this.setData({
        detailDesc: e.detail.value
      })
    },
    async topping(id) {
      let res
      if (this.data.type == 'like') {
        res = await getLikeNote(id)
      } else {
        res = await getCommentNote(id)
      }
      this.setData({
        firstData: res
      })
      this.loadMore()
    },
    async quickRemark({
      currentTarget
    }) {
      let data = {
        columnId: this.data.columnId,
        detailDesc: currentTarget.dataset.remark
      }
      await postReply(data)
      // 评论数+1
      this.triggerEvent('addCommentNum', this.data.columnId)
      this.resetData()
    },
    // 评论作品
    async sendReply() {
      if (!this.data.detailDesc.trim()) {
        return
      }
      if (this.data.replyType == 'works') {
        let data = {
          columnId: this.data.columnId,
          detailDesc: this.data.detailDesc,
        }
        await postReply(data)
        // 评论数+1
        this.triggerEvent('addCommentNum', this.data.columnId)
      } else {
        let data = {
          postsId: this.data.postId,
          content: this.data.detailDesc,
        }
        await ReplyComment(data)
      }
      this.setData({
        detailDesc: '',
        replyType: 'works'
      })
      this.resetData()
    },
    async ReplyComment({
      currentTarget
    }) {
      let postId = currentTarget.dataset.id
      let index = currentTarget.dataset.index
      this.setData({
        postId: postId,
        replyType: 'comment',
        ifGetFocus: true,
        postIndex: index
      })
    },
    cancelId() {
      this.setData({
        replyType: 'works',
        postId: null,
        postIndex: null,
        ifGetFocus: false,
      })
    },
    // 评论点赞
    async setLike({
      currentTarget
    }) {
      let postId = currentTarget.dataset.id
      let index = currentTarget.dataset.index
      let res = await likeReply(postId)
      const str = `list[${index}].likeCount`;
      const strImg = `list[${index}].isLike`;
      this.setData({
        [str]: res,
        [strImg]: true
      })
    },
    jumpUserInfo({
      currentTarget
    }) {
      let pages = getCurrentPages(); // 获取当前页面栈
      let len = pages.length; // 获取当前页面栈的长度
      if (len > 4) {
        wx.redirectTo({
          url: `/pages/personal/index?uid=${currentTarget.dataset.uid}&type=user`,
        })
      } else {
        wx.navigateTo({
          url: `/pages/personal/index?uid=${currentTarget.dataset.uid}&type=user`,
        })
      }
    },
    onLongPress({
      currentTarget
    }) {
      if (this.data.uid != this.data.author) {
        return
      }
      let {
        id,
        type
      } = currentTarget.dataset
      wx.showActionSheet({
        itemList: ['删除评论'],
        success: async () => {
          await delPost({
            id,
            type
          })
          if (type == '1') {
            let index = this.data.list.findIndex(item => {
              return item.id == id
            })
            this.data.list.splice(index, 1);
            this.setData({
              'count.commentNum': --this.data.count.commentNum,
              list: this.data.list
            })
          } else {
            let {
              parent
            } = currentTarget.dataset
            let index = this.data.list.findIndex(item => {
              return item.id == parent
            })
            let index2 = this.data.list[index].replyVOList.findIndex(item2 => {
              return item2.id == id
            })
            this.data.list[index].replyVOList.splice(index2, 1);
            this.setData({
              list: this.data.list
            })
          }
        },
      })
    },
    // 关注
    async setFans({
      currentTarget
    }) {
      let user = currentTarget.dataset.user
      if (user.isFans) {
        return
      }
      await setFans({
        uid: user.user.uid
      })
      let listCopy = JSON.parse(JSON.stringify(this.data.list));
      listCopy.forEach(item => {
        if (item.user.uid == user.user.uid) {
          item.isFans = true;
        }
      });
      this.setData({
        list: listCopy
      });
      wx.showToast({
        title: '已关注',
        icon: 'none'
      });
    },
  }
})