<template>
  <div class="works-detail-page">
    <a-card class="mb-4">
      <template #title>
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link :to="`/${tenantCode}/contests/works`">作品管理</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ contestName || '参赛作品' }}</a-breadcrumb-item>
        </a-breadcrumb>
      </template>
      <template #extra>
        <a-button
          type="primary"
          :disabled="selectedRowKeys.length === 0"
          @click="handleBatchAssign"
        >
          分配评委
        </a-button>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item :label="contestType === 'team' ? '队伍名称' : '选手名称'">
        <a-input
          v-model:value="searchParams.name"
          :placeholder="
            contestType === 'team' ? '请输入队伍名称' : '请输入选手名称'
          "
          allow-clear
          style="width: 150px"
        />
      </a-form-item>
      <a-form-item label="报名账号">
        <a-input
          v-model:value="searchParams.username"
          placeholder="请输入报名账号"
          allow-clear
          style="width: 150px"
        />
      </a-form-item>
      <a-form-item label="作品编号">
        <a-input
          v-model:value="searchParams.workNo"
          placeholder="请输入作品编号"
          allow-clear
          style="width: 150px"
        />
      </a-form-item>
      <a-form-item label="分配状态">
        <a-select
          v-model:value="searchParams.assignStatus"
          placeholder="请选择"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="assigned">已分配</a-select-option>
          <a-select-option value="unassigned">未分配</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="递交时间">
        <a-range-picker
          v-model:value="searchParams.submitTimeRange"
          style="width: 240px"
        />
      </a-form-item>
      <a-form-item label="机构">
        <a-select
          v-model:value="searchParams.tenantId"
          placeholder="请选择机构"
          allow-clear
          style="width: 150px"
          show-search
          :filter-option="filterOption"
        >
          <a-select-option
            v-for="tenant in tenants"
            :key="tenant.id"
            :value="tenant.id"
          >
            {{ tenant.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button style="margin-left: 8px" @click="handleReset">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      :row-selection="rowSelection"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.key === 'workNo'">
          <a @click="handleViewWork(record)">{{ record.workNo || "-" }}</a>
        </template>
        <template v-else-if="column.key === 'username'">
          {{
            record.submitterAccountNo ||
            record.registration?.user?.username ||
            "-"
          }}
        </template>
        <template v-else-if="column.key === 'name'">
          <template v-if="contestType === 'team'">
            {{ record.registration?.team?.teamName || "-" }}
          </template>
          <template v-else>
            {{ record.registration?.user?.nickname || "-" }}
          </template>
        </template>
        <template v-else-if="column.key === 'submitTime'">
          {{ formatDate(record.submitTime) }}
        </template>
        <template v-else-if="column.key === 'assignStatus'">
          <a-tag v-if="record._count?.assignments > 0" color="success"
            >已分配</a-tag
          >
          <a-tag v-else color="default">未分配</a-tag>
        </template>
        <template v-else-if="column.key === 'judges'">
          <template v-if="record.assignments && record.assignments.length > 0">
            <a-space wrap>
              <a-tag
                v-for="assignment in record.assignments"
                :key="assignment.id"
              >
                {{
                  assignment.judge?.nickname ||
                  assignment.judge?.username ||
                  "-"
                }}
              </a-tag>
            </a-space>
          </template>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" size="small" @click="handleAssignJudge(record)">
            分配评委
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 作品详情弹框 -->
    <WorkDetailModal
      v-model:open="workModalVisible"
      :work-id="currentWorkId"
    />

    <!-- 分配评委抽屉 -->
    <a-drawer
      v-model:open="assignModalVisible"
      title="分配评委"
      placement="right"
      width="800px"
      :footer-style="{ textAlign: 'right' }"
      @close="handleAssignDrawerClose"
    >
      <div class="assign-judge-drawer">
        <!-- 搜索区域 -->
        <a-card class="mb-4" size="small">
          <a-form layout="inline" :model="judgeSearchParams" @finish="handleSearchJudges">
            <a-form-item label="姓名">
              <a-input
                v-model:value="judgeSearchParams.nickname"
                placeholder="请输入姓名"
                allow-clear
                style="width: 150px"
                @press-enter="handleSearchJudges"
              />
            </a-form-item>
            <a-form-item label="所属单位">
              <a-input
                v-model:value="judgeSearchParams.tenantName"
                placeholder="请输入所属单位"
                allow-clear
                style="width: 200px"
                @press-enter="handleSearchJudges"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button style="margin-left: 8px" @click="handleResetJudgeSearch">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 全部评委列表 -->
        <a-card class="mb-4" size="small">
          <template #title>全部评委</template>
          <a-table
            :columns="judgeColumns"
            :data-source="judgeList"
            :loading="judgeListLoading"
            :pagination="judgePagination"
            :row-selection="{
              selectedRowKeys: selectedJudgeKeys,
              onChange: handleJudgeSelectionChange,
            }"
            row-key="id"
            size="small"
            @change="handleJudgeTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'judgeName'">
                {{ record.judge?.nickname || record.judge?.username || "-" }}
              </template>
              <template v-else-if="column.key === 'phone'">
                {{ record.judge?.phone || "-" }}
              </template>
              <template v-else-if="column.key === 'tenant'">
                {{ record.judge?.organization || record.judge?.tenant?.name || "-" }}
              </template>
              <template v-else-if="column.key === 'assignedCount'">
                {{ record._count?.assignedContestWorks || 0 }}
              </template>
            </template>
          </a-table>
        </a-card>

        <!-- 已选评委区域 -->
        <a-card size="small">
          <template #title>
            已选 {{ selectedJudgeRows.length }} 位评委
          </template>
          <a-list
            :data-source="selectedJudgeRows"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    {{ item.judge?.nickname || item.judge?.username || "-" }}
                  </template>
                  <template #description>
                    {{ item.judge?.organization || item.judge?.tenant?.name || "-" }}
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button
                    type="link"
                    danger
                    size="small"
                    @click="handleRemoveSelectedJudge(item.id)"
                  >
                    移除
                  </a-button>
                </template>
              </a-list-item>
            </template>
            <template #empty>
              <a-empty description="暂未选择评委" :image="false" />
            </template>
          </a-list>
        </a-card>

        <!-- 底部操作按钮 -->
        <div class="drawer-footer">
          <a-space>
            <a-button @click="handleAssignDrawerClose">取消</a-button>
            <a-button
              type="primary"
              :loading="assignLoading"
              :disabled="selectedJudgeRows.length === 0"
              @click="handleConfirmAssign"
            >
              确定
            </a-button>
          </a-space>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRoute, useRouter } from "vue-router"
