<template>
  <div class="course-notes v-page" v-loading="loading">
    <div class="catalog-box">
      <h2 class="v-title">我的笔记</h2>
      <div style="width: 100%; padding: 10px 5px">
        <el-button
          style="width: 100%"
          class="add-note-button"
          size="small"
          round
          type="primary"
          @click="addNote"
          icon="el-icon-plus"
          >新建笔记</el-button
        >
      </div>
      <div class="note-list" v-infinite-scroll="getNewData" id="note-list">
        <div
          :class="`note-box ${
            checkNoteInfo.id == note.id ? 'now-check-box' : ''
          }`"
          v-for="(note, index) in noteList"
          :key="note.id"
          @click="checkNote(note, index)"
        >
          <div class="note-header">
            <span class="note-title">{{ note.title }}</span>
          </div>
          <div class="note-explain" v-html="note.explain">
          </div>

          <div class="note-manage">
            <span class="note-time">
              <i class="el-icon-time"></i>
              {{ new Date(note.updateTime).format("yyyy/MM/dd") }}</span
            >
            <div class="note-manage-button">
              <i class="el-icon-delete" @click.stop="deleteNote(note.id)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="right-content">
      <div class="content-header">
        <div class="note-title-input">
          <span style="width: 130px">笔记名称：</span
          ><el-input
            v-model="checkNoteInfo.title"
            @blur="saveTitleChange"
            maxlength="20"
            size="mini"
            show-word-limit
            :disabled="!checkNoteInfo.updateTime"
            placeholder="请输入笔记名称"
          ></el-input>
        </div>
        <div class="note-update-time" v-if="checkNoteInfo.updateTime">
          最后更新日期：{{
            new Date(checkNoteInfo.updateTime).format("yyyy.MM.dd")
          }}
        </div>
      </div>
      <RichTextEditor
        ref="RichTextEditor"
        :checkNoteInfo="checkNoteInfo"
        @change="editorChange"
      ></RichTextEditor>
    </div>
  </div>
</template>

<script>
import {
  addCourseNoteAPI,
  getCourseNotesListAPI,
  editorNoteAPI,
  deleteNoteAPI,
  getOneCourseNotesListAPI
} from '@/api/online-course/course-notes'
import RichTextEditor from '../components/rich-text-editor.vue'
import { deepClone } from '../utils'
import { dataReportMixin } from '@/utils/data-report'
export default {
  data () {
    return {
      noteList: [],
      checkNoteInfo: {},
      checkNoteInfoBase: {},
      loading: false,
      pageInfo: {
        page: 0,
        pageSize: 10,
        total: 0
      },
      submitTimeout: null,
      /*
       *  用于解决：课程在选中时，触发编辑器change事件，不需要submitTimeout去提交数据
       */
      isCheckFirst: true
    }
  },
  components: {
    RichTextEditor
  },
  created () {
    // this.getCourseNotesList()
  },

  methods: {
    async getCourseNotesList () {
      this.loading = true
      const { data } = await getCourseNotesListAPI(this.pageInfo)
      this.noteList = data[0]

      data[0][0]
        ? this.getOneNoteInfo(data[0][0], 0).then((res) => {
          this.pageInfo.total = data[1]
          this.loading = false
        })
        : (this.loading = false)
    },
    async addNote () {
      const { data } = await addCourseNoteAPI({
        title: '新增笔记',
        content: '',
        explain: '新增笔记'
      })
      this.noteList.push(data)
      this.checkNoteInfoBase = data
      this.checkNoteInfo = deepClone(data)
      this.checkNoteInfo.title = ''

      const listBox = document.getElementById('note-list')
      this.$nextTick(() => {
        listBox.scrollTo(0, listBox.scrollHeight)
      })
    },
    async getNewData (e) {
      this.pageInfo.page++
      if (this.pageInfo.page * this.pageInfo.pageSize <= this.noteList.length) {
        this.$message.warning('到底啦')
        return
      }
      if (this.pageInfo.page === 1) {
        this.getCourseNotesList()
        return
      }
      this.loading = true
      const { data } = await getCourseNotesListAPI(this.pageInfo)
      this.pageInfo.total = data[1]
      this.noteList.push(...data[0])
      this.loading = false
    },
    async deleteNote (id) {
      this.$confirm('此操作将永久删除该笔记, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.loading = true
          await deleteNoteAPI(id)
          this.pageInfo.page = 1
          await this.getCourseNotesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
    },
    // 选中节点
    async checkNote (note, index) {
      if (!this.checkNoteInfo.title.trim()) {
        return this.$message.warning('笔记名称不可为空')
      }
      this.loading = true
      let isChange = false
      const oldBase = this.checkNoteInfoBase
      const newNote = this.checkNoteInfo
      // 清除上篇文章的防抖函数 以免再次提交
      if (this.submitTimeout) {
        clearTimeout(this.submitTimeout)
        this.submitTimeout = null
      }
      // 遍历查找数据是否有更改
      for (const k in oldBase) {
        if (k !== 'id' && oldBase[k] !== newNote[k]) {
          isChange = true
        }
      }
      // 如果有更改，则直接向服务器保存数据，然后再切换
      if (isChange) {
        const { data } = await this.submitValue()
        const index = this.noteList.findIndex((item) => {
          if (item.id === data.id) {
            return true
          }
          return false
        })
        this.noteList[index] = data
      }
      this.getOneNoteInfo(note, index).then(() => {
        this.loading = false
      })
    },

    editorChange (value) {
      this.checkNoteInfo.content = value
      this.antiShakeSubmit()
    },
    async saveTitleChange () {
      if (!this.checkNoteInfo.title.trim()) {
        this.checkNoteInfo.title = this.checkNoteInfoBase.title
        return
      }
      if (this.checkNoteInfo.title !== this.checkNoteInfoBase.title) {
        const { data } = await editorNoteAPI({
          id: this.checkNoteInfo.id,
          title: this.checkNoteInfo.title
        })
        this.checkNoteInfoBase.title = data.title
        this.checkNoteInfoBase.updateTime = data.updateTime
        this.checkNoteInfo.updateTime = data.updateTime
      }
    },
    // 防抖提交
    antiShakeSubmit () {
      if (this.submitTimeout) {
        clearTimeout(this.submitTimeout)
        this.submitTimeout = null
      }
      this.submitTimeout = setTimeout(async () => {
        const { data } = await this.submitValue()
        const index = this.noteList.findIndex((item) => {
          if (item.id === data.id) {
            return true
          }
          return false
        })
        this.noteList[index] = data
        // this.$set(this.noteList, index, data)
        clearTimeout(this.submitTimeout)
        this.submitTimeout = null
      }, 200)
    },
    async  getOneNoteInfo (note, index) {
      this.$refs.RichTextEditor.editor.destroy()
      const { data } = await getOneCourseNotesListAPI(note.id)

      this.noteList[index] = data
      this.checkNoteInfoBase = data
      this.checkNoteInfo = deepClone(data)
      this.$refs.RichTextEditor.seteditor()
      return data
    },
    async submitValue () {
      return await editorNoteAPI({ id: this.checkNoteInfo.id, explain: this.checkNoteInfo.explain, title: this.checkNoteInfo.title, content: this.checkNoteInfo.content })
    }
  },

  mixins: [
    /**
     * 数据上报
     */
    dataReportMixin('CLASS_NOTE')
  ]
}
</script>

<style lang="scss" scoped>
.course-notes {
  height: 100%;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  overflow-y: auto;
  // ::v-deep .el-input__count-inner {
  //   font-weight: 300;
  // }
  .catalog-box {
    width: 250px;
    // padding-right: 10px;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #f0f1f3;
    height: 100%;
    .note-list {
      padding: 5px;
      flex: 1;
      overflow: auto;
    }

    .note-box:hover {
      background: $--background-color-base;
    }
    .note-box:first-child {
      margin-top: 0;
    }
    .note-box:last-child {
      margin-bottom: 0;
    }
    .note-box {
      height: 100px;
      width: 230px;
      border: 1px solid $--color-primary;
      margin: 10px 0;
      border-radius: 4px;
      padding: 5px;
      cursor: pointer;
      .note-header {
        width: 100%;
        padding-bottom: 5px;
      }
      .note-title {
        width: 100%;
        display: inline-block;
        font-weight: 700;
        color: $--color-primary;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .now-check-box {
      // border: 3px solid $--color-primary;
      box-shadow: 0px 0px 2px  2px $--color-primary;
    }
    .note-explain {
      width: 100%;
      height: 53px;
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
      letter-spacing: 2px;
    }
    .note-manage {
      padding-top: 2px;
      display: flex;
      width: 100%;
      font-size: 12px;
      justify-content: space-between;
      .note-time {
        color: #c0c0c0;
      }
      .note-manage-button {
        padding-right: 5px;
        cursor: pointer;
        color: red;
      }
    }
    .add-note-button {
      margin-right: 10px;
    }
  }
  .right-content {
    padding: 10px;
    height: 100%;
    position: relative;
    flex: 1;
    display: flex;
    flex-direction: column;
    z-index: 1;
    .content-header {
      display: flex;
      height: 50px;
      justify-content: space-between;
      margin-bottom: 10px;
      align-items: center;
      flex-wrap: wrap;
    }
    .note-update-time {
      font-size: 12px;
      color: $--color-primary;
    }
    .note-title-input {
      align-items: center;
      font-size: 15px;
      font-weight: 700;
      display: flex;
    }
    ::v-deep .el-input__inner {
      padding-right: 50px;
    }
  }
}
</style>
