<template>
	<div class="modern-page-container">
		<div class="page-wrapper">
			<!-- 搜索表单卡片 -->
			<el-card v-show="showSearch" class="search-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span class="card-title">
							<el-icon class="title-icon"><Search /></el-icon>
							筛选条件
						</span>
					</div>
				</template>
				<el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch" class="search-form">
					<el-form-item label="学院" prop="deptCode">
						<el-select v-model="searchForm.deptCode" placeholder="请选择学院" clearable filterable style="width: 200px" @change="handleDeptChange">
							<el-option v-for="item in deptList" :key="item.deptCode" :label="item.deptName" :value="item.deptCode"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="班级" prop="classCode">
						<el-select v-model="searchForm.classCode" placeholder="请选择班级" clearable filterable style="width: 200px">
							<el-option v-for="item in filteredClassList" :key="item.classCode" :label="item.classNo" :value="item.classCode"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="申诉结果" prop="appealStatus">
						<el-select v-model="searchForm.appealStatus" placeholder="请选择申诉结果" clearable filterable style="width: 200px">
							<el-option v-for="item in appealStatusList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" plain icon="Search" @click="handleSearch">查询</el-button>
						<el-button icon="Refresh" @click="handleReset">重置</el-button>
					</el-form-item>
				</el-form>
			</el-card>

			<!-- 内容卡片 -->
			<el-card class="content-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span class="card-title">
							<el-icon class="title-icon"><Document /></el-icon>
							班主任考核申诉列表
						</span>
						<div class="header-actions">
							<right-toolbar v-model:showSearch="showSearch" class="ml10" @queryTable="getDataList">
								<TableColumnControl
									ref="columnControlRef"
									:columns="tableColumns"
									v-model="visibleColumns"
									trigger-type="default"
									trigger-circle
									@change="handleColumnChange"
									@order-change="handleColumnOrderChange"
								>
									<template #trigger>
										<el-tooltip class="item" effect="dark" content="列设置" placement="top">
											<el-button circle style="margin-left: 0">
												<el-icon><Menu /></el-icon>
											</el-button>
										</el-tooltip>
									</template>
								</TableColumnControl>
							</right-toolbar>
						</div>
					</div>
				</template>

				<!-- 表格 -->
				<el-table
					:data="state.dataList"
					v-loading="state.loading"
					stripe
					:cell-style="tableStyle.cellStyle"
					:header-cell-style="tableStyle.headerCellStyle"
					class="modern-table"
					@sort-change="sortChangeHandle"
				>
					<el-table-column type="index" label="序号" width="70" align="center">
						<template #header>
							<el-icon><List /></el-icon>
						</template>
						<template #default="{ $index }">
							{{ $index + 1 + ((state.pagination?.current || 1) - 1) * (state.pagination?.size || 10) }}
						</template>
					</el-table-column>
					<template v-for="col in visibleColumnsSorted" :key="col.prop || col.label">
						<el-table-column
							v-if="checkColumnVisible(col.prop || '') && col.prop !== '操作'"
							:prop="col.prop"
							:label="col.label"
							:width="col.width"
							:min-width="col.minWidth"
							:show-overflow-tooltip="col.showOverflowTooltip !== false"
							:align="col.align || 'center'"
						>
							<template #header>
								<el-icon v-if="col.icon"><component :is="col.icon" /></el-icon>
								<span :style="{ marginLeft: col.icon ? '4px' : '0' }">{{ col.label }}</span>
							</template>
							<template #default="scope" v-if="col.prop === 'appealStatus'">
								<StatusTag
									:value="scope.row.appealStatus"
									:options="[
										{ label: '待审核', value: '0' },
										{ label: '通过', value: '1' },
										{ label: '驳回', value: '2' },
									]"
									:type-map="{
										'0': { type: 'warning', effect: 'light' },
										'1': { type: 'success', effect: 'light' },
										'2': { type: 'danger', effect: 'light' },
									}"
								/>
							</template>
						</el-table-column>
					</template>
					<el-table-column label="操作" width="150" align="center" fixed="right">
						<template #header>
							<el-icon><Setting /></el-icon>
							<span style="margin-left: 4px">操作</span>
						</template>
						<template #default="scope">
							<el-button
								v-if="!scope.row.appealStatus || scope.row.appealStatus === '0'"
								icon="Edit"
								link
								type="primary"
								@click="handleAudit(scope.row)"
							>
								审核
							</el-button>
							<el-button icon="Delete" link type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
						</template>
					</el-table-column>
					<template #empty>
						<el-empty description="暂无数据" :image-size="120" />
					</template>
				</el-table>

				<!-- 分页 -->
				<div class="pagination-wrapper">
					<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
				</div>
			</el-card>
		</div>

		<!-- 审核对话框 -->
		<el-dialog title="审核申诉" v-model="auditDialogVisible" :close-on-click-modal="false" draggable width="600px">
			<el-form :model="auditForm" ref="auditFormRef" label-width="100px">
				<el-form-item label="班级">
					<el-input :value="auditForm.classNo || '-'" disabled />
				</el-form-item>
				<el-form-item label="班主任">
					<el-input :value="auditForm.realName || '-'" disabled />
				</el-form-item>
				<el-form-item label="考核项目">
					<el-input :value="auditForm.assessmentCategory || '-'" disabled />
				</el-form-item>
				<el-form-item label="考核指标">
					<el-input :value="auditForm.assessmentPoint || '-'" disabled />
				</el-form-item>
				<el-form-item label="申诉原因">
					<el-input :value="auditForm.appealReason || '-'" type="textarea" :rows="3" disabled />
				</el-form-item>
				<el-form-item label="申诉结果" prop="appealStatus" :rules="[{ required: true, message: '请选择申诉结果', trigger: 'change' }]">
					<el-select v-model="auditForm.appealStatus" placeholder="请选择申诉结果" clearable filterable style="width: 100%">
						<el-option v-for="item in appealStatusList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="反馈意见" prop="appealReply">
					<el-input v-model="auditForm.appealReply" type="textarea" :rows="4" placeholder="请输入反馈意见" maxlength="500" show-word-limit />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="auditDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitAudit" :loading="auditLoading">确 认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="ClassMasterEvaluationAppeal">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs, auditAppeal } from '/@/api/stuwork/classmasterevaluationappeal';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { getDeptList, getClassListByRole } from '/@/api/basic/basicclass';