import { message } from "ant-design-vue"
import type { TableProps } from "ant-design-vue"
import type { Dayjs } from "dayjs"
import {
  ArrowLeftOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue"
import dayjs from "dayjs"
import {
  contestsApi,
  worksApi,
  reviewsApi,
  judgesApi,
  type ContestWork,
  type ContestJudge,
} from "@/api/contests"
import WorkDetailModal from "../components/WorkDetailModal.vue"

interface Tenant {
  id: number
  name: string
}

const route = useRoute()
const router = useRouter()
const tenantCode = route.params.tenantCode as string
const contestId = Number(route.params.id)
const contestType = (route.query.type as string) || "individual"

// 活动名称
const contestName = ref("")

// 租户列表
const tenants = ref<Tenant[]>([])

// 列表状态
const loading = ref(false)
const dataSource = ref<ContestWork[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// 搜索参数
const searchParams = reactive({
  name: "",
  username: "",
  workNo: "",
  assignStatus: undefined as string | undefined,
  submitTimeRange: null as [Dayjs, Dayjs] | null,
  tenantId: undefined as number | undefined,
})

// 选中的行
const selectedRowKeys = ref<number[]>([])
const selectedRows = ref<ContestWork[]>([])

// 行选择配置
const rowSelection = computed<TableProps["rowSelection"]>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any, rows: ContestWork[]) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  },
}))

