<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" @keyup.enter="handleQuery">
                <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="type">
              <el-select v-model="queryParams.type" placeholder="类型" clearable style="width: 120px">
                <el-option v-for="opt in rpTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="分类" prop="category">
              <el-select v-model="queryParams.category" placeholder="分类" clearable style="width: 120px">
                <el-option v-for="opt in rpCategoryOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </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 rpStatusOptions" :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:reward:add']" type="primary" plain icon="Plus" @click="handleAdd">新增记录</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:reward:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</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="rewardList" @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" width="80">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)" size="small">{{ getTypeLabel(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryTag(scope.row.category)" effect="plain" size="small">{{ getCategoryLabel(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center" prop="title" min-width="160" show-overflow-tooltip />
        <el-table-column label="发生时间" align="center" prop="occurTime" width="110">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.occurTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值变动" align="center" prop="scoreChange" width="100">
          <template #default="scope">
            <span :style="{ color: scope.row.scoreChange >= 0 ? '#67c23a' : '#f56c6c', fontWeight: 600 }">
              {{ scope.row.scoreChange >= 0 ? '+' : '' }}{{ scope.row.scoreChange || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="handlerName" width="90" />
        <el-table-column label="状态" align="center" width="80">
          <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" prop="description" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="140" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button v-hasPermi="['edu:reward:edit']" link type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:reward: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="600px" 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="奖惩类型" prop="type">
              <el-select v-model="form.type" placeholder="类型" style="width: 100%">
                <el-option v-for="opt in rpTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select v-model="form.category" placeholder="分类" style="width: 100%">
                <el-option v-for="opt in rpCategoryOptions" :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-date-picker v-model="form.occurTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="如：数学竞赛一等奖" />
        </el-form-item>
        <el-form-item label="分值变动">
          <el-input-number v-model="form.scoreChange" :precision="1" controls-position="right" style="width: 200px" />
          <span class="ml-2 text-gray-400 text-sm">正数=加分, 负数=扣分</span>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="详细描述" />
        </el-form-item>
        <el-form-item label="附件">
          <file-upload v-model="form.attachments" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="状态" style="width: 100%">
                <el-option v-for="opt in rpStatusOptions" :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.remark" type="textarea" :rows="2" placeholder="备注" />
        </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="EduReward" lang="ts">
import { listRewardPunish, getRewardPunish, addRewardPunish, updateRewardPunish, delRewardPunish } from '@/api/edu/reward';
import { listStudent } from '@/api/edu/student';
import { RewardPunishQuery, RewardPunishVO, RewardPunishForm, rpTypeOptions, rpCategoryOptions, rpStatusOptions } from '@/api/edu/reward/types';
import { StudentVO } from '@/api/edu/student/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const rewardList = ref<RewardPunishVO[]>([]);
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<RewardPunishForm, RewardPunishQuery>>({
  form: {
    studentId: undefined,
    type: '',
    category: '',
    title: '',
    occurTime: '',
    scoreChange: undefined,
    description: '',
    attachments: '',
    status: '0',
    remark: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    type: '',
    category: '',
    status: ''
  },
  rules: {
    studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
    type: [{ required: true, message: '请选择奖惩类型', trigger: 'change' }],
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getTypeLabel = (val: string) => rpTypeOptions.find((o) => o.value === val)?.label || val;
const getTypeTag = (val: string) => rpTypeOptions.find((o) => o.value === val)?.elTagType || 'info';
const getCategoryLabel = (val: string) => rpCategoryOptions.find((o) => o.value === val)?.label || val;
const getCategoryTag = (val: string) => rpCategoryOptions.find((o) => o.value === val)?.elTagType || 'info';
const getStatusLabel = (val: string) => rpStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => rpStatusOptions.find((o) => o.value === val)?.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 listRewardPunish(queryParams.value);
  rewardList.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: RewardPunishVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 重置表单 */
const reset = () => {
  form.value = {
    studentId: undefined,
    type: '',
    category: '',
    title: '',
    occurTime: '',
    scoreChange: undefined,
    description: '',
    attachments: '',
    status: '0',
    remark: ''
  };
  formRef.value?.resetFields();
};

/** 新增 */
const handleAdd = () => {
  reset();
  dialog.title = '新增奖惩记录';
  dialog.visible = true;
};

/** 编辑 */
const handleEdit = async (row: RewardPunishVO) => {
  reset();
  const res = await getRewardPunish(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 updateRewardPunish(form.value);
    proxy?.$modal.msgSuccess('修改成功');
  } else {
    await addRewardPunish(form.value);
    proxy?.$modal.msgSuccess('新增成功');
  }
  dialog.visible = false;
  await getList();
};

/** 删除 */
const handleDelete = async (row?: RewardPunishVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的奖惩记录？');
  await delRewardPunish(delIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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