<script setup lang="ts">
import { ref, reactive } from 'vue'
import {
  getKnowledgeContentDetail,
  querycomment,
  addComment,
  queryrecord,
} from '@/api/knowledge/index'
import { uploadUrl } from '@/utils/uploadFile'
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
const uploadAction = uploadUrl.USER_AVATAR
const isloading = ref(false)
const footernav = ref([
  {
    name: '评论',
  },
  {
    name: '查看记录',
  },
])
const replyContents = reactive({})
const handleReplyInput = (e: any, commentId: string) => {
  replyContents[commentId] = e.detail.value
}
const selected = ref('评论')
const commentlist = ref([]) as any
const paramsoptions = ref({}) as any
const maindata = ref({}) as any
const isReply = ref({}) as any
const commentipt = ref<string>('')
const fileListup = ref([])
const viewRecords = ref([])
// 控制回复内容展开/收起的状态
const expandedReplies = ref({}) as any
//获取知识库内容详细信息
const queryKnowledgeContentDetailfn = async () => {
  try {
    isloading.value = true
    const res = (await getKnowledgeContentDetail({
      roleId: paramsoptions.value?.id,
    })) as any
    if (res.code === 200) {
      maindata.value = res?.data || {}
    }
  } catch (error) {
    console.log(error)
  } finally {
    isloading.value = false
  }
}
//获取评论列表
const querycommentfn = async () => {
  try {
    isloading.value = true
    const res = (await querycomment({
      targetId: '14',
      targetType: 'knowledge',
    })) as any
    if (res.code === 200) {
      commentlist.value = res?.data || []
    }
  } catch (error) {
    console.log(error)
  } finally {
    isloading.value = false
  }
}
//获取查看记录
const queryrecordfn = async () => {
  try {
    isloading.value = true
    const res = (await queryrecord({
      contentId: paramsoptions.value?.classId,
      userId: userStore.userInfo.user.userId,
    })) as any
    viewRecords.value = res?.rows || []
  } catch (error) {
    console.log(error)
  } finally {
    isloading.value = false
  }
}
onLoad(async (options) => {
  paramsoptions.value = options
  await Promise.all([
    queryKnowledgeContentDetailfn(),
    querycommentfn(),
    queryrecordfn(),
  ])
})
const navigateToReminder = () => {
  uni.navigateTo({
    url: '/pages/knowledge/search/details/viewdetails/reminder',
  })
}
const formatRelativeTime = (dateString: any) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  if (diff < 60_000) {
    return '刚刚'
  }
  const minutes = Math.floor(diff / 60_000)
  const hours = Math.floor(diff / 3_600_000)
  const days = Math.floor(diff / 86_400_000)

  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else {
    return `${days}天前`
  }
}
const download = (url) => {
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        // uni.saveFile({
        //   tempFilePath: res.tempFilePath,
        //   success: function (res) {
        //     console.log(res);
        //   },
        // })
      }
    },
  })
}
// 提交评论
const handleSend = async () => {
  if (!commentipt.value.trim() && fileListup.value.length === 0) {
    uni.showToast({
      icon: 'error',
      title: '请输入评论内容或上传图片',
    })
    return
  }
  try {
    await addComment({
      targetId: Number(paramsoptions.value?.classId),
      targetType: 'knowledge',
      attachments: fileListup.value
        .map((item) => JSON.parse(item.response).data.fileName)
        .join(','),
      content: commentipt.value,
    })
    commentipt.value = ''
    fileListup.value = []
    querycommentfn()
  } catch {
    uni.showToast({
      icon: 'error',
      title: '评论提交失败',
    })
  }
}

