<template>
  <div class="p-6 bg-white rounded-lg shadow-sm border border-white/50 overflow-hidden">
    <el-skeleton :rows="5" animated :loading="loading" :throttle="{ leading: 0, trailing: 300 }">
      <template #template>
        <!-- 发布者信息 -->
        <div class="border-b border-gray-100 pb-0">
          <div class="flex items-center gap-4">
            <!-- 头像 -->
            <el-skeleton-item variant="circle" style="width: 48px; height: 48px" />

            <!-- 用户名 + 时间 -->
            <div class="flex-1">
              <el-skeleton-item variant="text" style="width: 120px; height: 16px" />
              <el-skeleton-item
                variant="text"
                style="width: 220px; height: 14px; margin-top: 6px"
              />
            </div>

            <!-- 编辑 -->
            <!-- <el-skeleton-item variant="text" style="width: 40px; height: 16px" /> -->

            <!-- 右侧标签 / 操作 -->
            <div class="flex items-center gap-3">
              <el-skeleton-item
                variant="text"
                style="width: 52px; height: 28px; border-radius: 6px"
              />
              <el-skeleton-item
                variant="text"
                style="width: 72px; height: 28px; border-radius: 6px"
              />
              <el-skeleton-item
                variant="text"
                style="width: 72px; height: 28px; border-radius: 6px"
              />
              <!-- <el-skeleton-item variant="circle" style="width: 24px; height: 24px" /> -->
            </div>
          </div>
        </div>

        <!-- 正文区域 -->
        <div class="mt-6">
          <!-- 标题 -->
          <el-skeleton-item variant="text" style="width: 90%; height: 32px; margin-bottom: 16px" />

          <!-- 顶部视频占位 -->
          <!-- <el-skeleton-item
            variant="image"
            style="width: 80%; height: 320px; margin: 0 auto 24px; border-radius: 8px"
          /> -->

          <!-- 文章内容 -->
          <div class="space-y-3">
            <el-skeleton-item variant="text" style="width: 100%" />
            <el-skeleton-item variant="text" style="width: 96%" />
            <el-skeleton-item variant="text" style="width: 92%" />
            <el-skeleton-item variant="text" style="width: 88%" />
          </div>

          <!-- 图片内容 -->
          <!-- <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
            <el-skeleton-item
              v-for="i in 2"
              :key="i"
              variant="image"
              style="width: 100%; height: 256px; border-radius: 12px"
            />
          </div> -->

          <!-- 底部视频 -->
          <!-- <el-skeleton-item
            variant="image"
            style="width: 80%; height: 320px; margin: 24px auto; border-radius: 8px"
          /> -->

          <!-- 标签 -->
          <div class="flex flex-wrap gap-2 mt-6">
            <el-skeleton-item
              v-for="i in 3"
              :key="i"
              variant="text"
              style="width: 72px; height: 28px; border-radius: 9999px"
            />
          </div>
        </div>
      </template>
      <template #default>
        <!-- 发布者信息 -->
        <div class="border-b border-gray-100 pb-0">
          <div class="flex items-center gap-4">
            <div class="relative">
              <img
                :src="articleDetail?.createUserAvatar"
                alt=""
                class="w-12 h-12 rounded-full object-cover cursor-pointer"
                @click="
                  jumpToUserHomePage({
                    userId: articleDetail.createUserId,
                    type: articleDetail.type,
                  })
                "
              />
              <!-- <div
            class="absolute -bottom-1 -right-1 w-6 h-6 bg-gradient-to-r from-yellow-400 to-orange-400 rounded-full flex items-center justify-center text-xs font-bold text-white"
          >
            8
          </div> -->
            </div>

            <div class="flex-1">
              <div class="flex items-center gap-2">
                <h3 class="font-semibold text-gray-800">{{ articleDetail?.createUserName }}</h3>
                <!-- <span
              class="px-2 py-0.5 text-xs bg-gradient-to-r from-purple-100 to-blue-100 text-purple-600 rounded-full"
            >
              资深前端工程师
            </span> -->
              </div>
              <p class="text-sm text-gray-500 mt-1">
                {{ dayjs((articleDetail?.createTime || 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
                · {{ articleDetail?.viewCount || 0 }} 阅读
                <span v-if="articleDetail?.region">· {{ articleDetail?.region }}</span>
              </p>
            </div>
            <!-- 再次编辑按钮 -->
            <el-link
              v-if="isAuthor"
              type="primary"
              :underline="false"
              @click="
                router.push(`/publishLongArticle/${articleDetail.type}?id=${articleDetail.id}`)
              "
              class="text-sm"
            >
              编辑
            </el-link>
            <!-- 优化后的右侧内容 -->
            <div class="flex items-center gap-3 flex-wrap justify-end">
              <button
                v-if="!isAudit && !isAuthor && articleDetail.createUserId"
                type="button"
                class="inline-flex items-center px-3.5 py-1.5 text-sm font-medium bg-blue-50 text-blue-600 rounded-lg border border-blue-100/80 shadow-sm hover:bg-blue-100 hover:border-blue-200/80 active:scale-[0.98] transition-all cursor-pointer shrink-0"
                @click="
                  sendMessageDialogRef?.open({
                    receiverId: articleDetail.createUserId,
                    isReal: isReal,
                  })
                "
              >
                私信
              </button>
              <span
                class="px-3 py-1.5 text-sm font-medium bg-blue-50 text-blue-600 rounded-md hover:bg-blue-100 transition-colors"
                v-if="articleDetail.relateColumn"
              >
                {{ articleDetail.relateColumn }}
              </span>

              <span
                class="px-3 py-1.5 text-sm font-medium bg-blue-50 text-blue-600 rounded-md hover:bg-blue-100 transition-colors"
              >
                {{ articleType }}
              </span>

              <ActionMore :articleDetail="articleDetail" />
            </div>
          </div>
        </div>

        <div class="mt-6">
          <h1 class="text-2xl font-bold text-gray-900 mb-4 leading-tight">
            {{ articleDetail?.title }}
          </h1>
          <!-- 顶部添加的视频 剧中固定宽度 -->
          <div v-if="showTopVideo" class="flex justify-center">
            <video
              :src="articleDetail.articleVideoUrl"
              controls
              class="w-100%! aspect-video bg-black"
              :poster="`${articleDetail.articleVideoUrl}?x-oss-process=video/snapshot,t_1000,f_jpg`"
            />
          </div>
          <!-- 文章内容 -->
          <div v-if="!isHtml" class="prose prose-lg max-w-none">
            <div class="text-gray-700 leading-relaxed space-y-1 text-17px">
              <template v-for="(line, i) in (articleDetail?.content || '').split(/\n/)" :key="i">
                <div v-if="line.trim()" class="indent-2em">
                  {{ line }}
                </div>
                <div v-else class="h-2" aria-hidden="true" />
              </template>
            </div>

            <!-- 图片内容 -->
            <div
              v-if="articleDetail.imgUrl && articleDetail.type !== ArticleTypeEnum.VIDEO"
              class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6"
            >
              <el-image
                v-for="(item, index) in articleDetail.imgUrl.split(',')"
                :key="item"
                :src="item"
                :initial-index="index"
                fit="cover"
                class="rounded-lg w-full h-64 hover:scale-105 transition-transform cursor-pointer"
                :preview-src-list="articleDetail.imgUrl.split(',')"
                :preview-teleported="true"
              />
            </div>
            <div v-if="articleDetail.type === ArticleTypeEnum.VIDEO" class="flex justify-center">
              <video
                :src="articleDetail.videoUrl"
                controls
                class="w-100%! aspect-video bg-black"
                :poster="`${articleDetail.videoUrl}?x-oss-process=video/snapshot,t_1000,f_jpg`"
              />
            </div>
          </div>

          <div v-else v-html="articleDetail.content" class="html-content" v-image-preview />

          <!-- 底部添加的视频 -->
          <div v-if="showBottomVideo" class="flex justify-center">
            <!-- 长宽 1/1 -->
            <video
              :src="articleDetail.articleVideoUrl"
              controls
              class="w-100%! aspect-video bg-black"
              :poster="`${articleDetail.articleVideoUrl}?x-oss-process=video/snapshot,t_1000,f_jpg`"
            />
          </div>
          <!-- 标签 -->
          <div class="flex flex-wrap gap-2 mt-6">
            <span
              v-for="item in articleDetail?.tagNameList"
              :key="item"
              class="px-3 py-1 text-sm bg-gradient-to-r from-cyan-100 to-blue-100 text-cyan-600 rounded-full hover:shadow-md transition-all cursor-pointer"
            >
              #{{ item }}
            </span>
          </div>
        </div>
      </template>
    </el-skeleton>
    <!-- 富文本内容的 图片预览 -->
    <el-image-viewer
      v-if="showPreview"
      :url-list="srcList"
      show-progress
      :teleported="true"
      :initial-index="currentPreviewIndex"
      @close="showPreview = false"
    />
    <SendMessageDialog ref="sendMessageDialogRef" />
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import type { ArticleItemDto } from '@/api'
import { articleTypeListOptions, ArticleTypeEnum, VideoPositionEnum } from '@/constants'
import ActionMore from '@/components/common/ActionMore/index.vue'
import SendMessageDialog from '@/components/common/SendMessageDialog/index.vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import type { Directive } from 'vue'
import { useNavigation } from '@/hooks'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const router = useRouter()
const { jumpToUserHomePage } = useNavigation()
const { articleDetail, isAudit } = defineProps<{
  articleDetail: ArticleItemDto
  isAudit: boolean // 是否是审核页面
}>()

const sendMessageDialogRef = ref<InstanceType<typeof SendMessageDialog> | null>(null)
const articleType = computed(() => {
  return articleTypeListOptions.find((item) => item.value === articleDetail.type)?.label
})
const isReal = computed(() => {
  return +(
    articleDetail.type === ArticleTypeEnum.PRACTICE ||
    articleDetail.type === ArticleTypeEnum.INTERVIEW ||
    articleDetail.type === ArticleTypeEnum.QUESTION
  )
})

const loading = computed(() => !articleDetail.title)

// 是否是作者
const isAuthor = computed(() => {
  return articleDetail.createUserId === userInfo.value.userId
})

// 如果类型是帖子 专栏 和 专访 就是html
const isHtml = computed(() => {
  return (
    articleDetail.type === ArticleTypeEnum.POST ||
    articleDetail.type === ArticleTypeEnum.COLUMN ||
    articleDetail.type === ArticleTypeEnum.INTERVIEW
  )
})

const isInterviewOrColumn = computed(
  () =>
    articleDetail.type === ArticleTypeEnum.INTERVIEW ||
    articleDetail.type === ArticleTypeEnum.COLUMN,
)

const showTopVideo = computed(
  () =>
    isInterviewOrColumn.value &&
    articleDetail.videoLocation === VideoPositionEnum.TOP &&
    articleDetail.articleVideoUrl,
)
const showBottomVideo = computed(
  () =>
    isInterviewOrColumn.value &&
    articleDetail.videoLocation === VideoPositionEnum.BOTTOM &&
    articleDetail.articleVideoUrl,
)

const showPreview = ref(false)
const currentPreviewIndex = ref(0)
const srcList = ref<string[]>([])

// 图片预览的指令
const vImagePreview: Directive = {
  mounted(el: HTMLElement) {
    const imgs = el.querySelectorAll('img')
    imgs.forEach((item, index) => {
      item.style.cursor = 'pointer'
      if (item.src) {
        srcList.value.push(item.src)
        item.addEventListener('click', () => {
          currentPreviewIndex.value = index
          showPreview.value = true
        })
      }
    })
  },
}
</script>

<style scoped>
.html-content {
  font-size: 18px;
  line-height: 1.8;
  color: #374151;
  word-break: break-word;
}

.html-content :deep(p) {
  margin: 1em 0;
}

.html-content :deep(h1),
.html-content :deep(h2),
.html-content :deep(h3),
.html-content :deep(h4),
.html-content :deep(h5),
.html-content :deep(h6) {
  margin: 1.2em 0 0.6em;
  line-height: 1.4;
  font-weight: 600;
  color: #111827;
}

.html-content :deep(h1) {
  font-size: 1.7em;
}

.html-content :deep(h2) {
  font-size: 1.5em;
}

.html-content :deep(h3) {
  font-size: 1.3em;
}

.html-content :deep(ul),
.html-content :deep(ol) {
  margin: 1em 0;
  padding-left: 1.5em;
}

.html-content :deep(ul) {
  list-style: disc;
}

.html-content :deep(ol) {
  list-style: decimal;
}

.html-content :deep(li) {
  margin: 0.35em 0;
}

.html-content :deep(blockquote) {
  margin: 1em 0;
  padding: 0.6em 1em;
  border-left: 4px solid #d1d5db;
  color: #6b7280;
  background: #f9fafb;
}

.html-content :deep(pre),
.html-content :deep(code) {
  font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
}

.html-content :deep(pre) {
  margin: 1em 0;
  padding: 0.8em 1em;
  border-radius: 6px;
  overflow-x: auto;
  background: #f3f4f6;
}

.html-content :deep(code) {
  padding: 0.1em 0.35em;
  border-radius: 4px;
  background: #f3f4f6;
}

.html-content :deep(pre code) {
  padding: 0;
  background: transparent;
}

.html-content :deep(a) {
  color: #2563eb;
  text-decoration: underline;
}
</style>
