<template>
  <div class="add-judge-drawer">
    <!-- 搜索区域 -->
    <a-card class="mb-4" size="small">
      <a-form layout="inline" :model="searchParams" @finish="handleSearch">
        <a-form-item label="姓名">
          <a-input
            v-model:value="searchParams.nickname"
            placeholder="请输入姓名"
            allow-clear
            style="width: 150px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="所属单位">
          <a-input
            v-model:value="searchParams.organization"
            placeholder="请输入所属单位"
            allow-clear
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </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-card>

    <!-- 全部评委列表 -->
    <a-card class="mb-4" size="small">
      <template #title>全部评委</template>
      <a-table
        :columns="judgeColumns"
        :data-source="judgeList"
        :loading="judgeLoading"
        :pagination="judgePagination"
        :row-selection="{
          selectedRowKeys: selectedJudgeIds,
          onChange: handleJudgeSelectionChange,
          getCheckboxProps: (record: Judge) => ({
            disabled: isJudgeSelected(record.id),
          }),
        }"
        row-key="id"
        size="small"
        @change="handleJudgeTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'organization'">
            {{ record.organization || "-" }}
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'enabled' ? 'success' : 'error'">
              {{ record.status === "enabled" ? "启用" : "停用" }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 已选评委区域 -->
    <a-card size="small">
      <template #title>
        已选 {{ selectedJudges.length }} / {{ judgeCount || 0 }}
        <span
          v-if="selectedJudges.length > (judgeCount || 0)"
          class="warning-text"
        >
          （超出{{ selectedJudges.length - (judgeCount || 0) }}人）
        </span>
      </template>
      <a-list
        :data-source="selectedJudges"
        :loading="selectedJudgesLoading"
        size="small"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>
                {{ item.nickname }}（{{ item.username }}）
              </template>
              <template #description>
                {{ item.organization || "-" }}
              </template>
            </a-list-item-meta>
            <template #actions>
              <a-button
                type="link"
                danger
                size="small"
                @click="handleRemoveJudge(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="handleCancel">取消</a-button>
        <a-button
          type="primary"
          :loading="submitLoading"
          :disabled="selectedJudges.length === 0"
          @click="handleSubmit"
        >
          确定
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue"
import { message } from "ant-design-vue"
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons-vue"
import type { Judge, QueryJudgeParams } from "@/api/judges-management"
import { judgesManagementApi } from "@/api/judges-management"
import { judgesApi } from "@/api/contests"
import type { Contest } from "@/api/contests"

interface Props {
  contestId: number
  contest: Contest
}

const props = defineProps<Props>()
const emit = defineEmits<{
  success: []
}>()

// 评委数量（从评审规则中获取）
const judgeCount = computed(() => {
  return props.contest.reviewRule?.judgeCount || 0
})

// 搜索参数
const searchParams = reactive<QueryJudgeParams>({
  page: 1,
  pageSize: 10,
  nickname: undefined,
  organization: undefined,
})

// 全部评委列表
const judgeList = ref<Judge[]>([])
const judgeLoading = ref(false)
const judgePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

// 已选评委
const selectedJudgeIds = ref<number[]>([])
const selectedJudges = ref<Judge[]>([])
const selectedJudgesLoading = ref(false)

// 提交加载状态
const submitLoading = ref(false)

// 表格列定义
const judgeColumns = [
  {
    title: "姓名",
    dataIndex: "nickname",
    key: "nickname",
    width: 120,
  },
  {
    title: "账号",
    dataIndex: "username",
    key: "username",
    width: 150,
  },
  {
    title: "所属单位",
    dataIndex: "organization",
    key: "organization",
    width: 150,
  },
  {
    title: "联系方式",
    dataIndex: "phone",
    key: "phone",
    width: 130,
  },
  {
    title: "状态",
    key: "status",
    width: 80,
  },
]

// 加载全部评委列表
const loadJudges = async () => {
  judgeLoading.value = true
  try {
    const params: QueryJudgeParams = {
      page: judgePagination.current,
      pageSize: judgePagination.pageSize,
      nickname: searchParams.nickname || undefined,
      organization: searchParams.organization || undefined,
    }
    const res = await judgesManagementApi.getList(params)
    judgeList.value = res.list
    judgePagination.total = res.total
  } catch (error: any) {
    message.error(error?.response?.data?.message || "加载评委列表失败")
  } finally {
    judgeLoading.value = false
  }
}

// 加载已选评委
const loadSelectedJudges = async () => {
  selectedJudgesLoading.value = true
  try {
    const judges = await judgesApi.getList(props.contestId)
    // 提取评委ID和评委信息
    const judgeIds = judges.map((j) => j.judgeId)
    selectedJudgeIds.value = judgeIds

    // 获取评委详细信息
    if (judgeIds.length > 0) {
      const judgeDetails = await Promise.all(
        judgeIds.map((id) => judgesManagementApi.getDetail(id))
      )
      selectedJudges.value = judgeDetails
    } else {
      selectedJudges.value = []
    }
  } catch (error: any) {
    message.error(error?.response?.data?.message || "加载已选评委失败")
  } finally {
    selectedJudgesLoading.value = false
  }
}

// 检查评委是否已选
const isJudgeSelected = (judgeId: number): boolean => {
  return selectedJudgeIds.value.includes(judgeId)
}

// 评委选择变化
const handleJudgeSelectionChange = (selectedKeys: number[]) => {
  // 找出新增的评委（在 selectedKeys 中但不在 selectedJudgeIds 中）
  const newSelectedIds = selectedKeys.filter(
    (id) => !selectedJudgeIds.value.includes(id)
  )

  // 找出移除的评委（在 selectedJudgeIds 中但不在 selectedKeys 中）
  const removedIds = selectedJudgeIds.value.filter(
    (id) => !selectedKeys.includes(id)
  )

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

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

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

// 移除评委
const handleRemoveJudge = (judgeId: number) => {
  selectedJudgeIds.value = selectedJudgeIds.value.filter((id) => id !== judgeId)
  selectedJudges.value = selectedJudges.value.filter(
    (judge) => judge.id !== judgeId
  )
}

// 搜索
const handleSearch = () => {
  judgePagination.current = 1
  loadJudges()
}

// 重置搜索
const handleReset = () => {
  searchParams.nickname = undefined
  searchParams.organization = undefined
  handleSearch()
}

// 表格变化
const handleJudgeTableChange = (pag: any) => {
  judgePagination.current = pag.current
  judgePagination.pageSize = pag.pageSize
  loadJudges()
}

// 提交
const handleSubmit = async () => {
  if (selectedJudges.value.length === 0) {
    message.warning("请至少选择一个评委")
    return
  }

  submitLoading.value = true
  try {
    // 获取当前已选评委ID
    const currentJudgeIds = await judgesApi
      .getList(props.contestId)
      .then((judges) => judges.map((j) => j.judgeId))

    // 找出需要添加的评委（新选中的，但之前未添加的）
    const toAddIds = selectedJudgeIds.value.filter(
      (id) => !currentJudgeIds.includes(id)
    )

    // 批量添加评委
    if (toAddIds.length > 0) {
      await Promise.all(
        toAddIds.map((judgeId) =>
          judgesApi.create({
            contestId: props.contestId,
            judgeId: judgeId,
          })
        )
      )
    }

    message.success("添加评委成功")
    emit("success")
  } catch (error: any) {
    message.error(error?.response?.data?.message || "添加评委失败")
  } finally {
    submitLoading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit("success")
}

// 监听搜索参数变化
watch(
  () => searchParams.nickname,
  () => {
    if (searchParams.nickname === undefined || searchParams.nickname === "") {
      handleSearch()
    }
  }
)

watch(
  () => searchParams.organization,
  () => {
    if (
      searchParams.organization === undefined ||
      searchParams.organization === ""
    ) {
      handleSearch()
    }
  }
)

onMounted(() => {
  loadJudges()
  loadSelectedJudges()
})
</script>

<style scoped lang="scss">
.add-judge-drawer {
  .warning-text {
    color: #ff4d4f;
    font-size: 12px;
  }

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