<template>
  <PageShell>
    <div class="apply-page">
      <div class="apply-card">
        <div class="apply-title">报名列表</div>

        <div class="apply-toolbar">
          <div class="apply-search-box">
            <el-input v-model="queryParams.keyword" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            <el-button type="primary" class="apply-search-button" @click="handleQuery">
              <el-icon><Search /></el-icon>
            </el-button>
          </div>

          <div class="apply-toolbar-actions">
            <el-button type="primary" plain @click="handleBack">返回</el-button>
            <el-button type="primary" plain @click="handleAddEmployee">添加员工</el-button>
            <el-button type="primary" @click="handleExport">导出列表</el-button>
          </div>
        </div>

        <el-table :data="pagedApplyList" class="apply-list-table" header-row-class-name="apply-table-header">
          <el-table-column label="姓名" prop="name" min-width="160">
            <template #default="{ row }">
              <el-button v-if="row.statusText !== '待测评'" link type="primary" @click="handleOpenDetail(row)">{{ row.name }}</el-button>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="gender" width="80" align="center" />
          <el-table-column label="手机号" prop="phone" min-width="160" align="center" />
          <el-table-column label="状态" min-width="160" align="center">
            <template #default="{ row }">
              <span class="apply-status-text">
                <span class="apply-status-dot" :class="`is-${row.statusType}`"></span>
                {{ row.statusText }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="测评时间" prop="evaluateTime" min-width="180" align="center" />
          <el-table-column label="操作" width="160" align="center">
            <template #default="{ row }">
              <el-button v-if="row.actionType === 'detail'" link type="primary" @click="handleOpenDetail(row)">测评详情</el-button>
              <el-button v-else link type="primary" @click="handleRemove(row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="handlePagination"
        />
      </div>

      <el-dialog v-model="syncDialog.visible" title="同步测评" width="460px" append-to-body>
        <div class="sync-dialog-content">
          <div class="sync-dialog-row">
            <span class="sync-dialog-label">同步员工</span>
            <el-select
              v-model="syncDialog.employeeIds"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              class="sync-dialog-select"
              :loading="syncOptionLoading"
            >
              <el-option v-for="item in employeeOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </div>
        </div>
        <template #footer>
          <div class="sync-dialog-footer">
            <el-button @click="syncDialog.visible = false">取消</el-button>
            <el-button type="primary" :loading="syncLoading" @click="handleConfirmSync">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </PageShell>
</template>

<script setup name="EvaluationApplyList" lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref, type ComponentInternalInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import PageShell from '@/components/PageShell/index.vue';
import { getEvaluationSyncEmployeeOptions, listEvaluationApply, removeEvaluationApply, syncEvaluationToEmployees } from '@/api/main/evaluation';
import type { EvaluationApplyRow, EvaluationSyncEmployeeOption } from '@/api/main/evaluation/types';

type SyncEmployeeOption = EvaluationSyncEmployeeOption & { label: string };

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const modal = proxy?.$modal as any;
const loading = ref(false);
const syncLoading = ref(false);
const syncOptionLoading = ref(false);
const employeeOptions = ref<SyncEmployeeOption[]>([]);
const syncDialog = reactive({
  visible: false,
  employeeIds: [] as Array<string | number>
});
const evaluationId = computed(() => String(route.query.evaluationId || ''));

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
});

const allApplyList = ref<EvaluationApplyRow[]>([]);
const total = ref(0);
const pagedApplyList = computed(() => allApplyList.value);

const loadSyncEmployeeOptions = async () => {
  syncOptionLoading.value = true;
  try {
    const res = await getEvaluationSyncEmployeeOptions();
    const rows = res.data || [];
    employeeOptions.value = rows.map((item) => ({
      ...item,
      label: [item.name, item.mobile, item.studentNo].filter(Boolean).join(' / ')
    }));
  } finally {
    syncOptionLoading.value = false;
  }
};

