<template>
  <div>
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> 帖子详情 </span>
        </template>
      </el-page-header>
    </div>

    <div class="content" v-loading="pageLoading">
      <el-card shadow="hover">
        <template #header>
          <h3>{{ form.informationTitle }}</h3>
          <div class="card-header">
            <div class="header-left">
              <img src="@/assets/images/avatar.png" alt="">
              <span>{{ form.deptName }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ form.userName }}</span>
            </div>

            <div class="header-right">
              <span>{{ form.createTime }}</span>
            </div>
          </div>
        </template>

        <div class="info">
          <!-- <div v-html=""></div> -->
          <div>
            {{ form.informationDetail }}
          </div>
        </div>

        <template #footer>
          <div class="comment">
            <p>评论：</p>
            <el-input type="textarea" :rows="5" v-model="commentInput" placeholder="请输入活动名称关键字搜索"
              class="input-with-select" clearable>
            </el-input>
            <el-button @click="publishComment" type="primary">发表</el-button>
          </div>

          <!-- 评论列表 -->
          <div v-if="commentList.length != 0" class="comment-list" v-loading="commentLoading">
            <div class="comment-item" v-for="(item, index) of commentList">
              <div class="item-header">
                <div class="header-left">
                  <img v-if="item.expertPhotograph" :src="item.expertPhotograph" alt="">
                  <img v-else src="@/assets/images/avatar.png" alt="">
                  <span>{{ item.deptName }}</span>
                  <el-divider direction="vertical"></el-divider>
                  <span>{{ item.expertName }}</span>
                </div>
                <div class="header-right">
                  <span @click="handleReply(item.id, index, null, 0)" style="cursor: pointer" v-if="item.reply"><el-icon>
                      <ChatLineRound />
                    </el-icon>回复</span>
                  <span @click="handleDelete(item.id)" style="cursor: pointer" v-if="item.deleted"><el-icon>
                      <DeleteFilled />
                    </el-icon>删除</span>
                  <span>评论时间：{{ item.commentTime }}</span>
                </div>
              </div>
              <p>{{ item.comment }}</p>

              <!-- 次级评论列表 -->
              <div v-if="item.commontVoList != null" class="item-content">
                <div class="item-comment-item" v-for="(i, count) of item.commontVoList">
                  <div v-if="!i.canComment">

                    <div class="item-header">
                      <div class="header-left">
                        <img v-if="i.replyPhotograph" :src="i.replyPhotograph" alt="">
                        <img v-else src="@/assets/images/avatar.png" alt="">
                        <span>{{ i.replyDeptName }}</span>
                        <el-divider direction="vertical"></el-divider>
                        <span>{{ i.replyName }}</span>
                      </div>
                      <div class="header-right">
                        <span @click="handleReply(item.id, index, i, 1)" style="cursor: pointer" v-if="item.reply"><el-icon>
                            <ChatLineRound />
                          </el-icon>回复</span>
                        <span @click="handleDelete(i.id)" style="cursor: pointer" v-if="item.deleted"><el-icon>
                            <DeleteFilled />
                          </el-icon>删除</span>
                        <span>评论时间：{{ i.commentTime }}</span>
                      </div>
                    </div>

                    <p>{{ i.comment }}</p>

                  </div>

                  <div v-if="i.canComment && replyShow">
                    <div class="comment">
                      <p>回复{{ i.replyName }}：</p>
                      <el-input type="textarea" :rows="5" v-model="replyEdit" placeholder="请输入回复"
                        class="input-with-select" clearable>
                      </el-input>
                      <el-button size="small" @click="publishReply(item.id)" type="primary">发表</el-button>
                    </div>
                  </div>

                </div>

              </div>


            </div>
          </div>

        </template>
      </el-card>

    </div>
  </div>
</template>