import { getTypeValue } from '/@/api/admin/dict';
import TableColumnControl from '/@/components/TableColumnControl/index.vue';
import {
	List,
	Grid,
	UserFilled,
	Calendar,
	Tickets,
	DataAnalysis,
	Document,
	Warning,
	User,
	CircleCheck,
	EditPen,
	Setting,
	Menu,
	Search,
} from '@element-plus/icons-vue';
import { useTableColumnControl } from '/@/hooks/tableColumn';
import { defineAsyncComponent } from 'vue';
const StatusTag = defineAsyncComponent(() => import('/@/components/StatusTag/index.vue'));

// 定义变量内容
const searchFormRef = ref();
const auditFormRef = ref();
const columnControlRef = ref();
// 搜索变量
const showSearch = ref(true);
const deptList = ref<any[]>([]);
const classList = ref<any[]>([]);
const appealStatusList = ref<any[]>([]);
const auditDialogVisible = ref(false);
const auditLoading = ref(false);

// 表格列配置
const tableColumns = [
	{ prop: 'classNo', label: '班级', icon: Grid },
	{ prop: 'realName', label: '班主任', icon: UserFilled },
	{ prop: 'recordDate', label: '考核日期', icon: Calendar, width: 120 },
	{ prop: 'createTime', label: '申诉日期', icon: Calendar, width: 120 },
	{ prop: 'assessmentCategory', label: '考核项目', icon: Tickets },
	{ prop: 'assessmentPoint', label: '考核指标', icon: DataAnalysis },
	{ prop: 'remarks', label: '情况说明', icon: Document },
	{ prop: 'appealReason', label: '申诉原因', icon: Warning },
	{ prop: 'createBy', label: '考核人', icon: User },
	{ prop: 'appealStatus', label: '申诉结果', icon: CircleCheck, width: 100 },
	{ prop: 'appealReply', label: '反馈意见', icon: EditPen },
];