const getList = async () => {
  if (!evaluationId.value) {
    allApplyList.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    const res = await listEvaluationApply({
      evaluationId: evaluationId.value,
      keyword: queryParams.keyword.trim(),
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    });
    allApplyList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const handlePagination = () => {
  getList();
};

const handleAddEmployee = () => {
  syncDialog.employeeIds = [];
  syncDialog.visible = true;
  if (!employeeOptions.value.length) {
    loadSyncEmployeeOptions();
  }
};

const handleExport = () => {
  if (!evaluationId.value) {
    modal?.msgWarning('测评ID不能为空');
    return;
  }
  proxy?.download(
    '/main/examEvaluation/applyList/export',
    {
      evaluationId: evaluationId.value,
      keyword: queryParams.keyword.trim()
    },
    `evaluation_apply_${new Date().getTime()}.xlsx`
  );
};

const handleConfirmSync = async () => {
  if (!syncDialog.employeeIds.length) {
    modal?.msgWarning('请选择员工');
    return;
  }
  syncLoading.value = true;
  try {
    await syncEvaluationToEmployees({
      evaluationIds: [evaluationId.value],
      studentIds: syncDialog.employeeIds
    });
    syncDialog.visible = false;
    modal?.msgSuccess('同步成功');
    await getList();
  } finally {
    syncLoading.value = false;
  }
};

const handleRemove = async (row: EvaluationApplyRow) => {
  await removeEvaluationApply(row.id);
  modal?.msgSuccess('已移除');
  await getList();
};

const handleOpenDetail = (row: EvaluationApplyRow) => {
  router.push({
    path: '/evaluation/evaluation-view',
    query: {
      applyId: String(row.id),
      studentId: String(row.studentId || ''),
      name: row.name || '',
      evaluationId: String(route.query.evaluationId || '')
    }
  });
};

const handleBack = () => {
  const raw = route.query.backPath;
  const backPath = Array.isArray(raw) ? raw[0] : raw || '';
  if (!backPath) {
    router.back();
    return;
  }
  const url = String(backPath + 'Manage');
  // 如果是完整的 http(s) 链接，直接跳转到该地址
  if (/^https?:\/\//i.test(url)) {
    window.location.href = url;
    return;
  }
  // 否则使用 vue-router 跳转（相对或绝对路径）
  try {
    router.push({ path: url });
  } catch (e) {
    router.push(url as any);
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.apply-page {
  min-height: 100%;
}

.apply-card {
  min-height: calc(100vh - 180px);
  padding: 18px 18px 12px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.apply-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.apply-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 14px;
}

.apply-search-box {
  display: flex;
  align-items: stretch;
  width: 290px;
}

.apply-search-box :deep(.el-input__wrapper) {
  border-radius: 4px 0 0 4px;
}

.apply-search-button {
  width: 36px;
  padding: 0;
  border-radius: 0 4px 4px 0;
}

.apply-toolbar-actions {
  display: flex;
  align-items: center;
  gap: 14px;
}

.apply-list-table {
  flex: 1;
}

.apply-list-table :deep(.apply-table-header th) {
  height: 48px;
  color: #303133;
  font-weight: 600;
  background: #eef4ff;
}

.apply-list-table :deep(.el-table__row td) {
  height: 46px;
}

.apply-status-text {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.apply-status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #c0c4cc;
}

.apply-status-dot.is-success {
  background: #67c23a;
}

.apply-status-dot.is-danger {
  background: #f56c6c;
}

.apply-status-dot.is-warning {
  background: #e6a23c;
}

.apply-status-dot.is-info {
  background: #909399;
}

.apply-card :deep(.pagination-container) {
  display: flex;
  justify-content: flex-end;
  margin-top: auto;
  padding: 16px 0 0;
}

.sync-dialog-content {
  padding: 10px 4px 24px;
}

.sync-dialog-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sync-dialog-label {
  width: 56px;
  color: #303133;
  flex-shrink: 0;
}

.sync-dialog-select {
  flex: 1;
}

.sync-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
