<template>
	<el-dialog title="招生计划专业调整" append-to-body width="98%" :close-on-click-modal="false" v-model="visible">
		<el-form :model="dataForm" ref="dataFormRef" class="mb4">
			<el-form-item label="招生计划名称" prop="groupName">
				<el-input v-model="dataForm.groupName" placeholder="招生计划名称" disabled style="width: 200px"></el-input>
			</el-form-item>
		</el-form>
		<el-tabs v-model="activiName" @tab-click="handleChange">
			<el-tab-pane v-for="item in deptList" :key="item.deptCode" :label="item.deptName" :name="item.deptCode">
				<div>
					<el-table :data="dataList" border stripe v-loading="dataListLoading">
						<el-table-column prop="majorName" header-align="center" align="center" label="专业">
							<template #default="scope">
								<span>{{ scope.row.majorName + ' || ' + scope.row.majorCode + ' || ' + scope.row.learnYear + ' 年制' }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="planStudentNum" header-align="center" align="center" label="计划总数" width="180px">
							<template #default="scope">
								<el-input-number
									style="width: 80%"
									v-model="scope.row.planStudentNum"
									:min="0"
									:max="999"
									@change="updateMajor(scope.row, 'planStudentNum')"
									width="100px"
								></el-input-number>
							</template>
						</el-table-column>

						<el-table-column prop="scoreLine" header-align="center" align="center" label="录取线" width="180px">
							<template #default="scope">
								<el-input-number
									style="width: 80%"
									v-model="scope.row.scoreLine"
									:min="0"
									:max="999"
									@change="updateMajor(scope.row, 'scoreLine')"
								></el-input-number>
							</template>
						</el-table-column>
						<el-table-column prop="degreeOfEducation" header-align="center" align="center" label="生源">
							<template #default="scope">
								<el-select
									v-model="scope.row.degreeOfEducation"
									placeholder="请选择生源"
									multiple	
									@change="updateMajor(scope.row,'degreeOfEducation')"
								>
									<el-option v-for="item in degreeOfEducationList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
								</el-select>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-tab-pane>
		</el-tabs>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { ElNotification } from 'element-plus';
import { listPlanByCondition as list, delObj, putObj, editQuickField } from '/@/api/recruit/recruitstudentplan';
import { fetchSecondTree } from '/@/api/basic/basicdept';
import { getDicts } from '/@/api/admin/dict';

// 消息提示 hooks
const message = useMessage();
const messageBox = useMessageBox();

// 表单引用
const dataFormRef = ref();

// 响应式数据
const visible = ref(false);
const activiName = ref('11');
const dataList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const degreeOfEducationList = ref<any[]>([]);
const dataListLoading = ref(false);

const dataForm = reactive({
	groupId: '',
	groupName: '',
	deptCode: '11',
});

// 初始化数据
const initData = () => {
	degreeOfEducationList.value = [];
	// 获取数据字典
	getDicts('finance_student_source')
		.then((res: any) => {
			degreeOfEducationList.value = res.data || [];
		})
		.catch((error: any) => {
			message.error('获取字典数据失败：' + (error.msg || '未知错误'));
			degreeOfEducationList.value = [];
		});
};

// 获取部门列表
const getDepartment = () => {
	fetchSecondTree()
		.then((res: any) => {
			deptList.value = res.data || [];
		})
		.catch((error: any) => {
			message.error('获取部门列表失败：' + (error.msg || '未知错误'));
			deptList.value = [];
		});
};

// 更新专业
const updateMajor = (row: any, type: any) => {
	if (!row || !row.id) {
		message.error('缺少计划主键');
		return;
	}

	if (row.degreeOfEducation && Array.isArray(row.degreeOfEducation) && row.degreeOfEducation.length != 0) {
		row.degreeOfEducations = row.degreeOfEducation.join(',');
	} else {
		row.degreeOfEducations = '';
	}
	let params = {} as any;
	params.id = row.id;
	if (type == 'planStudentNum') {
    params.planStudentNum=row.planStudentNum
	}
  if (type == 'scoreLine') {
    params.scoreLine=row.scoreLine
  }
  if (type == 'degreeOfEducation') {
    params.degreeOfEducation=row.degreeOfEducations
  }

	editQuickField(params)
		.then(() => {
			ElNotification.success({
				title: '成功',
				message: '修改成功',
			});
		})
		.catch((error: any) => {
			message.error('修改失败：' + (error.msg || '未知错误'));
		});
};

// 标签切换
const handleChange = (tab: any) => {
	dataForm.deptCode = tab.paneName;
	getDataList();
};

// 获取数据列表
const getDataList = () => {
	if (!dataForm.groupId) {
		dataListLoading.value = false;
		return;
	}

	dataList.value = [];
	dataListLoading.value = true;
	if (dataForm.deptCode == '') {
		dataForm.deptCode = '11';
	}
	list({ groupId: dataForm.groupId, deptCode: dataForm.deptCode })
		.then((response: any) => {
			dataList.value = response.data || [];
			dataList.value.forEach((e: any) => {
				if (e.degreeOfEducation && typeof e.degreeOfEducation === 'string') {
					e.degreeOfEducation = e.degreeOfEducation.split(',');
				}
			});
			dataListLoading.value = false;
		})
		.catch((error: any) => {
			message.error('获取数据失败：' + (error.msg || '未知错误'));
			dataListLoading.value = false;
		});
};

// 删除
const deleteHandle = async (id: string) => {
	try {
		await messageBox.confirm('是否确认删除本条数据？请谨慎操作');
		await delObj(id);
		message.success('删除成功');
		getDataList();
	} catch {
		// 用户取消
	}
};

// 初始化方法
const init = (row: any) => {
	if (!row) {
		message.error('初始化参数错误');
		return;
	}

	if (!row.id || !row.groupName) {
		message.error('缺少必要的参数：id 或 groupName');
		return;
	}

	try {
		visible.value = true;
		dataForm.deptCode = '11';
		dataForm.groupName = row.groupName || '';
		dataForm.groupId = row.id || '';
		initData();
		getDepartment();
		getDataList();
	} catch (error: any) {
		message.error('初始化失败：' + (error.message || '未知错误'));
		visible.value = false;
	}
};

// 暴露方法给父组件
defineExpose({
	init,
	deleteHandle,
});
</script>

<style lang="scss" scoped></style>
