<!--  -->
<template>
  <div class="FAQ-info" v-loading="mainLoading">
    <div class="issues-info-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="110px"
        class="demo-ruleForm"
      >
        <el-form-item label="问题名称" prop="title">
          <el-input
            maxlength="20"
            show-word-limit
            :disabled="disabled"
            v-model="ruleForm.title"
            placeholder="请输入问题名称"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="问题描述"
          style="padding-right: 25px"
          prop="content"
        >
          <RichTextEditor
            ref="RichTextEditor"
            :checkNoteInfo="ruleForm"
            :disabled="disabled ? true : false"
            @change="explainChnage"
          ></RichTextEditor>
        </el-form-item>
        <el-form-item label="选择解答人" prop="content" v-if="!isAnswerPage">
          <el-tag
            v-for="(answer, index) in nowSelectUser"
            :key="index"
            type="success"
            class="user-tag"
            :closable="!disabled"
            @close="deleteUser(answer, index)"
            >{{ answer.name }}</el-tag
          >
          <el-button
            v-if="!disabled"
            @click="addAnswerPersion"
            size="mini"
            icon="el-icon-plus"
            class="add-answe-persion-button"
          >
            选择解答人
          </el-button>
        </el-form-item>
        <el-form-item label="问题解答" v-if="isAnswerPage">
          <el-input
            style="height: 100px; padding-right: 25px"
            type="textarea"
            :rows="2"
            placeholder="请输入解答内容"
            v-model="answerContent"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="send-issues-button">
        <el-button type="primary" round @click="saveAnswer" v-if="isAnswerPage">
          保存答案
        </el-button>
        <el-button
          type="danger"
          round
          @click="$emit('cancelAnswer')"
          v-if="isAnswerPage"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          round
          @click="saveDataChange"
          v-if="!isAnswerPage"
        >
          {{ nowCheckInfo?.id ? "重新发送" : "发送问题" }}
        </el-button>
        <el-button
          type="danger"
          round
          @click="$emit('cancelAdd')"
          v-if="!isAnswerPage"
        >
          关闭
        </el-button>
      </div>
    </div>
    <h2
      class="v-title"
      v-if="ruleForm.answer && ruleForm.answer.length > 0"
      style="margin-left: 15px"
    >
      问题解答详情
    </h2>

    <div
      class="issues-answer-box"
      v-if="ruleForm.answer && ruleForm.answer.length > 0"
    >
      <div
        class="answer-info-box"
        v-for="(anser, index) in ruleForm.answer"
        :key="index"
      >
        <span class="answer-info-title">解答{{ index + 1 }}：</span>
        <div class="answer-info">
          <div class="answer-info-text">
            <strong class="answer-info-username"
              >/{{ anser.answer_person.name }}/： </strong
            >{{ anser.content }}
          </div>
          <div class="reply-time">
            最后解答时间：{{ new Date(anser.updateTime).format("yyyy-MM-dd") }}
          </div>
        </div>
      </div>
    </div>
    <el-empty v-else-if="!isAnswerPage" description="当前暂无解答人"></el-empty>
    <DialogSelf
      title="选择解答人"
      @onCancel="isShowAddPersion = false"
      @onConfirm="isShowAddPersion = false"
      :visible="isShowAddPersion"
      :actionBarOption="{ noCencel: true }"
    >
      <el-tabs
        style="width: 400px"
        v-model="activeName"
        type="card"
        @tab-click="handleClick"
        v-loading="dialogLoading"
      >
        <el-tab-pane label="老师" name="teacher" style="width: 100%">
          <div class="select-table-box">
            <searchInput
              v-model="searchValue"
              @query="getSearchList"
            ></searchInput>
            <el-table :border="false" :data="searchList" height="350">
              <el-table-column
                prop="name"
                label="名称"
                width="200"
                align="center"
              >
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template slot-scope="props">
                  <el-button
                    v-if="props.row.isSelect"
                    type="text"
                    style="color: red"
                    icon="el-icon-error"
                    @click="changeUserState(props)"
                    >取消邀请</el-button
                  >
                  <el-button
                    v-else
                    type="text"
                    icon="el-icon-s-custom"
                    @click="changeUserState(props)"
                    >邀请解答</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="同学" name="student" style="width: 100%">
          <div class="select-table-box">
            <searchInput
              v-model="searchValue"
              @query="getSearchList"
            ></searchInput>
            <el-table :data="searchList" height="350">
              <el-table-column
                prop="name"
                label="名称"
                width="200"
                align="center"
              >
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template slot-scope="props">
                  <el-button
                    v-if="props.row.isSelect"
                    type="text"
                    style="color: red"
                    icon="el-icon-error"
                    @click="changeUserState(props)"
                    >取消邀请</el-button
                  >
                  <el-button
                    v-else
                    type="text"
                    icon="el-icon-s-custom"
                    @click="changeUserState(props)"
                    >邀请解答</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </DialogSelf>
  </div>
