<template>
  <div class="art-page-view space-y-4">
    <ElCard class="art-table-card" shadow="never">
      <div class="flex flex-col gap-4">
        <ElForm :model="filters" inline class="flex flex-wrap gap-4">
          <ElFormItem :label="t('announcement.search.status')">
            <ElSelect
              v-model="filters.status"
              clearable
              class="w-48"
              :placeholder="t('announcement.search.statusPlaceholder')"
            >
              <ElOption
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>

          <ElFormItem :label="t('announcement.search.keyword')">
            <ElInput
              v-model="filters.keyword"
              clearable
              class="w-64"
              :placeholder="t('announcement.search.keywordPlaceholder')"
            />
          </ElFormItem>

          <ElFormItem :label="t('announcement.search.dateRange')">
            <ElDatePicker
              v-model="filters.dateRange"
              type="daterange"
              unlink-panels
              range-separator="-"
              class="w-[320px]"
              :value-format="dateTimeFormat"
              :start-placeholder="t('announcement.search.dateRangeStart')"
              :end-placeholder="t('announcement.search.dateRangeEnd')"
            />
          </ElFormItem>

          <ElFormItem>
            <ElButton type="primary" @click="handleSearch">
              {{ t('table.searchBar.search') }}
            </ElButton>
            <ElButton @click="handleReset">
              {{ t('table.searchBar.reset') }}
            </ElButton>
          </ElFormItem>
        </ElForm>

        <div class="flex flex-wrap items-center justify-between gap-3">
          <div class="text-sm text-[var(--el-text-color-secondary)]">
            {{ t('announcement.list.total', { total: pagination.totalCount }) }}
          </div>

          <div class="flex items-center gap-2">
            <ElButton type="primary" @click="handleCreate">
              {{ t('announcement.action.create') }}
            </ElButton>
            <ElButton @click="handleRefresh">
              {{ t('announcement.action.refresh') }}
            </ElButton>
          </div>
        </div>
      </div>

      <ElTable class="mt-4" row-key="id" stripe border :data="announcements" v-loading="loading">
        <ElTableColumn type="index" width="60" :label="t('table.column.index')" />

        <ElTableColumn
          prop="title"
          min-width="220"
          :label="t('announcement.table.title')"
          show-overflow-tooltip
        />

        <ElTableColumn min-width="180" :label="t('announcement.table.type')">
          <template #default="{ row }">
            {{ getTypeLabel(row.announcementType) }}
          </template>
        </ElTableColumn>

        <ElTableColumn min-width="100" :label="t('announcement.table.priority')">
          <template #default="{ row }">
            {{ row.priority }}
          </template>
        </ElTableColumn>

        <ElTableColumn min-width="120" :label="t('announcement.table.status')">
          <template #default="{ row }">
            <ElTag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn min-width="220" :label="t('announcement.table.effectiveRange')">
          <template #default="{ row }">
            <div class="flex flex-col">
              <span>{{ formatDateTime(row.effectiveFrom) }}</span>
              <span class="text-xs text-[var(--el-text-color-secondary)]">
                {{ resolveEffectiveTo(row.effectiveTo) }}
              </span>
            </div>
          </template>
        </ElTableColumn>

        <ElTableColumn min-width="180" :label="t('announcement.table.publishedAt')">
          <template #default="{ row }">
            {{ formatDateTime(row.publishedAt) }}
          </template>
        </ElTableColumn>

        <ElTableColumn fixed="right" min-width="320" :label="t('announcement.table.actions')">
          <template #default="{ row }">
            <div class="flex flex-wrap items-center gap-2">
              <ElButton size="small" @click="handleDetail(row)">
                {{ t('announcement.action.detail') }}
              </ElButton>

              <ElButton
                size="small"
                :disabled="resolveStatus(row.status) !== 'Draft'"
                @click="handleEdit(row)"
              >
                {{ t('announcement.action.edit') }}
              </ElButton>

              <ElButton
                size="small"
                type="success"
                :disabled="resolveStatus(row.status) !== 'Draft'"
                @click="handlePublish(row)"
              >
                {{ t('announcement.action.publish') }}
              </ElButton>

              <ElButton
                size="small"
                type="warning"
                :disabled="resolveStatus(row.status) !== 'Published'"
                @click="handleRevoke(row)"
              >
                {{ t('announcement.action.revoke') }}
              </ElButton>

              <ElTooltip :content="t('announcement.message.deleteNotSupported')">
                <ElButton size="small" type="danger" disabled>
                  {{ t('announcement.action.delete') }}
                </ElButton>
              </ElTooltip>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>

      <div class="flex justify-end pt-4">
        <ElPagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="pageSizeOptions"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { useRouter } from 'vue-router'
  import { storeToRefs } from 'pinia'
  import {
    ElButton,
    ElCard,
    ElDatePicker,
    ElForm,
    ElFormItem,
    ElInput,
    ElMessage,
    ElMessageBox,
    ElOption,
    ElPagination,
    ElSelect,
    ElTable,
    ElTableColumn,
    ElTag,
    ElTooltip
  } from 'element-plus'
  import { useAnnouncementStore } from '@/store/modules/announcement'
  import { normalizeAnnouncementStatus } from '@/utils/announcementStatus'
  import type {
    AnnouncementQueryParams,
    AnnouncementStatus,
    AnnouncementStatusOption,
    TenantAnnouncementDto,
    TenantAnnouncementType
  } from '@/types/announcement'
  import { TenantAnnouncementType as TenantAnnouncementTypeEnum } from '@/types/announcement'

  defineOptions({ name: 'PlatformAnnouncementList' })

  const { t } = useI18n()
  const router = useRouter()

  // 1. 初始化公告状态与分页信息
  const announcementStore = useAnnouncementStore()
  const { announcements, pagination, loading } = storeToRefs(announcementStore)

  // 2. 查询筛选条件（状态/关键词/日期范围）
  const filters = reactive({
    status: undefined as AnnouncementStatus | undefined,
    keyword: '',
    dateRange: [] as [string, string] | []
  })

  // 3. 日期格式与分页选项
  const dateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
  const pageSizeOptions = [10, 20, 50, 100]

  // 4. 状态/类型选项（基于枚举与国际化）
  const statusOptions = computed<AnnouncementStatusOption[]>(() => [
    { label: t('announcement.status.draft'), value: 'Draft' },
    { label: t('announcement.status.published'), value: 'Published' },
    { label: t('announcement.status.revoked'), value: 'Revoked' }
  ])

  // 5. 构建查询参数
  const buildQueryParams = (): AnnouncementQueryParams => {
    const hasRange = filters.dateRange.length === 2
    const [dateFrom, dateTo] = hasRange ? filters.dateRange : [undefined, undefined]

    return {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      status: filters.status,
      keyword: filters.keyword.trim() || undefined,
      dateFrom,
      dateTo
    }
  }

  const handleSearch = () => {
    // 1. 重置分页到首页
    pagination.value.page = 1

    // 2. 执行查询
    void fetchList()
  }

  const handleReset = () => {
    // 1. 清空筛选条件
    filters.status = undefined
    filters.keyword = ''
    filters.dateRange = []

    // 2. 重新加载列表
    handleSearch()
  }

  const handleRefresh = () => {
    // 1. 保持当前分页刷新
    void fetchList()
  }

  const handlePageChange = (page: number) => {
    // 1. 更新页码并重新查询
    pagination.value.page = page
    void fetchList()
  }

  const handleSizeChange = (pageSize: number) => {
    // 1. 更新分页大小并回到第一页
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    void fetchList()
  }

  const handleCreate = () => {
    // 1. 跳转创建页面
    void router.push('/platform/announcements/create')
  }

  const handleDetail = (row: TenantAnnouncementDto) => {
    // 1. 跳转详情页面
    void router.push(`/platform/announcements/${row.id}`)
  }

  const handleEdit = (row: TenantAnnouncementDto) => {
    // 1. 跳转编辑页面
    void router.push(`/platform/announcements/${row.id}/edit`)
  }

  const confirmAction = async (message: string) => {
    try {
      // 1. 弹出二次确认
      await ElMessageBox.confirm(message, t('common.tips'), {
        type: 'warning',
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel')
      })

      return true
    } catch {
      return false
    }
  }

  const handlePublish = async (row: TenantAnnouncementDto) => {
    // 1. 校验 RowVersion
    if (!row.rowVersion) {
      ElMessage.error(t('announcement.message.rowVersionMissing'))
      return
    }

    // 2. 二次确认发布
    const confirmed = await confirmAction(t('announcement.message.publishConfirm'))
    if (!confirmed) {
      return
    }

    try {
      // 3. 调用发布接口
      const result = await announcementStore.publishAnnouncement(row.id, row.rowVersion, {
        scope: 'platform'
      })

      if (result) {
        ElMessage.success(t('announcement.message.publishSuccess'))
      }
    } catch {
      ElMessage.error(t('announcement.message.publishFailed'))
    }
  }

  const handleRevoke = async (row: TenantAnnouncementDto) => {
    // 1. 校验 RowVersion
    if (!row.rowVersion) {
      ElMessage.error(t('announcement.message.rowVersionMissing'))
      return
    }

    // 2. 二次确认撤销
    const confirmed = await confirmAction(t('announcement.message.revokeConfirm'))
    if (!confirmed) {
      return
    }

    try {
      // 3. 调用撤销接口
      const result = await announcementStore.revokeAnnouncement(row.id, row.rowVersion, {
        scope: 'platform'
      })

      if (result) {
        ElMessage.success(t('announcement.message.revokeSuccess'))
      }
    } catch {
      ElMessage.error(t('announcement.message.revokeFailed'))
    }
  }

  const fetchList = async () => {
    try {
      // 1. 构建查询参数
      const params = buildQueryParams()

      // 2. 调用 Store 拉取平台公告列表
      await announcementStore.fetchAnnouncements(params, { scope: 'platform' })
    } catch {
      ElMessage.error(t('announcement.message.loadFailed'))
    }
  }

  const resolveStatus = (status: unknown) => normalizeAnnouncementStatus(status)
  const getStatusLabel = (status: AnnouncementStatus) => {
    switch (resolveStatus(status)) {
      case 'Draft':
        return t('announcement.status.draft')
      case 'Published':
        return t('announcement.status.published')
      case 'Revoked':
        return t('announcement.status.revoked')
      default:
        return t('announcement.status.unknown')
    }
  }

  const getStatusTagType = (status: AnnouncementStatus) => {
    switch (resolveStatus(status)) {
      case 'Draft':
        return 'info'
      case 'Published':
        return 'success'
      case 'Revoked':
        return 'danger'
      default:
        return 'info'
    }
  }

  const getTypeLabel = (type: TenantAnnouncementType) => {
    switch (type) {
      case TenantAnnouncementTypeEnum.System:
        return t('announcement.type.system')
      case TenantAnnouncementTypeEnum.Billing:
        return t('announcement.type.billing')
      case TenantAnnouncementTypeEnum.Operation:
        return t('announcement.type.operation')
      case TenantAnnouncementTypeEnum.SYSTEM_PLATFORM_UPDATE:
        return t('announcement.type.platformUpdate')
      case TenantAnnouncementTypeEnum.SYSTEM_SECURITY_NOTICE:
        return t('announcement.type.security')
      case TenantAnnouncementTypeEnum.SYSTEM_COMPLIANCE:
        return t('announcement.type.compliance')
      case TenantAnnouncementTypeEnum.TENANT_INTERNAL:
        return t('announcement.type.tenantInternal')
      case TenantAnnouncementTypeEnum.TENANT_FINANCE:
        return t('announcement.type.tenantFinance')
      case TenantAnnouncementTypeEnum.TENANT_OPERATION:
        return t('announcement.type.tenantOperation')
      default:
        return t('announcement.type.unknown')
    }
  }

  const formatDateTime = (value?: string | null) => {
    if (!value) {
      return t('announcement.common.empty')
    }

    const date = new Date(value)
    if (Number.isNaN(date.getTime())) {
      return value
    }

    return date.toLocaleString()
  }

  const resolveEffectiveTo = (value?: string | null) => {
    if (!value) {
      return t('announcement.table.effectiveOpenEnded')
    }

    return formatDateTime(value)
  }

  onMounted(() => {
    // 1. 首次进入加载列表
    void fetchList()
  })
</script>