const handleUploadSuccess = ({ file, fileList, formData }) => {
  fileListup.value = fileList
}
const handleUploadRemove = ({ file }) => {
  fileListup.value = fileListup.value.filter((item) => item.uid !== file.uid)
}
const handleReply = (data) => {
  isReply.value[data.id] = !isReply.value[data.id]
}
const handleClose = (id) => {
  isReply.value[id] = false
}
const handleReplySubmit = async (id: any) => {
  console.log(replyContents)
  if (!replyContents[id].trim()) {
    uni.showToast({
      icon: 'error',
      title: '评论提交失败',
    })
    return
  }
  try {
    await addComment({
      parentId: id,
      targetId: Number(paramsoptions.value?.classId),
      targetType: 'knowledge',
      content: replyContents[id] || '',
    })
    querycommentfn()
    isReply.value[id] = false
    replyContents[id] = ''
  } catch {
    uni.showToast({
      icon: 'error',
      title: '评论提交失败',
    })
  }
}
const toggleReplyExpand = (commentId: string, replyIndex: any) => {
  const key = `${commentId}-${replyIndex}`
  expandedReplies.value[key] = !expandedReplies.value[key]
}
</script>
<template>
  <view class="viewdetails">
    <view v-if="isloading" class="loading-container">
      <wd-loading size="40px" color="#215ACD"></wd-loading>
    </view>
    <view class="viewdetails_header">
      <view class="viewdetails_header_title">
        {{ maindata?.title || '' }}
      </view>
      <view class="viewdetails_header_time">
        {{ `编辑于${maindata?.updateTime || ''}` }}
      </view>
    </view>
    <view class="viewdetails_main_box">
      <view class="viewdetails_main">
        <view v-html="maindata?.content || ''"></view>
      </view>
      <view class="viewdetails_upload_box">
        <view
          class="viewdetails_upload"
          @click="download(value)"
          v-for="value in maindata?.attachmentUrl"
        >
          <view class="viewdetails_upload_title">
            <span>{{ value.split('?')[0].split('/').pop() || '' }}</span>
            <span>kb</span>
          </view>
          <view class="viewdetails_upload_download">
            <wd-icon
              style="color: #31373d"
              name="download"
              size="22px"
            ></wd-icon>
          </view>
        </view>
      </view>
      <view class="viewdetails_footer">
        <view class="viewdetails_footer_nav">
          <view
            :class="{
              viewdetails_footer_nav_item: true,
              viewdetails_footer_nav_item_active: selected === item.name,
            }"
            v-for="item in footernav"
            :key="item.name"
            @tap="selected = item.name"
          >
            {{ item.name }}
            <view
              class="viewdetails_footer_nav_line"
              v-if="selected === item.name"
            ></view>
          </view>
        </view>
        <view v-if="selected === '评论'">
          <view class="viewdetails_footer_comment_ipt">
            <view class="viewdetails_footer_comment_ipt_input">
              <input
                v-model="commentipt"
                type="text"
                placeholder="说点什么..."
                :maxlength="200"
                @keydown.enter="handleSend"
              />
              <view
                style="
                  position: absolute;
                  bottom: 8rpx;
                  right: 16rpx;
                  font-size: 20rpx;
                  color: #999;
                "
              >
                <text>{{ commentipt.length }}/200</text>
              </view>
            </view>

            <wd-upload
              :file-list="fileListup"
              :action="uploadAction"
              image-mode="aspectFill"
              :limit="1"
              @success="handleUploadSuccess"
              @remove="handleUploadRemove"
            >
              <template #default>
                <view class="viewdetails_footer_comment_ipt_send"> </view>
              </template>
            </wd-upload>
          </view>
          <view style="display: flex; flex-direction: column; gap: 40rpx">
            <view
              class="viewdetails_footer_comment_list"
              v-for="item in commentlist"
              :key="item.name"
            >
              <view class="viewdetails_footer_comment_list_info">
                <view class="viewdetails_footer_comment_list_avatvr">{{
                  item?.username?.slice(-2) || ''
                }}</view>
                <span class="viewdetails_footer_comment_list_name">{{
                  item?.username
                }}</span>
              </view>
              <view class="viewdetails_footer_comment_list_content">
                {{ item.content }}
              </view>
              <view>
                <wd-img
                  v-for="(value, index) in item?.attachmentsUrl"
                  :key="index"
                  :src="value"
                  :width="50"
                  :height="50"
                  :enable-preview="true"
                />
              </view>
              <view class="viewdetails_footer_comment_list_time">
                <span class="viewdetails_footer_comment_list_time_text">{{
                  formatRelativeTime(item?.updateTime)
                }}</span>
                <span
                  class="viewdetails_footer_comment_list_time_reply"
                  @tap="handleReply(item)"
                  >回复</span
                >
              </view>
              <view
                class="viewdetails_footer_comment_list_reply"
                v-for="(value, index) in item?.children"
                :key="index"
              >
                <text>{{ value?.username }}：</text>
                <template v-if="value?.content?.length > 50">
                  <text class="reply-content" v-if="!expandedReplies[`${item.id}-${index}`]">
                    {{ value.content.substring(0, 50) }}...
                  </text>
                  <text class="reply-content" v-else>
                    {{ value.content }}
                  </text>
                  <text 
                    class="reply-expand-btn" 
                    @tap="toggleReplyExpand(item.id, index)"
                  >
                    {{ expandedReplies[`${item.id}-${index}`] ? '收起' : '展开' }}
                  </text>
                </template>
                <template v-else>
                  <text class="reply-content">{{ value?.content }}</text>
                </template>
              </view>
              <view
                class="viewdetails_footer_comment_list_reply_box"
                v-if="isReply[item?.id]"
              >
                <view style="position: relative; width: 100%">
                  <input
                    class="viewdetails_footer_comment_list_reply_ipt"
                    type="text"
                    placeholder="写下您的回复..."
                    :maxlength="200"
                    v-model="replyContents[item?.id]"
                    @input="(e) => handleReplyInput(e, item?.id)"
                  />
                  <view
                    style="
                      position: absolute;
                      bottom: 8rpx;
                      right: 16rpx;
                      font-size: 20rpx;
                      color: #999;
                    "
                  >
                    <text
                      >{{ (replyContents[item?.id] || '').length }}/200</text
                    >
                  </view>
                </view>
                <view style="display: flex; gap: 20rpx">
                  <wd-button
                    size="small"
                    @tap="handleReplySubmit(item?.id)"
                    style="
                      padding: 6rpx 16rpx;
                      font-size: 24rpx;
                      border-radius: 14rpx;
                    "
                    >提交</wd-button
                  >
                  <wd-button
                    plain
                    size="small"
                    style="
                      padding: 6rpx 16rpx;
                      font-size: 24rpx;
                      border-radius: 14rpx;
                    "
                    @tap="handleClose(item?.id)"
                    >收起</wd-button
                  >
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
          v-else
          style="
            display: flex;
            flex-direction: column;
            gap: 40rpx;
            margin-top: 40rpx;
          "
        >
          <view
            v-for="item in viewRecords"
            :key="item.id"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <view
              style="
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                background-color: #234b9a;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #fff;
              "
              >{{ item?.userName?.slice(-2) || '' }}</view
            >
            <view style="color: #31373d">{{ item?.userName }}</view>
            <view style="color: #999">{{ item?.updateTime }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="viewdetails_footer_btn" @tap="navigateToReminder">提 醒</view>
  </view>
</template>
<style scoped lang="scss">
html,
body {
  overflow: hidden;
}
.viewdetails {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 44rpx;
  padding: 40rpx;
  box-sizing: border-box;
}

.viewdetails_header {
  align-self: flex-start;
  .viewdetails_header_title {
    font-family: Alibaba PuHuiTi 2;
    font-weight: 500;
    font-style: 65 Medium;
    font-size: 64rpx;
    leading-trim: NONE;
    letter-spacing: 4%;
    line-height: 100rpx;
    color: #31373d;
  }
  .viewdetails_header_time {
    font-family: Alibaba PuHuiTi 2;
    font-weight: 400;
    font-style: 55 Regular;
    font-size: 24rpx;
    leading-trim: NONE;
    line-height: 42rpx;
    letter-spacing: 4%;
    vertical-align: middle;
    color: #86909c;
    margin-top: 16rpx;
  }
}
.viewdetails_main_box {
  height: 74%;
  //   flex: 0.9;
  overflow-y: auto;
}
.viewdetails_main {
  width: 100%;
  // .viewdetails_main_title {
  //   font-family: Alibaba PuHuiTi 2;
  //   font-weight: 400;
  //   font-style: 55 Regular;
  //   font-size: 42rpx;
  //   leading-trim: NONE;
  //   line-height: 80rpx;
  //   letter-spacing: 4%;
  //   margin-bottom: 18rpx;
  //   color: #31373d;
  // }
  // .viewdetails_main_content {
  //   font-family: Alibaba PuHuiTi 2;
  //   font-weight: 400;
  //   font-style: 55 Regular;
  //   font-size: 28rpx;
  //   leading-trim: NONE;
  //   line-height: 44rpx;
  //   letter-spacing: 4%;
  //   color: #31373d;
  // }
}

.viewdetails_upload_box {
  margin-top: 48rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}
.viewdetails_upload {
  width: 100%;
  height: 120rpx;
  border: 1rpx solid #e6e8eb;
  display: flex;
  border-radius: 16rpx;
  padding: 24rpx 32rpx;
  box-sizing: border-box;
  justify-content: space-between;
  gap: 16rpx;
  .viewdetails_upload_title {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    :nth-child(1) {
      font-family: Alibaba PuHuiTi 2;
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 28rpx;
      leading-trim: NONE;
      line-height: 28rpx;
      letter-spacing: 4%;
      color: #31373d;
    }
    :nth-child(2) {
      font-family: Alibaba PuHuiTi 2;
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 24rpx;
      leading-trim: NONE;
      line-height: 24rpx;
      letter-spacing: 0%;
      color: #bbbdbf;
    }
  }
  .viewdetails_upload_download {
    align-self: center;
  }
}
.viewdetails_footer {
  width: 100%;
  border-top: 1rpx solid #ebeef1;
  padding-top: 46rpx;
  margin-top: 36rpx;
  box-sizing: border-box;
  .viewdetails_footer_nav {
    width: 100%;
    display: flex;
    gap: 40rpx;
    .viewdetails_footer_nav_item {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 32rpx;
      color: #4e5969;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10rpx;
    }
    .viewdetails_footer_nav_item_active {
      font-weight: 500;
      color: #31373d;
    }
    .viewdetails_footer_nav_line {
      width: 60%;
      height: 6rpx;
      background-color: #215acd;
      border-radius: 4rpx;
    }
  }
  .viewdetails_footer_comment_ipt {
    margin-top: 52rpx;
    margin-bottom: 76rpx;
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    gap: 32rpx;
    .viewdetails_footer_comment_ipt_input {
      position: relative;
      height: 100%;
      flex: 1;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 0 24rpx;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      input {
        width: 100%;
        height: 100%;
        border: none;
        background: transparent;
        font-size: 28rpx;
        color: #31373d;
      }
    }
    .viewdetails_footer_comment_ipt_send {
      width: 45rpx;
      height: 37rpx;
      background-image: url('../../../../../assets/image.png');
      background-repeat: no-repeat;
      background-size: cover;
      align-self: center;
    }
    :deep(.wd-upload__preview) {
      width: 110rpx;
      height: 110rpx;
    }
  }
  .viewdetails_footer_comment_list {
    width: 100%;
    margin-bottom: 24rpx;
    // display: flex;
    // flex-direction: column;
    // gap: 30rpx;
    .viewdetails_footer_comment_list_info {
      display: flex;
      gap: 16rpx;
      align-items: center;
      .viewdetails_footer_comment_list_avatvr {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background-color: #234b9a;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 400;
        font-size: 24rpx;
        color: #fff;
      }
      .viewdetails_footer_comment_list_name {
        font-weight: 400;
        font-size: 32rpx;
        color: #31373d;
      }
    }
    .viewdetails_footer_comment_list_content {
      margin-top: 8rpx;
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 28rpx;
      line-height: 40rpx;
      color: #86909c;
    }
    .viewdetails_footer_comment_list_time {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .viewdetails_footer_comment_list_time_text {
        margin-top: 16rpx;
        font-weight: 400;
        font-style: 55 Regular;
        font-size: 28rpx;
        color: #86909c;
      }
      .viewdetails_footer_comment_list_time_reply {
        font-size: 24rpx;
        color: #215acd;
      }
    }
    .viewdetails_footer_comment_list_reply {
      width: 100%;
      // background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 12rpx 24rpx;
      box-sizing: border-box;
      font-size: 24rpx;
      color: #86909c;
      line-height: 36rpx;
      margin-top: 16rpx;
      word-break: break-word;
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;
      .reply-content {
        display: inline;
        white-space: normal;
        word-wrap: break-word;
        flex: 1;
      }
      .reply-expand-btn {
        color: #215acd;
        font-size: 20rpx;
        margin-left: 8rpx;
        cursor: pointer;
        flex-shrink: 0;
        align-self: center;
      }
    }
    .viewdetails_footer_comment_list_reply_box {
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      margin-top: 16rpx;
      .viewdetails_footer_comment_list_reply_ipt {
        border: 1px solid #f5f5f5;
        border-radius: 20rpx;
        padding: 12rpx;
        font-size: 24rpx;
        color: #86909c;
      }
    }
  }
}
.viewdetails_footer_btn {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #d4d6d9;
  border-radius: 8rpx;
  font-size: 32rpx;
  color: #31373d;
  line-height: 80rpx;
  text-align: center;
}
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
</style>