<script lang="ts" setup>
import FileOrImage from '@/components/FileOrImage/index.vue';
import { getLearningInformation, updateLearningInformation, addLearningInformation } from '@/api/study/information';
import { listLearningCommont, addLearningCommont, delLearningCommont } from '@/api/study/comment';
import { globalHeaders } from '@/utils/request';
import { LearningInformationVO, LearningInformationQuery, LearningInformationForm } from '@/api/study/information/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { source_classify, resource_status, source_type } = toRefs<any>(proxy?.useDict('source_classify', 'resource_status', 'source_type'));
const type = computed(() => proxy.$route.query.type);
const _id = computed(() => proxy.$route.query.id);
const buttonLoading = ref(false)
const router = useRouter();
const { is_publish, information_classify } = toRefs<any>(proxy?.useDict('is_publish', 'information_classify'));
const learningInformationFormRef = ref<ElFormInstance>();
const route = useRoute();
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const commentInput = ref('');
const goBack = () => {
  router.back();
}
const resourceFormRef = ref<ElFormInstance>();
const initForm = {
  id: undefined,
  informationClassifyId: undefined,
  informationImage: undefined,
  informationTitle: undefined,
  informationDetail: undefined,
  deptName: '',
  createTime: '',
  userName: '',
  status: undefined,
  remark: undefined,
  userId: undefined
}
//删除评论
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除这条评论吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {

    commentLoading.value = true;
    const res = await delLearningCommont(id).finally(() => {
      commentLoading.value = false;
    })
    if (res.code == 200) {

      getCommentList();

      ElNotification({
        title: '提示',
        message: '删除评论成功！',
        type: 'success',
      })
    }
  }).catch(() => {

  })


}
const replyEdit = ref('');
const replyShow = ref(false);
const replyMode = ref(0);
const replyIndex = ref<number>(undefined)
//回复评论
const handleReply = async (id, index, ele, mode) => {
  if (!replyShow.value) {
    if (ele == null) {
      commentList.value[index].commontVoList == null ?
        commentList.value[index].commontVoList = [{ canComment: true, replyName: commentList.value[index].expertName }] :
        commentList.value[index].commontVoList.push({ canComment: true, replyName: commentList.value[index].expertName });
      replyMode.value = 0;
    } else {
      commentList.value[index].commontVoList == null ?
        commentList.value[index].commontVoList = [{ canComment: true, replyName: ele.replyName }] :
        commentList.value[index].commontVoList.push({ canComment: true, replyName: ele.replyName });
      replyMode.value = 1;
    }
    replyIndex.value = index;
    replyShow.value = true;
  } else {

    if (index != replyIndex) {
      replyIndex.value != undefined ?
        commentList.value[replyIndex.value].commontVoList.pop() : null;
      if (mode == 0) {
        commentList.value[index].commontVoList == null ?
          commentList.value[index].commontVoList = [{ canComment: true, replyName: commentList.value[index].expertName }] :
          commentList.value[index].commontVoList.push({ canComment: true, replyName: commentList.value[index].expertName });
        replyMode.value = 0;
        replyIndex.value = index;
        return
      } else {
        commentList.value[index].commontVoList == null ?
          commentList.value[index].commontVoList = [{ canComment: true, replyName: ele.replyName }] :
          commentList.value[index].commontVoList.push({ canComment: true, replyName: ele.replyName });
        replyMode.value = 0;
        replyIndex.value = index;
        return
      }
    } else {

      if (mode != replyMode.value) {
        if (mode == 0) {
          commentList.value[index].commontVoList[commentList.value[index].commontVoList.length - 1].replyName = commentList.value[index].expertName;
          replyMode.value = 0;
          return
        } else {
          commentList.value[index].commontVoList[commentList.value[index].commontVoList.length - 1].replyName = ele.replyName;
          replyMode.value = 1;
          return
        }
      } else {
        commentList.value[index].commontVoList.pop();
      }

    }
    replyShow.value = false;
  }
}
const form = ref({ ...initForm });
//提交
const submitForm = async () => {

  ElMessageBox.confirm('确认提交以上信息吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    resourceFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (type.value == 'add') {

          form.value.status = '1';

          const res = await addLearningInformation(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("提交成功");
            router.back();
          }

        } else if (type.value == 'edit') {
          const res = await updateLearningInformation(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("修改成功");
            router.back();
          }
        }
        // const res = await addExpertRecommend(form.value).finally(() => { buttonLoading.value = false });
        // if (res.code == 200) {
        //   proxy?.$modal.msgSuccess("提交成功");
        //   router.back();
        // }
        reset();

      }

    });
  }).catch(() => {

  })

}