</template>
<script>
import DialogSelf from '@/components/layout/DialogLayout.vue'
import { findAllTeacherApi } from '@/api/system/user'
import {
  createIssuesAPI,
  editorIssuesAPI,
  getMyTeacherStudentAPI,
  answerAPI
} from '@/api/online-course/online-FAQ'
import searchInput from '@/components/widget/QueryInput.vue'
import { deepClone } from '../utils'
import RichTextEditor from '../components/rich-text-editor.vue'
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
export default {
  props: {
    nowCheckInfo: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isAnswerPage: {
      type: Boolean,
      default: false
    }
  },
  // import引入的组件需要注入到对象中才能使用
  components: { DialogSelf, searchInput, RichTextEditor },
  data () {
    // 这里存放数据
    return {
      rules: {
        title: [{ required: true, message: '请输入问题名称', trigger: 'blur' }],
        region: [
          { required: true, message: '请输入问题详情', trigger: 'change' }
        ]
      },
      ruleForm: {},
      isShowAddPersion: false,
      teachList: [],
      studentList: [],
      searchList: [],
      activeName: 'teacher',
      mainLoading: false,
      dialogLoading: [],
      searchValue: '',
      nowSelectUser: [],
      baseSelectUser: [],
      delOnceHaveUser: [],
      answerContent: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    nowCheckInfo () {
      if (this.isAnswerPage) {
        this.answerContent = this.nowCheckInfo?.answerContent
        this.ruleForm = deepClone(this.nowCheckInfo)
      } else {
        this.nowSelectUser = []
        this.baseSelectUser = []
        this.delOnceHaveUser = []
        this.ruleForm = deepClone(this.nowCheckInfo)

        this.nowSelectUser = this.ruleForm.answer
          ? this.ruleForm.answer.map((item) => {
            return {
              id: item.answer_person.id,
              name: item.answer_person.name
            }
          })
          : []
        this.baseSelectUser = deepClone(this.nowSelectUser)
      }
    }
  },
  // 方法集合
  methods: {
    deleteUser (info, i) {
      const index = this.baseSelectUser.findIndex((item) => {
        if (item.id === info.id) {
          return true
        }
        return false
      })
      if (index !== -1) {
        this.delOnceHaveUser.push(info)
      }
      this.nowSelectUser.splice(i, 1)
    },
    cancelAnswer () {
      this.answerContent = this.ruleForm.answerContent
    },
    explainChnage () {},
    handleClick () {
      if (this.activeName === 'teacher') {
        this.searchList = this.teachList
      } else {
        this.searchList = this.studentList
      }
    },
    // 在dialog中选择解答人时的处理
    changeUserState (e) {
      /* 拿到当前数据，并判断当前数据是否选中 并取反
       * 同时：
       * nowSelectUser 新增或减少一条数据
       * delOnceHaveUser 新增状态此变量无用，编辑状态下需要向后端发送删除保存过的解答人ID
       * baseSelectUser 用来做对比
       */
      const data = e.row

      if (data.isSelect) {
        data.isSelect = false
        const nowSelUserIndex = this.nowSelectUser.findIndex((item) => {
          if (item.id === data.id) {
            return true
          }
          return false
        })
        if (nowSelUserIndex !== -1) {
          this.nowSelectUser.splice(nowSelUserIndex, 1)
        }
        if (data.isBase) {
          this.delOnceHaveUser.push(data)
        }
      } else {
        data.isSelect = true
        this.nowSelectUser.push(data)
        if (data.isBase) {
          const index = this.delOnceHaveUser.findIndex((item) => {
            if (item.id === data.id) {
              return true
            }
            return false
          })
          if (index !== -1) {
            this.delOnceHaveUser.splice(index, 1)
          }
        }
      }
    },
    // 点击添加解答人时做的处理
    async addAnswerPersion () {
      this.isShowAddPersion = true
      this.dialogLoading = true
      let { data } = await findAllTeacherApi()
      const userList = await getMyTeacherStudentAPI(this.$store.user)

      data = [...data]
      this.teachList = [...data]
      this.studentList = [...userList.data]
      this.searchList = this.teachList
      const allUserList = [...data, ...userList.data]
      allUserList.forEach((item) => {
        this.$set(item, 'isSelect', false)
      })

      this.nowSelectUser.forEach((nowSelUser) => {
        const index = allUserList.findIndex((user) => {
          if (nowSelUser.id === user.id) {
            return true
          }
          return false
        })

        if (index !== -1) {
          this.$set(allUserList[index], 'isSelect', true)
          this.$set(allUserList[index], 'isBase', true)
        }
      })

      this.dialogLoading = false
    },
    // 保存答案
    async saveAnswer () {
      if (!this.answerContent?.trim().length) {
        this.$message.warning('回复内容不可为空')
        return
      }
      this.mainLoading = true
      this.ruleForm.answerContent = this.answerContent

      const res = await answerAPI({
        id: this.ruleForm.id,
        content: this.answerContent,
        issuesId: this.ruleForm.issuesId
      })
      console.info(res)
      this.nowCheckInfo.answerContent = this.answerContent
      this.$message.success('回复成功')
      this.mainLoading = false
    },
    getSearchList (e) {
      if (this.activeName === 'teacher') {
        this.searchList = this.teachList.filter((teacher) => {
          if (teacher.name.indexOf(this.searchValue) !== -1) {
            return true
          }
          return false
        })
      } else {
        this.searchList = this.studentList.filter((student) => {
          if (student.name.indexOf(this.searchValue) !== -1) {
            return true
          }
          return false
        })
      }
    },
    async saveDataChange () {
      if (this.disabled) {
        this.$message.warning('问题不支持修改')
      } else if (this.nowSelectUser.length <= 0) {
        this.$message.warning('未添加解答人，无法提交！')
      } else {
        // 判断问题信息是否填写完整
        this.$refs.ruleForm.validate(async (isok) => {
          if (isok) {
            this.$confirm(
              '问题发出后将无法删除，请确认无误后再提交！',
              '提示',
              {
                confirmButtonText: '提交',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
              .then(async () => {
                // eslint-disable-next-line vue/no-mutating-props
                this.ruleForm.answerPersonIds = this.nowSelectUser.map(
                  (item) => item.id
                )
                this.ruleForm.delAnswerPersonIds = this.delOnceHaveUser.map(
                  (item) => item.id
                )
                let res = {}
                if (this.ruleForm.id) {
                  res = await editorIssuesAPI(this.ruleForm)
                } else {
                  res = await createIssuesAPI(this.ruleForm)
                }
                this.$emit('saveAfter', {
                  isEditor: !!this.ruleForm.id,
                  res
                })
                this.$message({
                  type: 'success',
                  message: '提问成功!'
                })
              })
              .catch(() => {
                // this.$message({
                //   type: 'info',
                //   message: '已取消删除'
                // })
              })
          }
        })
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeUnmount () {}, // 生命周期 - 销毁之前
  unmounted () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
.FAQ-info {
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  ::v-deep .dialog_layout {
    z-index: 11;
  }
  ::v-deep .el-textarea__inner {
    height: 100%;
  }
  ::v-deep .editor {
    height: 200px;
    .textNeirong {
      overflow: unset;
      .w-e-text-container {
        flex: unset !important;
      }
    }
  }
}

.issues-answer-box {
  height: 65%;
  overflow-y: auto;
  padding-left: 10px;
}
.add-answe-persion-button {
  border: 1px dashed $--color-primary;
  color: $--color-primary;
}
.send-issues-button {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 25px;
}
.user-tag {
  margin-right: 10px;
}
.select-table-box {
  height: 400px !important;
}
.query_input {
  width: 100%;
}
.answer-info-box {
  display: flex;
  padding: 15px;

  .answer-info-title {
    width: 80px;
    text-align: right;
    font-size: 14px;
    font-weight: 700;
  }
  .answer-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    border: 1px solid #c9d8db;
    height: 150px;
    border-radius: 4px;
    overflow-y: auto;
    padding: 5px;
    position: relative;

    .answer-info-username {
      color: $--color-primary;
      font-size: 14px;
      font-weight: 700;
    }
    .answer-info-text {
      flex: 1;
      overflow-y: auto;
    }
  }
  .reply-time {
    width: 100%;
    text-align: right;
    padding: 3px 0;
    color: $--color-primary;
    font-size: 12px;
  }
}
</style>