// 表格列定义
const columns = computed(() => [
  { title: "序号", key: "index", width: 70 },
  { title: "作品编号", key: "workNo", width: 150 },
  { title: "报名账号", key: "username", width: 120 },
  {
    title: contestType === "team" ? "队伍名称" : "选手姓名",
    key: "name",
    width: 150,
  },
  { title: "递交时间", key: "submitTime", width: 160 },
  { title: "分配状态", key: "assignStatus", width: 100 },
  { title: "评委", key: "judges", width: 200 },
  { title: "操作", key: "action", width: 100, fixed: "right" as const },
])

// 作品详情弹框
const workModalVisible = ref(false)
const currentWorkId = ref<number | null>(null)

// 分配评委弹框
const assignModalVisible = ref(false)
const assignLoading = ref(false)
const currentAssignWork = ref<ContestWork | null>(null)
const isBatchAssign = ref(false)

// 评委列表
const judgeList = ref<ContestJudge[]>([])
const judgeListLoading = ref(false)
const judgePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})
const judgeSearchParams = reactive({
  nickname: "",
  tenantName: "",
})
const selectedJudgeKeys = ref<number[]>([])
const selectedJudgeRows = ref<ContestJudge[]>([])

// 评委选择变化
const handleJudgeSelectionChange = (selectedKeys: number[]) => {
  // 找出新增的评委
  const newSelectedIds = selectedKeys.filter(
    (id) => !selectedJudgeKeys.value.includes(id)
  )
  // 找出移除的评委
  const removedIds = selectedJudgeKeys.value.filter(
    (id) => !selectedKeys.includes(id)
  )

  // 更新已选评委ID列表
  selectedJudgeKeys.value = selectedKeys

  // 更新已选评委详情列表
  // 先移除被取消选择的
  selectedJudgeRows.value = selectedJudgeRows.value.filter(
    (judge) => !removedIds.includes(judge.id)
  )

  // 再添加新选择的（从当前页的评委列表中查找）
  const newSelectedJudges = judgeList.value.filter((judge) =>
    newSelectedIds.includes(judge.id)
  )
  selectedJudgeRows.value = [...selectedJudgeRows.value, ...newSelectedJudges]
}

// 移除已选评委
const handleRemoveSelectedJudge = (judgeId: number) => {
  selectedJudgeKeys.value = selectedJudgeKeys.value.filter((id) => id !== judgeId)
  selectedJudgeRows.value = selectedJudgeRows.value.filter(
    (judge) => judge.id !== judgeId
  )
}

// 评委表格列
const judgeColumns = [
  { title: "评委姓名", key: "judgeName", width: 120 },
  { title: "联系方式", key: "phone", width: 130 },
  { title: "机构", key: "tenant", width: 150 },
  { title: "已分配作品数", key: "assignedCount", width: 120 },
]

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm")
}

// 搜索选项过滤
const filterOption = (input: string, option: any) => {
  return option.children?.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 获取活动信息
const fetchContestInfo = async () => {
  try {
    const contest = await contestsApi.getDetail(contestId)
    contestName.value = contest.contestName
  } catch (error) {
    console.error("获取活动信息失败", error)
  }
}

// 获取租户列表
const fetchTenants = async () => {
  try {
    // TODO: 需要后端提供租户列表接口
    tenants.value = []
  } catch (error) {
    console.error("获取租户列表失败", error)
  }
}

// 获取作品列表
const fetchList = async () => {
  loading.value = true
  try {
    const response = await worksApi.getList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      contestId,
      workNo: searchParams.workNo || undefined,
      username: searchParams.username || undefined,
    })
    dataSource.value = response.list
    pagination.total = response.total
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取作品列表失败")
  } finally {
    loading.value = false
  }
}

