<template>
  <PageShell>
    <div class="apply-page">
      <div class="apply-card">
        <div class="apply-header">
          <div class="apply-title">{{ pageTitle }}</div>
          <div class="apply-actions">
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>

        <el-form :model="queryParams" :inline="true" class="apply-search-form">
          <el-form-item class="apply-search-name-item">
            <el-input v-model="queryParams.keyword" placeholder="请输入姓名/手机号" clearable @keyup.enter="handleQuery">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="apply-search-btn-item">
            <el-button type="primary" icon="Search" @click="handleQuery" />
          </el-form-item>
          <el-form-item class="apply-search-select-item">
            <el-select v-model="queryParams.status" placeholder="审核状态" clearable @change="handleQuery">
              <el-option v-for="item in applyStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="apply-search-select-item" v-if="false">
            <el-select v-model="queryParams.ability" placeholder="测评能力" clearable>
              <el-option v-for="item in abilityOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <div class="apply-toolbar-actions">
            <el-button disabled>录用</el-button>
            <el-button type="primary" @click="handleExport">导出列表</el-button>
          </div>
        </el-form>

        <el-table v-loading="loading" :data="applyList" class="apply-list-table">
          <el-table-column label="姓名" prop="name" min-width="160">
            <template #default="scope">
              <el-button link type="primary" @click="handleOpenDetail(scope.row)">{{ scope.row.name }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="gender" width="100" align="center" />
          <el-table-column label="手机号" prop="phone" min-width="180" align="center" />
          <el-table-column label="状态" min-width="160" align="center">
            <template #default="scope">
              <span class="apply-status-text">
                <span class="apply-status-dot" :class="`is-${scope.row.statusType}`"></span>
                {{ scope.row.statusText }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="测评时间" prop="evaluateTime" min-width="180" align="center" />
          <el-table-column label="操作" min-width="220" align="center">
            <template #default="scope">
              <template v-if="scope.row.status !== STATUS_CLOSED">
                <el-button link type="primary" @click="handleEvaluationDetail(scope.row)">测评详情</el-button>
                <el-button link type="primary">下载附件简历</el-button>
                <template v-if="scope.row.status === STATUS_PENDING">
                  <el-button link type="primary" @click="handleHire(scope.row)">录用</el-button>
                  <el-button link type="primary" @click="handleReject(scope.row)">不录用</el-button>
                </template>
              </template>
            </template>
          </el-table-column>
        </el-table>

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

      <el-dialog v-model="hireDialog.visible" title="审核说明" width="680px" append-to-body>
        <div class="result-dialog-content">
          <div class="result-line"><span class="result-label">结果:</span><span class="result-value">录用</span></div>
          <div class="result-remark-row">
            <span class="result-label top">附件</span>
            <div class="result-upload-panel">
              <FileUpload
                v-model="hireDialog.offerAttachment"
                :limit="5"
                :file-type="['png', 'jpg', 'jpeg', 'doc', 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'txt', 'pdf']"
                :file-size="20"
              />
            </div>
          </div>
          <div class="result-remark-row">
            <span class="result-label top">说明</span>
            <el-input v-model="hireDialog.remark" type="textarea" :rows="5" placeholder="请输入" />
          </div>
          <el-checkbox v-model="hireDialog.agree">我已阅读并同意服务 offer 确认前免责协议</el-checkbox>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="hireDialog.visible = false">返回</el-button>
            <el-button type="primary" :loading="hireDialog.submitting" @click="submitHire">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="rejectDialog.visible" title="审核说明" width="520px" append-to-body>
        <div class="result-dialog-content compact">
          <div class="result-line"><span class="result-label">结果:</span><span class="result-value">不录用</span></div>
          <div class="result-remark-row compact">
            <span class="result-label top">备注:</span>
            <el-input v-model="rejectDialog.remark" type="textarea" :rows="4" placeholder="说明" />
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rejectDialog.visible = false">取消</el-button>
            <el-button type="primary" :loading="rejectDialog.submitting" @click="submitReject">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </PageShell>
</template>

<script setup name="PostManageApplyList" lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref, type ComponentInternalInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { hirePostCandidate, listPostCandidates, updatePostCandidateStatus, type PostCandidateVO } from '@/api/main/postManage/candidate';
import PageShell from '@/components/PageShell/index.vue';
import FileUpload from '@/components/FileUpload/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const modal = proxy?.$modal as any;
const STATUS_ADOPTED = 'adopted';
const STATUS_REJECTED = 'rejected';
const STATUS_PENDING = 'pending';
const STATUS_CLOSED = 'closed';

const pageTitle = computed(() => {
  const postName = route.query.postName as string | undefined;
  return postName ? `${postName} 报名列表` : '报名列表';
});

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

const loading = ref(false);
const total = ref(0);

const applyStatusOptions = [
  { label: '录用', value: STATUS_ADOPTED },
  { label: '不录用', value: STATUS_REJECTED },
  { label: '待回复', value: STATUS_PENDING },
  { label: '学员已拒绝', value: STATUS_CLOSED }
];

const abilityOptions = ['测评能力'];

const applyList = ref<PostCandidateVO[]>([]);

const hireDialog = reactive({
  visible: false,
  remark: '',
  agree: true,
  offerAttachment: '',
  currentId: '',
  submitting: false
});

const rejectDialog = reactive({
  visible: false,
  remark: '',
  currentId: '',
  submitting: false
});

const getList = async () => {
  const postId = route.query.postId as string | undefined;
  if (!postId) {
    applyList.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    const res = await listPostCandidates({
      postId,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      keyword: queryParams.keyword,
      status: queryParams.status
    });
    applyList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

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

const handleBack = () => {
  proxy?.$tab.closePage();
  router.push((route.query.backPath as string) || '/postManage');
};

const handleExport = () => {
  const postId = route.query.postId as string | undefined;
  if (!postId) {
    modal?.msgWarning('岗位ID不能为空');
    return;
  }
  proxy?.download(
    '/main/postCandidate/export',
    {
      postId,
      keyword: queryParams.keyword,
      status: queryParams.status
    },
    `post_candidate_${new Date().getTime()}.xlsx`
  );
};

const handleHire = (row: PostCandidateVO) => {
  hireDialog.currentId = String(row.id);
  hireDialog.remark = row.remark || '';
  hireDialog.offerAttachment = '';
  hireDialog.agree = true;
  hireDialog.visible = true;
};

const handleReject = (row: PostCandidateVO) => {
  rejectDialog.currentId = String(row.id);
  rejectDialog.remark = row.remark || '';
  rejectDialog.visible = true;
};

const submitHire = async () => {
  if (!hireDialog.currentId) return;
  if (!hireDialog.agree) {
    modal?.msgWarning('请先阅读并同意免责协议');
    return;
  }
  if (!hireDialog.offerAttachment) {
    modal?.msgWarning('请先上传录用附件');
    return;
  }
  hireDialog.submitting = true;
  try {
    await hirePostCandidate({
      id: hireDialog.currentId,
      remark: hireDialog.remark.trim(),
      offerAttachment: hireDialog.offerAttachment
    });
    hireDialog.visible = false;
    modal?.msgSuccess('录用成功');
    await getList();
  } finally {
    hireDialog.submitting = false;
  }
};

const submitReject = async () => {
  if (!rejectDialog.currentId) return;
  rejectDialog.submitting = true;
  try {
    await updatePostCandidateStatus({
      id: rejectDialog.currentId,
      status: STATUS_REJECTED,
      remark: rejectDialog.remark.trim()
    });
    rejectDialog.visible = false;
    modal?.msgSuccess('操作成功');
    await getList();
  } finally {
    rejectDialog.submitting = false;
  }
};

const handleOpenDetail = (row: { id: number; name: string }) => {
  router.push({
    path: '/postManage/apply-detail',
    query: {
      applyId: String(row.id),
      name: row.name,
      postId: String(route.query.postId || ''),
      studentId: String((row as PostCandidateVO).studentId || '')
    }
  });
};

const handleEvaluationDetail = (row: PostCandidateVO) => {
  router.push({
    path: '/postManage/evaluation-view',
    query: {
      applyId: String(row.id),
      name: row.name || '',
      postId: String(route.query.postId || ''),
      studentId: String(row.studentId || ''),
      evaluationId: String((row as any).evaluationId || route.query.postId || '')
    }
  });
};

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

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

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

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

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

.apply-search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.apply-search-name-item {
  width: 280px;
  margin-bottom: 0;
}
.apply-search-btn-item {
  margin-left: -82px;
}

.apply-search-btn-item,
.apply-search-select-item {
  margin-bottom: 0;
}

.apply-search-select-item {
  width: 140px;
}

.apply-toolbar-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.apply-list-table :deep(.el-table__header th) {
  background: #eef4ff;
}

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

.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-card :deep(.pagination-container) {
  display: flex;
  justify-content: flex-end;
  margin-top: auto;
  padding-top: 20px;
  padding: 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.result-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 8px 8px 0;
}

.result-dialog-content.compact {
  gap: 16px;
}

.result-line {
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-label {
  width: 44px;
  color: #303133;
  flex-shrink: 0;
}

.result-label.top {
  padding-top: 8px;
}

.result-value {
  color: #303133;
}

.result-upload-row {
  padding-left: 44px;
}

.result-file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-left: 44px;
}

.result-file-item {
  color: #606266;
  font-size: 13px;
}

.result-remark-row {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.result-remark-row.compact :deep(.el-textarea) {
  flex: 1;
}

.result-upload-panel {
  flex: 1;
}
</style>