/** 表单重置 */
const reset = () => {
  form.value = { ...initForm };
  learningInformationFormRef.value?.resetFields();
}
//取消
const cancel = () => {
  router.back();
  reset();
}
const commentList = ref([]);
const commentLoading = ref(false);
//评论列表
const getCommentList = async () => {
  commentLoading.value = true;
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await listLearningCommont({ informationId: _id.value.toString(), parentId: 0 }).finally(() => {
    commentLoading.value = false;
  });
  console.log(`rresssss`, res);
  commentList.value = res.rows;

}
// 发表评论
const publishComment = async () => {
  commentLoading.value = true;
  let data = {
    informationId: form.value.id,
    comment: commentInput.value
  }
  const res = await addLearningCommont(data).finally(() => {
    commentLoading.value = false;
  })
  if (res.code == 200) {
    resetComment();

    getCommentList();

    ElNotification({
      title: '提示',
      message: '发表评论成功！',
      type: 'success',
    })
  }


}
const resetComment = () => {

  replyShow.value = false;
  replyEdit.value = '';
  commentInput.value = '';
}
// 发表回复
const publishReply = async (id) => {
  let data = {
    parentId: id,
    informationId: form.value.id,
    comment: replyEdit.value
  }
  const res = await addLearningCommont(data).finally(() => { })
  if (res.code == 200) {
    resetComment();

    getCommentList();

    ElNotification({
      title: '提示',
      message: '发表回复成功！',
      type: 'success',
    })
  }


}
const pageLoading = ref(false);
//帖子详情
const getData = async () => {
  pageLoading.value = true;
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await getLearningInformation(_id.value.toString()).finally(()=>{pageLoading.value = false;});
  console.log(`rresssss`, res);
  Object.assign(form.value, res.data);

}
/** 附件上传成功处理 */
const handleUpload = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {

  // form.value.paperAccessory = response.data.url;

  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '上传论文结果', {
    dangerouslyUseHTMLString: true
  });
};
onActivated(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();
  getCommentList();

})
onMounted(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();
  getCommentList();
})

const formRules = ref({
  resourceName: [{ required: true, message: '资源名称不能为空', trigger: 'blur' }],
  resourceClassify: [{ required: true, message: '资源类型不能为空', trigger: 'blur' }],
  resourceType: [{ required: true, message: '资源分类不能为空', trigger: 'blur' }],
  resourceBrief: [{ required: true, message: '资源简介不能为空', trigger: 'blur' }],
  resourceTime: [{ required: true, message: '发表时间不能为空', trigger: 'blur' }],
  author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
  publishJournal: [{ required: true, message: '发表期刊不能为空', trigger: 'blur' }],
  journalNo: [{ required: true, message: '期刊号不能为空', trigger: 'blur' }],
  paperTitle: [{ required: true, message: '论文标题不能为空', trigger: 'blur' }],
  paperAccessory: [{ required: true, message: '论文附件不能为空', trigger: 'blur' }],
})

</script>

<style lang="scss" scoped>
.header {
  margin: 1vh 0 1vh 2vw;

}

.el-form {
  margin-top: 2vh;
  margin-left: 2vw;
  width: 40%;
}

.btn {
  margin-top: 1vh;
  width: 60%;
  margin: 0 auto;
  display: flex;
  justify-content: space-evenly;

  .el-button {
    width: 30%;
  }
}

.el-card {
  :deep(.el-card__footer) {
    padding-bottom: 1vh;
  }

  width: 95%;
  margin: 0 auto;

  padding: 0 1vw;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 12px;

  img {
    margin-left: 10px;
    width: 40px;
    aspect-ratio: 1;
    border: 0.5px solid black;
    border-radius: 50%;
  }

  span {
    font-size: 18px;
  }

  span:nth-child(2) {
    margin-left: 10px;
    padding-left: 5px;
    display: flex;
    align-items: center;
  }

  span:nth-child(4) {}
}

.content {
  h3 {
    margin: 2vh 0;
    font-weight: bolder;
    font-size: 1.4rem;
  }
}

.info {}

.comment {
  padding-bottom: 1vh;

  .el-textarea {
    width: 100%;
    margin-bottom: 1vh;
  }

  .el-button {
    float: right;
  }
}

.comment-list {
  margin-top: 4vh;
  background-color: #eee;
  padding: 20px;
  border-radius: 5px;

  .comment-item {
    margin-bottom: 20px;

    &>p {
      padding-left: 2vw;
    }

    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 10px;
      border-bottom: 0.5px solid #ddd;

      .header-right {
        display: flex;
        align-items: center;

        span {
          display: flex;
          align-items: center;
          margin-left: 25px;
        }
      }
    }

    .item-content {
      width: 96%;
      margin-left: 4%;
      margin-top: 2vh;
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;

      .item-comment-item {
        margin-top: 1.5vh;
        padding: 10px;
        border-radius: 10px;
        border: 0.5px solid #ddd;
        padding-bottom: 20px;

        p {
          margin: 15px;
          margin-bottom: 0;
        }
      }


    }
  }
}
</style>
