<!-- views/backend/official/index.vue -->
<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="flex-1 flex gap-2">
        <el-input
          v-model="searchParams.title"
          placeholder="请输入栏目标题"
          class="w-200px"
        ></el-input>

        <!-- 审核状态 -->
        <el-select
          v-model="searchParams.isAudit"
          placeholder="请选择审核状态"
          class="search-select"
          clearable
        >
          <el-option
            v-for="item in auditTypeListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 发布状态 -->
        <el-select
          v-model="searchParams.isUse"
          placeholder="请选择发布状态"
          class="search-select"
          clearable
        >
          <el-option
            v-for="item in usageStatusListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <div>
          <el-button type="primary" @click="refresh">
            <el-icon><IEpSearch /></el-icon>
            搜索</el-button
          >
          <el-button @click="reset">重置</el-button>
        </div>
      </div>

      <div class="flex justify-end">
        <UploadExcel :api="importCaseExcel" @success="refresh" @error="handleError" />
        <el-button type="primary" @click="handleBatchPublish"> 批量发布/隐藏 </el-button>
        <el-button type="danger" @click="handleBatchDelete"> 批量删除 </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="list"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="来源渠道（选填）" align="center">
            <el-table-column label="来源对象" align="center">
              <el-table-column prop="sourceUserWorkNo" label="工号" width="120"></el-table-column>
              <el-table-column prop="sourceUserName" label="姓名" width="120"></el-table-column>
              <el-table-column prop="level" label="层级" width="120"></el-table-column>
            </el-table-column>
            <el-table-column prop="sourceProject" label="来源项目" width="120"></el-table-column>
            <el-table-column prop="sourceType" label="来源类型" width="120"></el-table-column>
            <el-table-column prop="sourceTime" label="来源时间" width="170">
              <template #default="{ row }">
                {{ dayjs(row.sourceTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column prop="detail3" label="上传人" width="120"></el-table-column>
          </el-table-column>
          <el-table-column prop="number" label="案例编号" width="90"></el-table-column>

          <el-table-column prop="title" label="案例标题" width="200"></el-table-column>

          <!-- 内容过多加入tooltip -->
          <el-table-column prop="content" label="案例文本内容" width="300">
            <template #default="{ row }">
              <!-- 省略号 -->
              <div class="line-clamp-1 text-blue-500 cursor-pointer" @click="handleContent(row)">
                {{ row.content }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="文化关键词" align="center">
            <el-table-column prop="cultureKeywordMain" label="主关键词" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.cultureKeywordMain[0]" type="primary">
                  {{ row.cultureKeywordMain[0].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="cultureKeywordSecond" label="次关键词1" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.cultureKeywordSecond[0]" type="primary">
                  {{ row.cultureKeywordSecond[0].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="cultureKeywordSecond" label="次关键词2" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.cultureKeywordSecond[1]" type="primary">
                  {{ row.cultureKeywordSecond[1].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="cultureKeywordSecond" label="次关键词3" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.cultureKeywordSecond[2]" type="primary">
                  {{ row.cultureKeywordSecond[2].title }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="年度主推关键词（选填）" align="center">
            <el-table-column prop="yearKeywordMain" label="主关键词" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.yearKeywordMain[0]" type="primary">
                  {{ row.yearKeywordMain[0].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="yearKeywordSecond" label="次关键词" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.yearKeywordSecond[0]" type="primary">
                  {{ row.yearKeywordSecond[0].title }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="关联场景" align="center">
            <el-table-column label="主关键词" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.sceneKeywordMain[0]" type="primary">
                  {{ row.sceneKeywordMain[0].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="abnormalReason" label="次关键词1" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.sceneKeywordSecond[0]" type="primary">
                  {{ row.sceneKeywordSecond[0].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="abnormalReason" label="次关键词2" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.sceneKeywordSecond[1]" type="primary">
                  {{ row.sceneKeywordSecond[1].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="abnormalReason" label="次关键词3" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.sceneKeywordSecond[2]" type="primary">
                  {{ row.sceneKeywordSecond[2].title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="abnormalReason" label="次关键词4" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.sceneKeywordSecond[3]" type="primary">
                  {{ row.sceneKeywordSecond[3].title }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="关联部门（选填）" align="center">
            <el-table-column label="部门1" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.depNameList[0]" type="primary">
                  {{ row.depNameList[0] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="taxBracket2" label="部门2" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.depNameList[1]" type="primary">
                  {{ row.depNameList[1] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="taxBracket3" label="部门3" width="160">
              <template #default="{ row }">
                <el-tag v-if="row.depNameList[2]" type="primary">
                  {{ row.depNameList[2] }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="caseType" label="案例类型" width="120"></el-table-column>

          <el-table-column label="案例评分级别" align="center">
            <el-table-column prop="taxBracket1" label="案例完整性" width="120"></el-table-column>
            <el-table-column prop="taxBracket2" label="企业文化关联" width="120"></el-table-column>
          </el-table-column>

          <el-table-column label="审核状态" width="160" fixed="right">
            <template #default="{ row }">
              <!-- 下拉框 -->
              <el-select
                :modelValue="row.isAudit"
                @update:modelValue="handleAuditStatusChange(row, $event)"
                placeholder="选择审核状态"
              >
                <el-option
                  v-for="item in auditTypeListOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="应用状态" width="160" fixed="right">
            <template #header
              >应用状态
              <el-tooltip content="只有已通过的才能修改应用状态" placement="top">
                <el-icon><IEpInfoFilled /></el-icon>
              </el-tooltip>
            </template>
            <template #default="{ row }">
              <el-select
                :modelValue="row.isUse"
                @update:modelValue="handleUsageStatusChange(row, $event)"
                placeholder="选择应用状态"
                :disabled="row.isAudit !== AuditStatusEnum.AGREED"
              >
                <el-option
                  v-for="item in usageStatusListOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <!-- <el-button type="danger" link @click="handleDelete(row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          :total="total"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="changePageSize"
          @current-change="goToPage"
        />
      </div>
    </div>

    <ErrorListDialog v-model:visible="errorListDialogVisible" :errorList="errorList" />
    <EditDialog ref="editDialogRef" @refresh="refresh" />
  </div>
</template>

<script setup lang="ts">
import { usePageSearch } from '@/hooks'
import {
  getCaseList,
  deleteColumn,
  hideColumn,
  changeUsageStatus,
  auditCase,
  importCaseExcel,
} from '@/api/backend'
import type { BackendCaseListItemDto } from '@/api/backend'
import {
  usageStatusListOptions,
  auditTypeListOptions,
  AuditStatusEnum,
  UsageStatusEnum,
} from '@/constants'
import UploadExcel from '@/components/common/UploadExcel/index.vue'
import dayjs from 'dayjs'
import ErrorListDialog from './components/errorListDialog.vue'
import EditDialog from './components/editDialog.vue'

const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams } =
  usePageSearch(getCaseList, {
    defaultParams: {},
  })

const editDialogRef = useTemplateRef<InstanceType<typeof EditDialog>>('editDialogRef')

// 编辑
const handleEdit = async (row: BackendCaseListItemDto) => {
  // 已使用的状态 不允许编辑
  if (row.isUse === UsageStatusEnum.USED) return ElMessage.warning('已使用的状态 不允许编辑')
  // 审核通过再编辑
  if (row.isAudit === AuditStatusEnum.AGREED) {
    await ElMessageBox.confirm('案例库已审核通过，修改后需重新审核，点击确定继续编辑', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  }

  editDialogRef.value?.open(row)
}

const selectedRows = ref<BackendCaseListItemDto[]>([])
// 选择
const handleSelectionChange = (selection: BackendCaseListItemDto[]) => {
  selectedRows.value = selection
}

// 批量发布/隐藏
const handleBatchPublish = async () => {
  await hideColumn(selectedRows.value.map((item) => item.id))
  refresh()
  selectedRows.value = []
  ElMessage.success('发布/隐藏成功')
}

// 批量删除
const handleBatchDelete = async () => {
  await deleteColumn(selectedRows.value.map((item) => item.id))
  refresh()
  selectedRows.value = []
  ElMessage.success('删除成功')
}

const handleContent = (row: BackendCaseListItemDto) => {
  ElMessageBox.alert(row.content, '案例全部文本内容', {
    confirmButtonText: '确定',
  })
}

const handleAuditStatusChange = async (row: BackendCaseListItemDto, value: number) => {
  await auditCase({
    id: row.id,
    isAudit: value,
  })
  ElMessage.success('审核成功')
  row.isAudit = value
}

const handleUsageStatusChange = async (row: BackendCaseListItemDto, value: number) => {
  await changeUsageStatus({
    id: row.id,
    isUse: value,
  })
  ElMessage.success('使用状态修改成功')
  refresh()
  row.isUse = value
}

/**
 * 关于上传文件的错误处理
 */
const errorListDialogVisible = ref(false)
const errorList = ref<BackendCaseListItemDto[]>([])
const handleError = (list: BackendCaseListItemDto[]) => {
  errorListDialogVisible.value = true
  errorList.value = list
}
</script>

<style scoped lang="scss">
.official-tag-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 搜索区域
.search-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  gap: 12px;
  flex-shrink: 0;

  .search-select {
    width: 200px;
  }
}

// 表格区域
.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  min-height: 0;

  .color-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .color-block {
      width: 100%;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      flex: 1;
    }

    .color-text {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  flex-shrink: 0;
}

// 对话框内的颜色显示
.color-value {
  margin-left: 12px;
  color: #606266;
  font-family: monospace;
}

.btn-icon {
  margin-right: 4px;
}
</style>
