<template>
  <div class="course-disscuss" @scroll="scrollHandler">
    <div class="v-title" style="margin: 10px 0 0px 0">公共讨论区</div>
    <div class="dis-input-box" v-if="disFormForDis">
      <el-input
        type="textarea"
        @input="disFormForDisChange"
        :rows="2"
        v-model="disFormForDis.content"
      >
      </el-input>
      <div class="send-button" @click="sendDis(disFormForDis)">发送</div>
    </div>
    <div class="dis-input-box" v-else>
      <el-input type="textarea" :rows="2" v-model="disFormForcourse.content">
      </el-input>
      <div class="send-button" @click="sendDis(false)">发送</div>
    </div>
    <div
      v-show="discussions.length"
      class="root-disscuss"
      v-for="dis in this.discussions"
      :key="dis.id"
    >
      <div class="disscuss-user-name">
        <img :src="dis?.avatar?.fileLinkTransfer()||'/logo.svg'" alt="" style="width:20px;height:20px;border-radius: 10px;overflow: hidden; object-fit: cover;margin-right: 5px;">
        {{ dis.creatorName }}</div>
      <div class="disscuss-content">
        {{ dis.content }}
      </div>
      <div class="disscuss-floor">
        <span class="disscuss-time">{{
          new Date(dis.updateTime).format("yyyy-MM-dd hh:mm")
        }}</span>
        <span
          class="reply-button"
          @click="callback(dis, dis)"
          >回复</span
        >
        <span
            class="reply-button"
            @click="deleteThisDis(dis.id)"
            v-if="dis.creator === $store.user.id"
            >删除</span
          >
      </div>
      <!-- v-show="index <= 1 || notFoldDis.includes(dis.id)" -->
      <div class="reply-disscuss" v-for="rep in dis.children" :key="rep.id">
        <div class="disscuss-user-name"><img :src="rep?.avatar?.fileLinkTransfer()||'/logo.svg'" alt="" style="width:20px;height:20px;border-radius: 10px;overflow: hidden; object-fit: cover;margin-right: 5px;" />{{ rep.creatorName }}</div>
        <div class="disscuss-content">
          <span style="color: #666">@{{ rep.replyUserName }}</span
          >：{{ rep.content }}
        </div>
        <div class="disscuss-floor">
          <span class="disscuss-time">{{
            new Date(rep.updateTime).format("yyyy-MM-dd hh:mm")
          }}</span>
          <span
            class="reply-button"
            @click="callback(rep, dis)"
            >回复</span
          >
          <span
            class="reply-button"
            @click="deleteThisDis(rep.id)"
            v-if="rep.creator === $store.user.id"
            >删除</span
          >
        </div>
      </div>
    </div>
    <div
      v-show="page_loading"
      style="color: #666; font-size: 14px; text-align: center; margin: 10px"
    >
      加载中...
    </div>
    <el-empty description="暂无评论" v-if="this.discussions <= 0"></el-empty>
  </div>
</template>

