<template>
  <div class="course-disscuss">
    <div class="dis-input-box" v-if="disFormForDis">
      <el-input
        type="textarea"
        @input="disFormForDisChange"
        :rows="2"
        v-model="disFormForDis.content"
      >
        <template slot="append">.com</template>
      </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">
        <template slot="append">.com</template>
      </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">{{ dis.userInfo?.name }}</div>
      <div class="disscuss-content">
        {{ dis.userInfo?.name }}评论：{{ dis.content }}
      </div>
      <div class="disscuss-floor">
        <span class="disscuss-time">{{
          new Date(dis.updateTime).format("yyyy-MM-dd hh:mm")
        }}</span>
        <i
          @click="kudosChange(dis, dis.id, 1)"
          :class="`i-zan ${
            dis.mykudos && dis.mykudos.type ? 'red-icon' : 'gray-icon'
          }`"
          >{{ dis.allkudos?.length }}</i
        >
        <i
          @click="kudosChange(dis, dis.id, 0)"
          :class="`i-cai ${
            dis.mykudos && !dis.mykudos.type ? 'red-icon' : 'gray-icon'
          }`"
          >{{ dis.allunkudos?.length }}</i
        >
        <span class="reply-button" @click="callback(dis, dis)">回复</span>
      </div>
      <div
        class="reply-disscuss"
        v-show="index <= 1 || notFoldDis.includes(dis.id)"
        v-for="(rep, index) in dis.children"
        :key="rep.id"
      >
        <div class="disscuss-user-name">{{ rep.userInfo?.name }}</div>
        <div class="disscuss-content">
          {{ rep.userInfo?.name }}对{{ rep.replyUserInfo?.name }}的评论：{{
            rep.content
          }}
        </div>
        <div class="disscuss-floor">
          <span class="disscuss-time">{{
            new Date(rep.updateTime).format("yyyy-MM-dd hh:mm")
          }}</span>
          <i
            @click="kudosChange(rep, rep.id, 1)"
            :class="`i-zan ${
              rep.mykudos && rep.mykudos.type ? 'red-icon' : 'gray-icon'
            }`"
            >{{ rep.allkudos?.length }}</i
          >
          <i
            @click="kudosChange(rep, rep.id, 0)"
            :class="`i-cai ${
              rep.mykudos && !rep.mykudos.type ? 'red-icon' : 'gray-icon'
            }`"
            >{{ rep.allunkudos?.length }}</i
          >
          <span class="reply-button" @click="callback(rep, dis)">回复</span>
        </div>
      </div>
      <div
        class="open-fold"
        v-if="dis.children?.length > 3 && !notFoldDis.includes(dis.id)"
        @click="notFoldDis.push(dis.id)"
      >
        共{{ dis.children?.length }}条回复，点击查看
        <i class="el-icon-arrow-down"></i>
      </div>
      <div
        v-if="notFoldDis.includes(dis.id)"
        @click="
          () => {
            notFoldDis = notFoldDis.filter((i) => i !== dis.id);
          }
        "
        class="open-fold"
      >
        收起回复 <i class="el-icon-arrow-up"></i>
      </div>
    </div>
    <el-empty description="暂无评论" v-if=" this.discussions<=0"></el-empty>
  </div>
</template>

<script>
import { submitDisAPI, submitDisKudosAPI } from '@/api/online-course/my-course'
export default {
  props: {
    nowCheckCourse: { default: () => {} }
  },
  watch: {
    nowCheckCourse: {
      deep: true,
      immediate: true,
      handler (nv) {
        this.formatDis()
      }
    }
  },
  data () {
    return {
      discussions: [],
      notFoldDis: [],
      disFormForcourse: {
        recordId: null,
        replyId: null,
        replyUserId: null,
        content: '',
        replyUserInfo: null
      },
      disFormForDis: undefined,
      deleteCount: 0,
      nowCallbackRootDis: {}
    }
  },
  // created () {
  //   this.formatDis()
  // },
  methods: {
    formatDis () {
      this.nowCheckCourse?.discussion?.forEach((dis) => {
        const allkudos = []
        const allunkudos = []
        dis.kudos.forEach((kudos) => {
          if (kudos.creator === this.$store.user.id) {
            dis.mykudos = kudos
          }
          if (kudos.type) {
            allkudos.push(kudos)
          } else {
            allunkudos.push(allunkudos)
          }
        })
        dis.allkudos = allkudos
        dis.allunkudos = allunkudos
      })
      this.discussions = this.nowCheckCourse.discussion?.filter((dis) => {
        if (!dis.replyId) {
          dis.children = []
          return true
        }
        return false
      })
      this.discussions?.forEach((dis) => {
        const childs = this.nowCheckCourse.discussion.filter((childDis) => {
          if (childDis.replyId === dis.id || childDis.rootDis === dis.id) {
            return true
          }
          return false
        })
        this.$set(dis, 'children', childs)
      })
    },
    callback (row, rootDis) {
      this.nowCallbackRootDis = rootDis
      this.disFormForDis = {
        recordId: this.nowCheckCourse.courseInfo.id,
        replyId: row.id,
        replyUserId: row.userInfo.id,
        replyUserInfo: row.userInfo,
        userInfo: this.$store.user,
        rootDis: rootDis.id,
        content: `@${row.userInfo.name}：`
      }
    },
    async sendDis (row) {
      if (row) {
        row.content = row.content.replace(
          '@' + this.disFormForDis.replyUserInfo.name + '：',
          ''
        )
        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.$set(
        //   this.nowCallbackRootDis,
        //   'children',
        //   this.nowCallbackRootDis.children
        // )
        this.disFormForDis = undefined
        this.deleteCount = 0
        this.$message.success('评论成功')
        // this.$forceUpdate()
      } else {
        this.disFormForcourse.recordId = this.nowCheckCourse.courseInfo.id
        const res = await submitDisAPI(this.disFormForcourse)
        res.data.userInfo = this.$store.user
        this.discussions.unshift(res.data)
        this.$message.success('评论成功')
        this.disFormForcourse = {
          recordId: null,
          replyId: null,
          replyUserId: null,
          content: '',
          replyUserInfo: null
        }
      }
    },
    disFormForDisChange (e) {
      const string = '@' + this.disFormForDis.replyUserInfo.name + '：'
      if (e.indexOf(string) === -1 && this.deleteCount <= 1) {
        this.disFormForDis.content = string
        this.deleteCount++
      } else if (e.indexOf(string) === -1 && this.deleteCount > 1) {
        this.disFormForDis.content = ''
        this.disFormForcourse.content = ''
        this.deleteCount = 0
      }
    },
    async kudosChange (dis, id, type) {
      const data = {
        id: dis.mykudos ? dis.mykudos.id : undefined,
        disId: id,
        recordId: this.nowCheckCourse.courseInfo.id
      }

      if (dis.mykudos?.type !== type) {
        data.type = type
      } else {
        data.delFlag = 1
      }

      const res = await submitDisKudosAPI(data)
      dis.allkudos = []
      dis.allunkudos = []
      const allkudos = []
      const allunkudos = []
      let mykudos

      this.$forceUpdate()
      res.data.forEach((kudos) => {
        if (kudos.creator === this.$store.user.id) {
          mykudos = kudos
        }
        kudos.type ? allkudos.push(kudos) : allunkudos.push(kudos)
      })
      dis.mykudos = mykudos
      dis.allkudos = allkudos
      dis.allunkudos = allunkudos
    }
  }
}
</script>

<style lang="scss" scoped>
.course-disscuss {
  margin: 10px 0;
  max-height: 400px;
  width: 100%;
  padding: 0 15px 10px 15px;
  border: 1px solid #ccc;
  overflow: auto;
  .root-disscuss {
    padding: 10px 0;
  }
  .disscuss-user-name {
    font-size: 16px;
    font-weight: 700;
    padding-bottom: 5px;
  }
  .disscuss-content {
    font-size: 15px;
    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>
