<template>
  <div class="flex-1 flex flex-col" v-loading="loading">
    <!-- List Container -->
    <div class="flex-1 p-4 pt-1">
      <div class="relative">
        <el-tabs v-model="searchParams.releaseStatus" @tab-change="toggleTab">
          <el-tab-pane
            v-for="tab in caseTypeListOptions"
            :key="tab.value"
            :label="tab.label"
            :name="tab.value"
          />
        </el-tabs>
        <div class="absolute right-0 top-2.5 z-1000">
          <el-icon
            size="15"
            class="cursor-pointer hover:rotate-180 transition-all duration-300"
            @click="refresh"
            ><IEpRefresh
          /></el-icon>
        </div>
      </div>
      <div v-if="!list.length" class="flex flex-col items-center justify-center h-64">
        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <el-icon class="text-2xl text-gray-300"><IEpDocument /></el-icon>
        </div>
        <div class="text-gray-500 text-lg mb-2">暂无内容</div>
      </div>

      <div v-else class="space-y-4">
        <div
          v-for="item in list"
          :key="item.id"
          class="flex items-center p-2 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
        >
          <!-- Content -->
          <div class="flex-1 min-w-0">
            <div class="text-gray-900 font-medium truncate line-clamp-1">
              {{ item.title }}
            </div>
            <div class="text-gray-500 text-sm mt-1 truncate">
              <span class="mr-2">
                {{ dayjs(item.createTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
              </span>
              <span
                class="mr-2"
                v-if="searchParams.releaseStatus === ReleaseStatusTypeEnum.PUBLISH"
              >
                <el-tag v-if="item.isAudit === AuditStatusEnum.UNAUDITED" type="warning"
                  >待审核</el-tag
                >
                <el-tag
                  v-else-if="
                    item.isAudit === AuditStatusEnum.AGREED &&
                    item.isUse === UsageStatusEnum.UNUSABLE
                  "
                  type="success"
                  size="small"
                  >已通过</el-tag
                >
                <el-tag v-else-if="item.isAudit === AuditStatusEnum.REJECTED" type="warning"
                  >已驳回</el-tag
                >
                <el-tag
                  v-else-if="
                    item.isAudit === AuditStatusEnum.AGREED && item.isUse === UsageStatusEnum.USED
                  "
                  type="success"
                  size="small"
                  >已使用</el-tag
                >
              </span>
              <!-- <span class="mr-2">浏览 {{ item.viewCount }}</span>
              <span class="mr-2">点赞 {{ item.replyCount }}</span>
              <span class="mr-2">评论 {{ item.collectionCount }}</span>
              <span class="mr-2">收藏 {{ item.praiseCount }}</span> -->
            </div>
          </div>

          <!-- Meta Info -->
          <div class="flex items-center text-gray-400 text-sm ml-4">
            <el-button type="primary" link @click="handleView(item)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(item)"> 编辑 </el-button>
            <el-button v-if="showDelBtn(item)" type="danger" link @click="handleDelete(item)"
              >删除</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="list.length"
      class="flex items-center justify-end px-6 py-4 border-t border-gray-200"
    >
      <div class="pagination-wrapper bg-white rounded-lg shadow-sm border border-gray-100 p-2">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          @size-change="changePageSize"
          @current-change="goToPage"
          :page-sizes="[10, 20, 30, 40]"
          layout="prev, pager, next, jumper, total"
          :total="total"
          class="custom-pagination"
        />
      </div>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { getSelfCaseList, deleteCase, getCaseDetail } from '@/api'
import { usePageSearch } from '@/hooks'
import dayjs from 'dayjs'
import { ReleaseStatusTypeEnum, AuditStatusEnum, UsageStatusEnum } from '@/constants'
import type { TabPaneName } from 'element-plus'
import type { SelfCaseItemDto } from '@/api/user/types'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'

const { confirm } = useMessageBox()
const router = useRouter()

const caseTypeListOptions = [
  { label: '已发布', value: ReleaseStatusTypeEnum.PUBLISH },
  { label: '草稿', value: ReleaseStatusTypeEnum.DRAFT },
]

const toggleTab = (key: TabPaneName) => {
  searchParams.value.releaseStatus = key as ReleaseStatusTypeEnum
  refresh()
}

const { list, loading, searchParams, total, goToPage, changePageSize, refresh } = usePageSearch(
  getSelfCaseList,
  {
    defaultParams: {
      releaseStatus: caseTypeListOptions[0]!.value,
    },
    immediate: false,
  },
)

const showDelBtn = (item: SelfCaseItemDto) => {
  return (
    searchParams.value.releaseStatus === ReleaseStatusTypeEnum.DRAFT ||
    (searchParams.value.releaseStatus === ReleaseStatusTypeEnum.PUBLISH &&
      item.isAudit === AuditStatusEnum.UNAUDITED)
  )
}

const handleView = async (item: SelfCaseItemDto) => {
  // 根据 id获取详情数据
  const { data } = await getCaseDetail(item.id)
  // 打开弹窗 查看详情
  const formData = {
    title: data.title,
    content: data.content,
    keywords: [...data.cultureKeywordMain, ...data.cultureKeywordSecond],
    scenes: [...data.sceneKeywordMain, ...data.sceneKeywordSecond],
    departments: data.depNameList.filter(Boolean),
    syncPublish: data.isSync ? '是' : '否',
  }

  ElMessageBox({
    title: '案例详情',
    message: (
      <div class="w-400px max-h-500px overflow-y-auto px-4">
        {/* 标题 */}
        <div class="mb-5">
          <div class="text-13px text-gray-500 mb-2 flex items-center">
            <span class="text-red-500 mr-1">*</span>
            标题
          </div>
          <div class="bg-gray-50 rounded-lg px-4 py-3 text-gray-700">{formData.title}</div>
        </div>

        {/* 内容 */}
        <div class="mb-5">
          <div class="text-13px text-gray-500 mb-2 flex items-center">
            <span class="text-red-500 mr-1">*</span>
            内容
          </div>
          <div class="bg-gray-50 rounded-lg px-4 py-3 text-gray-700 min-h-80px whitespace-pre-wrap break-words">
            {formData.content}
          </div>
        </div>

        {/* 文化关键词 */}
        <div class="mb-5">
          <div class="text-13px text-gray-500 mb-2 flex items-center">
            <span class="text-red-500 mr-1">*</span>
            文化关键词
          </div>
          <div class="flex flex-wrap gap-2">
            {formData.keywords.map((item, index) => (
              <span key={index} class="px-3 py-1.5 bg-blue-50 text-blue-600 rounded-md text-13px">
                {item.title}
              </span>
            ))}
          </div>
        </div>

        {/* 关联场景 */}
        <div class="mb-5">
          <div class="text-13px text-gray-500 mb-2">关联场景</div>
          {formData.scenes.length > 0 ? (
            <div class="flex flex-wrap gap-2">
              {formData.scenes.map((item, index) => (
                <span key={index} class="px-3 py-1.5 bg-blue-50 text-blue-600 rounded-md text-13px">
                  {item.title}
                </span>
              ))}
            </div>
          ) : (
            <div class="text-gray-400 text-13px">暂无</div>
          )}
        </div>

        {/* 关联部门 */}
        <div class="mb-5">
          <div class="text-13px text-gray-500 mb-2">关联部门</div>
          {formData.departments.length > 0 ? (
            <div class="flex flex-wrap gap-2">
              {formData.departments.map((dept, index) => (
                <span key={index} class="px-3 py-1.5 bg-gray-50 text-gray-700 rounded-md text-13px">
                  {dept}
                </span>
              ))}
            </div>
          ) : (
            <div class="text-gray-400 text-13px">暂无</div>
          )}
        </div>

        {/* 是否同步发布到实践 */}
        <div>
          <div class="text-13px text-gray-500 mb-2 flex items-center">
            <span class="text-red-500 mr-1">*</span>
            是否同步发布到实践
          </div>
          <div class="px-4 py-2.5 bg-gray-50 rounded-lg text-gray-700 inline-block">
            {formData.syncPublish}
          </div>
        </div>
      </div>
    ),
    confirmButtonText: '确定',
    showCancelButton: false,
    customClass: 'form-detail-dialog',
  })
}

const handleEdit = async (item: SelfCaseItemDto) => {
  if (item.isAudit === AuditStatusEnum.AGREED && item.isUse === UsageStatusEnum.USED)
    return push.warning('案例已使用，无法编辑')

  router.push(`/publishCase?id=${item.id}`)
}

const handleDelete = async (item: SelfCaseItemDto) => {
  await confirm({
    title: '提示',
    message: '确定删除该案例吗？',
    type: 'danger',
  })
  await deleteCase(item.id)
  push.success('删除成功')
  refresh()
}

onActivated(() => {
  refresh()
})
</script>