<script>
import { pagingDis, submitDisAPI, deleteDisAPI } from '@/api/system/resource'
export default {
  props: {
    disType: { default: 'resource' }
  },
  watch: {
    disType: {
      immediate: true,
      handler (nv) {
        // this.formatDis()
        this.discussions_list = []
        this.page_info = { ...this.page_info, records: nv }
        this.queryDatas()
      }
    }
  },
  data () {
    return {
      page_loading: false,
      discussions: [],
      notFoldDis: [],
      disFormForcourse: {
        recordId: null,
        replyId: null,
        replyUserId: null,
        content: '',
        creatorName: '',
        replyUserName: null,
        avatar: ''
      },
      page_info: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
        records: 'resource'
      },
      disFormForDis: undefined,
      deleteCount: 0,
      discussions_list: [],
      nowCallbackRootDis: {}
    }
  },
  // created () {
  //   this.formatDis()
  // },
  methods: {
    async deleteThisDis (id) {
      try {
        await deleteDisAPI(id)
      } catch (error) {
      }
      this.discussions_list = []
      this.page_info = {
        currentPage: 1,
        pageSize: 20,
        total: 0,
        records: 'resource'
      }
      this.queryDatas()
    },

    async queryDatas () {
      this.page_loading = true
      try {
        // eslint-disable-next-line no-var
        var { data } = await pagingDis(this.page_info)
      } catch (error) {
        this.page_info.currentPage = +this.page_info.currentPage - 1
        if (this.page_info.currentPage <= 1) {
          this.page_info.currentPage = 1
        }
        this.page_loading = false
      }
      this.page_info.currentPage = data.currentPage
      this.page_info.pageSize = data.pageSize
      this.page_info.total = data.total
      this.discussions_list = this.discussions_list.concat(data.data)
      this.formatDis()
      this.page_loading = false

      console.log(data)
    },
    scrollHandler (e) {
      const tar = e.target
      if (this.discussions_list.length >= this.page_info.total) {
        return
      }
      if (
        !this.page_loading &&
        tar.clientHeight + tar.scrollTop > tar.scrollHeight - 20
      ) {
        this.page_info.currentPage = +this.page_info.currentPage + 1
        this.queryDatas()
      }
    },
    formatDis () {
      this.discussions = this.discussions_list?.filter((dis) => {
        if (!dis.replyId) {
          dis.children = []
          return true
        }
        return false
      })
      this.discussions?.forEach((dis) => {
        const childs = this.discussions_list.filter((childDis) => {
          if (childDis.replyId === dis.id || childDis.rootDis === dis.id) {
            return true
          }
          return false
        })
        this.$set(dis, 'children', childs)
      })
    },
    callback (row, rootDis) {
      console.log(row.replyUserId)
      this.nowCallbackRootDis = rootDis
      this.disFormForDis = {
        type: this.page_info.records,
        replyId: row.id,
        replyUserId: row.creator,
        replyUserName: row.creatorName,
        creatorName: this.$store.user.name,
        creator: this.$store.user.id,
        rootDis: rootDis.id,
        content: `@${row.creatorName}：`,
        avatar: this.$store.user.photo
      }
    },
    async sendDis (row) {
      if (row) {
        row.content = row.content.replace(
          '@' + this.disFormForDis.replyUserName + '：',
          ''
        )
        const res = await submitDisAPI(row)
        row = {
          id: res.data.id,
          ...row,
          updateTime: res.data.updateTime
        }
        this.nowCallbackRootDis.children ||
          (this.nowCallbackRootDis.children = [])
        this.nowCallbackRootDis.children.unshift(row)
        this.disFormForDis = undefined
        this.deleteCount = 0
        this.$message.success('评论成功')
      } else {
        this.disFormForcourse.type = this.page_info.records
        this.disFormForcourse.avatar = this.$store.user.photo
        const res = await submitDisAPI(this.disFormForcourse)
        res.data.creatorName = this.$store.user.name
        this.discussions.unshift(res.data)
        this.$message.success('评论成功')
        this.disFormForcourse = {
          type: this.page_info.records,
          replyId: null,
          replyUserId: null,
          content: '',
          creatorName: '',
          avatar: '',
          replyUserName: null
        }
      }
    },
    disFormForDisChange (e) {
      const string = '@' + this.disFormForDis.replyUserName + '：'
      if (e.indexOf(string) === -1 && this.deleteCount < 1 && this.disFormForDis.replyUserName) {
        this.disFormForDis.content = string
        this.deleteCount++
      } else if (e.indexOf(string) === -1 && this.deleteCount >= 1) {
        this.disFormForDis = undefined
        this.nowCallbackRootDis = null
        this.disFormForcourse.content = ''
        this.deleteCount = 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.course-disscuss {
  height: 100%;
  width: 100%;
  padding: 0 15px 10px 15px;
  border-left: 1px solid #ccc;
  overflow: auto;
  .root-disscuss {
    padding: 10px 0;
  }
  .disscuss-user-name {
    font-size: 15px;
    font-weight: 600;
    color: #555;
    display: flex;
    align-items: center;
    padding-bottom: 5px;
  }
  .disscuss-content {
    font-size: 13px;
    line-height: 1.5;
    padding: 5px 0;
  }
  .reply-disscuss {
    padding: 10px 0 10px 20px;
  }
  .disscuss-reply-user {
    font-size: 13px;
  }
  .disscuss-floor {
    padding: 2px 0;
    font-size: 13px;
    color: rgb(173, 166, 166);

    .disscuss-time {
      margin-right: 20px;
    }
    > i {
      margin-left: 10px;
      font-size: 15px;
      cursor: pointer;
    }
    .red-icon {
      color: red;
    }
    .gray-icon {
      color: $--color-text-secondary;
    }
  }
  .reply-button {
    // color: black;
    margin-left: 15px;
    cursor: pointer;
  }
  .reply-button:hover {
    color: $--color-primary;
  }
  .open-fold {
    margin-left: 10px;
    cursor: pointer;
  }
  .dis-input-box {
    background-color: white;
    padding: 10px 0;
    display: flex;
    align-items: stretch;
    position: sticky;
    top: 0;
    .send-button {
      text-align: center;
      width: 50px;
      display: flex;
      color: white;
      border-radius: 0 4px 4px 0;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: $--color-primary;
    }
    .send-button:hover {
      border-color: #c0c4cc;
    }
    ::v-deep .el-textarea__inner {
      border-radius: 4px 0 0 4px !important;
      resize: none;
    }
  }
}
</style>
