<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="queryParams.studentId" placeholder="选择学生" clearable filterable style="width: 180px">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请年份" prop="applyYear">
              <el-input v-model="queryParams.applyYear" placeholder="如2024" clearable style="width: 100px" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 120px">
                <el-option v-for="opt in applicationStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="薪酬状态" prop="salaryStatus">
              <el-select v-model="queryParams.salaryStatus" placeholder="薪酬" clearable style="width: 120px">
                <el-option v-for="opt in salaryStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:application:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:application:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:application:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生" align="center" prop="studentName" width="100" show-overflow-tooltip />
        <el-table-column label="申请学校" align="center" prop="schoolName" min-width="160" show-overflow-tooltip />
        <el-table-column label="申请年份" align="center" prop="applyYear" width="80" />
        <el-table-column label="截止日期" align="center" prop="deadline" width="110">
          <template #default="scope"><span>{{ proxy.parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span></template>
        </el-table-column>
        <el-table-column label="提交日期" align="center" prop="submitDate" width="110">
          <template #default="scope"><span>{{ proxy.parseTime(scope.row.submitDate, '{y}-{m}-{d}') }}</span></template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)" size="small">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="薪酬状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="getSalaryTag(scope.row.salaryStatus)" size="small">{{ getSalaryLabel(scope.row.salaryStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="失误记录" align="center" prop="mistakeNote" min-width="140" show-overflow-tooltip />
        <el-table-column label="超时记录" align="center" prop="overtimeNote" min-width="140" show-overflow-tooltip />
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button v-hasPermi="['edu:application:edit']" link type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:application:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </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" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="form.studentId" placeholder="选择学生" filterable style="width:100%">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请学校">
              <el-input v-model="form.schoolName" placeholder="学校名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="申请年份"><el-input v-model="form.applyYear" placeholder="如2024" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="截止日期"><el-date-picker v-model="form.deadline" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="提交日期"><el-date-picker v-model="form.submitDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="状态"><el-select v-model="form.status" style="width:100%"><el-option v-for="opt in applicationStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="薪酬状态"><el-select v-model="form.salaryStatus" style="width:100%"><el-option v-for="opt in salaryStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" /></el-select></el-form-item></el-col>
        </el-row>
        <el-form-item label="申请系统网址"><el-input v-model="form.systemUrl" placeholder="https://" /></el-form-item>
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="系统账号"><el-input v-model="form.systemAccount" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="系统密码"><el-input v-model="form.systemPwd" type="password" show-password /></el-form-item></el-col>
        </el-row>
        <el-form-item label="失误记录"><el-input v-model="form.mistakeNote" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="超时记录"><el-input v-model="form.overtimeNote" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="2" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduApplication" lang="ts">
import { listApplication, getApplication, addApplication, updateApplication, delApplication } from '@/api/edu/application';
import { ApplicationQuery, ApplicationVO, ApplicationForm, applicationStatusOptions, salaryStatusOptions } from '@/api/edu/application/types';
import { listStudent } from '@/api/edu/student';
import { StudentVO } from '@/api/edu/student/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dataList = ref<ApplicationVO[]>([]);
const studentList = ref<StudentVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const dialog = reactive<{ visible: boolean; title: string }>({ visible: false, title: '' });

const data = reactive<PageData<ApplicationForm, ApplicationQuery>>({
  form: { studentId: undefined, schoolName: '', applyYear: '', status: '0', salaryStatus: '0' },
  queryParams: { pageNum: 1, pageSize: 10, studentId: undefined, schoolId: undefined, applyYear: '', status: '', salaryStatus: '' },
  rules: { studentId: [{ required: true, message: '请选择学生', trigger: 'change' }] }
});
const { queryParams, form, rules } = toRefs(data);

const getStatusLabel = (v: string) => applicationStatusOptions.find((o) => o.value === v)?.label || v;
const getStatusTag = (v: string) => applicationStatusOptions.find((o) => o.value === v)?.elTagType || 'info';
const getSalaryLabel = (v: string) => salaryStatusOptions.find((o) => o.value === v)?.label || v;
const getSalaryTag = (v: string) => salaryStatusOptions.find((o) => o.value === v)?.elTagType || 'info';

const loadStudents = async () => { const res = await listStudent({ pageNum: 1, pageSize: 1000 } as any); studentList.value = res.rows; };
const getList = async () => { loading.value = true; const res = await listApplication(queryParams.value); dataList.value = res.rows; total.value = res.total; loading.value = false; };
const handleQuery = () => { queryParams.value.pageNum = 1; getList(); };
const resetQuery = () => { queryFormRef.value?.resetFields(); handleQuery(); };
const handleSelectionChange = (selection: ApplicationVO[]) => { ids.value = selection.map((item) => item.id); single.value = selection.length != 1; multiple.value = !selection.length; };

const reset = () => { form.value = { studentId: undefined, schoolName: '', applyYear: '', status: '0', salaryStatus: '0' }; formRef.value?.resetFields(); };
const handleAdd = () => { reset(); dialog.title = '新增申请'; dialog.visible = true; };
const handleEdit = async (row: ApplicationVO) => { reset(); const res = await getApplication(row.id); Object.assign(form.value, res.data); dialog.title = '编辑申请'; dialog.visible = true; };

const submitForm = async () => {
  await formRef.value?.validate();
  if (form.value.id) { await updateApplication(form.value); proxy?.$modal.msgSuccess('修改成功'); }
  else { await addApplication(form.value); proxy?.$modal.msgSuccess('新增成功'); }
  dialog.visible = false; await getList();
};

const handleDelete = async (row?: ApplicationVO) => { const delIds = row?.id || ids.value; await proxy?.$modal.confirm('是否确认删除？'); await delApplication(delIds); proxy?.$modal.msgSuccess('删除成功'); await getList(); };
const handleExport = () => { proxy?.download('edu/application/export', { ...queryParams.value }, `application_${new Date().getTime()}.xlsx`); };

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