// 获取活动评委列表
const fetchJudgeList = async () => {
  judgeListLoading.value = true
  try {
    const response = await judgesApi.getList(contestId)
    judgeList.value = response
    judgePagination.total = response.length
  } catch (error) {
    message.error("获取评委列表失败")
  } finally {
    judgeListLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

// 重置
const handleReset = () => {
  searchParams.name = ""
  searchParams.username = ""
  searchParams.workNo = ""
  searchParams.assignStatus = undefined
  searchParams.submitTimeRange = null
  searchParams.tenantId = undefined
  pagination.current = 1
  fetchList()
}

// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchList()
}

// 返回
const handleBack = () => {
  router.back()
}

// 查看作品详情
const handleViewWork = (record: ContestWork) => {
  currentWorkId.value = record.id
  workModalVisible.value = true
}

// 单个分配评委
const handleAssignJudge = (record: ContestWork) => {
  currentAssignWork.value = record
  isBatchAssign.value = false
  selectedJudgeKeys.value = []
  selectedJudgeRows.value = []
  assignModalVisible.value = true
  fetchJudgeList()
}

// 批量分配评委
const handleBatchAssign = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning("请先选择作品")
    return
  }
  isBatchAssign.value = true
  selectedJudgeKeys.value = []
  selectedJudgeRows.value = []
  assignModalVisible.value = true
  fetchJudgeList()
}

// 关闭分配评委抽屉
const handleAssignDrawerClose = () => {
  assignModalVisible.value = false
  selectedJudgeKeys.value = []
  selectedJudgeRows.value = []
  currentAssignWork.value = null
}

// 搜索评委
const handleSearchJudges = () => {
  judgePagination.current = 1
  fetchJudgeList()
}

// 重置评委搜索
const handleResetJudgeSearch = () => {
  judgeSearchParams.nickname = ""
  judgeSearchParams.tenantName = ""
  judgePagination.current = 1
  fetchJudgeList()
}

// 评委表格分页变化
const handleJudgeTableChange = (pag: any) => {
  judgePagination.current = pag.current
  judgePagination.pageSize = pag.pageSize
  fetchJudgeList()
}

// 确认分配评委
const handleConfirmAssign = async () => {
  if (selectedJudgeRows.value.length === 0) {
    message.warning("请选择评委")
    return
  }

  assignLoading.value = true
  try {
    const judgeIds = selectedJudgeRows.value.map((j) => j.judgeId)

    if (isBatchAssign.value) {
      // 批量分配
      await reviewsApi.batchAssignWorks(contestId, {
        workIds: selectedRowKeys.value,
        judgeIds,
      })
      message.success("批量分配成功")
      selectedRowKeys.value = []
      selectedRows.value = []
    } else if (currentAssignWork.value) {
      // 单个分配
      await reviewsApi.assignWork(contestId, {
        workId: currentAssignWork.value.id,
        judgeIds,
      })
      message.success("分配成功")
    }

    assignModalVisible.value = false
    fetchList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "分配失败")
  } finally {
    assignLoading.value = false
  }
}

onMounted(() => {
  fetchContestInfo()
  fetchTenants()
  fetchList()
})
</script>

<style scoped lang="scss">
$primary: #1890ff;
$primary-dark: #0958d9;
$gradient-primary: linear-gradient(135deg, $primary 0%, $primary-dark 100%);

.works-detail-page {
  :deep(.ant-card) {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;

    .ant-card-head {
      border-bottom: none;
      padding: 16px 24px;

      .ant-card-head-title {
        font-size: 18px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .ant-card-body {
      padding: 0;
    }
  }

  :deep(.ant-btn-primary) {
    background: $gradient-primary;
    border: none;
    box-shadow: 0 4px 12px rgba($primary, 0.35);
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(135deg, $primary-dark 0%, darken($primary-dark, 8%) 100%);
      box-shadow: 0 6px 16px rgba($primary, 0.45);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }

  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .ant-table {
      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-tbody > tr {
        transition: all 0.2s ease;

        &:hover > td {
          background: rgba($primary, 0.04);
        }

        > td {
          border-bottom: 1px solid #f5f5f5;
        }
      }
    }

    .ant-table-pagination {
      padding: 16px;
      margin: 0;
    }
  }
}

.search-form {
  margin-bottom: 16px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 16px 24px;

  :deep(.ant-form-item) {
    margin-bottom: 0;
    margin-right: 0;
  }
}

.mb-3 {
  margin-bottom: 12px;
}

.mb-4 {
  margin-bottom: 16px;
}

.ml-2 {
  margin-left: 8px;
}

.assign-judge-drawer {
  .drawer-footer {
    position: sticky;
    bottom: 0;
    padding: 16px 0;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    margin-top: 16px;
    text-align: right;
  }
}
</style>