// 使用表格列控制 Hook
const { visibleColumnsSorted, checkColumnVisible, handleColumnChange, handleColumnOrderChange } = useTableColumnControl(tableColumns);

// 审核表单
const auditForm = reactive({
	id: '',
	classNo: '',
	realName: '',
	assessmentCategory: '',
	assessmentPoint: '',
	recordDate: '',
	remarks: '',
	appealReason: '',
	appealStatus: '',
	appealReply: '',
});

// 搜索表单
const searchForm = reactive({
	deptCode: '',
	classCode: '',
	appealStatus: '',
});

// 根据学院筛选班级列表
const filteredClassList = computed(() => {
	if (!searchForm.deptCode) {
		return classList.value;
	}
	return classList.value.filter((item: any) => item.deptCode === searchForm.deptCode);
});

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: searchForm,
	pageList: fetchList,
	props: {
		item: 'records',
		totalCount: 'total',
	},
	createdIsNeed: true,
});

// table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 学院选择变化
const handleDeptChange = () => {
	searchForm.classCode = '';
};

// 查询
const handleSearch = () => {
	getDataList();
};

// 重置
const handleReset = () => {
	searchFormRef.value?.resetFields();
	Object.assign(searchForm, {
		deptCode: '',
		classCode: '',
		appealStatus: '',
	});
	getDataList();
};

// 获取申诉结果文本
const getAppealStatusText = (status: string) => {
	const item = appealStatusList.value.find((item: any) => item.value === status);
	return item ? item.label : status || '-';
};

// 审核
const handleAudit = (row: any) => {
	auditDialogVisible.value = true;
	Object.assign(auditForm, {
		id: row.id || '',
		classNo: row.classNo || '',
		realName: row.realName || '',
		assessmentCategory: row.assessmentCategory || '',
		assessmentPoint: row.assessmentPoint || '',
		recordDate: row.recordDate || '',
		remarks: row.remarks || '',
		appealReason: row.appealReason || '',
		appealStatus: row.appealStatus || '',
		appealReply: row.appealReply || '',
	});
};

// 提交审核
const submitAudit = async () => {
	const valid = await auditFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		auditLoading.value = true;
		await auditAppeal({
			id: auditForm.id,
			appealStatus: auditForm.appealStatus,
			appealReply: auditForm.appealReply,
		});
		useMessage().success('审核成功');
		auditDialogVisible.value = false;
		getDataList();
	} catch (err: any) {
		useMessage().error(err.msg || '审核失败');
	} finally {
		auditLoading.value = false;
	}
};

// 删除
const handleDelete = async (row: any) => {
	try {
		await useMessageBox().confirm('确定要删除这条申诉记录吗？');
		await delObjs([row.id]);
		useMessage().success('删除成功');
		getDataList();
	} catch (err: any) {
		if (err !== 'cancel') {
			useMessage().error(err.msg || '删除失败');
		}
	}
};

// 获取学院列表
const getDeptListData = async () => {
	try {
		const res = await getDeptList();
		if (res.data) {
			deptList.value = Array.isArray(res.data) ? res.data : [];
		}
	} catch (err) {
		deptList.value = [];
	}
};

// 获取班级列表
const getClassListData = async () => {
	try {
		const res = await getClassListByRole();
		if (res.data) {
			classList.value = Array.isArray(res.data) ? res.data : [];
		}
	} catch (err) {
		classList.value = [];
	}
};

// 获取申诉结果字典
const getAppealStatusListData = async () => {
	try {
		const res = await getTypeValue('appeal_status');
		if (res.data) {
			appealStatusList.value = Array.isArray(res.data)
				? res.data.map((item: any) => ({
						label: item.label || item.name || '',
						value: item.value || item.code || '',
				  }))
				: [];
		}
	} catch (err) {
		appealStatusList.value = [];
	}
};

// 初始化
onMounted(() => {
	getDeptListData();
	getClassListData();
	getAppealStatusListData();
});
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>
