<template>
	<el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" v-model="visible" width="800px">
		<el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit" label-width="100px">
			<el-form-item label="招生计划" prop="groupId">
				<el-select v-model="dataForm.groupId" filterable placeholder="请选择招生计划">
					<el-option v-for="item in planList" :key="item.id" :label="item.groupName" :value="item.id"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="专业序号" prop="majorCode">
				<el-input v-model="dataForm.majorCode" placeholder="专业序号"></el-input>
			</el-form-item>
			<el-form-item label="专业名称" prop="majorName">
				<el-input v-model="dataForm.majorName" placeholder="专业名称"></el-input>
			</el-form-item>
			<el-form-item label="专业规范名称" class="form-item-cascader">
				<el-cascader v-model="chooseMajorCate" :options="majorCateTreeData" @change="handleChange" style="width: 100%" />
			</el-form-item>
			<el-form-item label="所属学院" prop="deptCode">
				<el-select v-model="dataForm.deptCode" filterable placeholder="请选择">
					<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="learnYear">
				<el-select v-model="dataForm.learnYear" filterable placeholder="请选择学制">
					<el-option v-for="item in majorYears" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="层次" prop="majorLevel">
				<el-select v-model="dataForm.majorLevel" filterable placeholder="请选择层次">
					<el-option v-for="item in ccList" :key="item.label" :label="item.label" :value="item.label"> </el-option>
				</el-select>
			</el-form-item>
			<el-row>
				<el-col :span="8">
					<el-form-item label="中德班" prop="isZd">
						<el-radio-group v-model="dataForm.isZd">
							<el-radio v-for="item in yes_no_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="订单班" prop="isOrder">
						<el-radio-group v-model="dataForm.isOrder">
							<el-radio v-for="item in yes_no_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联院班" prop="isUnion">
						<el-radio-group v-model="dataForm.isUnion">
							<el-radio v-for="item in yes_no_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="正式专业代码" prop="stuworkMajorCode">
				<el-select v-model="dataForm.stuworkMajorCode" filterable placeholder="请选择正式专业代码">
					<el-option v-for="item in offcialZydmList" :key="item.majorCode" :label="item.majorCodeAndName" :value="item.majorCode"> </el-option>
				</el-select>
			</el-form-item>
			<el-row>
				<el-col :span="8">
					<el-form-item label="初中费用" prop="czFee">
						<el-input-number v-model="dataForm.czFee" controls-position="right" :min="0" :max="999999" :precision="2" placeholder="请输入初中费用">
						</el-input-number>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="高中费用" prop="gzFee">
						<el-input-number v-model="dataForm.gzFee" controls-position="right" :min="0" :max="999999" :precision="2" placeholder="请输入高中费用">
						</el-input-number>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="技职校费用" prop="jzxFee">
						<el-input-number v-model="dataForm.jzxFee" controls-position="right" :min="0" :max="999999" :precision="2" placeholder="请输入技职校费用">
						</el-input-number>
					</el-form-item>
				</el-col>
			</el-row>

			<el-form-item label="排序" prop="sort">
				<el-input-number :min="0" :max="999" v-model="dataForm.sort" placeholder="排序"></el-input-number>
			</el-form-item>
			<el-form-item label="备注" prop="remarks">
				<el-input type="textarea" :rows="3" placeholder="请输入备注信息" v-model="dataForm.remarks"></el-input>
			</el-form-item>
		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="dataFormSubmit" v-if="canSubmit">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue';
import { ElNotification } from 'element-plus';
import { addObj, getObj, putObj } from '/@/api/recruit/recruitstudentplan';
import { getDeptList } from '/@/api/basic/basicclass';
import { getList } from '/@/api/recruit/recruitstudentplangroup';
import { getMajorNameList } from '/@/api/basic/major';
import { getDictsByTypes } from '/@/api/admin/dict';
import { useDict } from '/@/hooks/dict';
import { majorCateTree } from '/@/api/recruit/recruitMajorCategory';

// Emits
const emit = defineEmits<{
	(e: 'refreshDataList'): void;
}>();

// 字典数据
const { yes_no_type } = useDict('yes_no_type');

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

// 响应式数据
const visible = ref(false);
const canSubmit = ref(false);
const cityPlanIdList = ref<any[]>([]);
const offcialZydmList = ref<any[]>([]);
const planList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const ccList = ref<any[]>([]);
const majorYears = ref<any[]>([]);
const tuitionFeeList = ref<any[]>([]);
const majorCateTreeData = ref<any[]>([]);
const chooseMajorCate = ref<any[]>([]);

const dataForm = reactive({
	id: '',
	groupId: '',
	majorCode: '',
	standardMajorCode: '',
	standardMajorTwoCode: '',
	majorName: '',
	deptCode: '',
	learnYear: '',
	majorLevel: '',
	isZd: '0',
	isOrder: '0',
	remarks: '',
	stuworkMajorCode: '',
	isUnion: '0',
	tuitionFee: 0,
	czFee: 0,
	gzFee: 0,
	jzxFee: 0,
	sort: 0,
});

const dataRule = {
	majorCode: [
		{ required: true, message: '专业代码不能为空', trigger: 'blur' },
		{ min: 1, max: 6, message: '专业代码长度不大于6个字符', trigger: 'blur' },
	],
	tuitionFee: [{ required: true, message: '学费不能为空', trigger: 'blur' }],
	majorName: [
		{ required: true, message: '专业名称不能为空', trigger: 'blur' },
		{ min: 1, max: 200, message: '专业名称长度不大于200个字符', trigger: 'blur' },
	],
	groupId: [{ required: true, message: '招生计划不能为空', trigger: 'blur' }],
	learnYear: [{ required: true, message: '学制不能为空', trigger: 'blur' }],
	deptCode: [{ required: true, message: '学院不能为空', trigger: 'blur' }],
	majorLevel: [{ required: true, message: '层次不能为空', trigger: 'blur' }],
	isOrder: [{ required: true, message: '订单班不能为空', trigger: 'blur' }],
	isZd: [{ required: true, message: '订单班不能为空', trigger: 'blur' }],
	isUnion: [{ required: true, message: '联院班不能为空', trigger: 'blur' }],
	czFee: [
		{ required: true, message: '初中费用不能为空', trigger: 'blur' },
		{ type: 'number', min: 0, message: '初中费用不能小于0', trigger: 'blur' },
	],
	gzFee: [
		{ required: true, message: '高中费用不能为空', trigger: 'blur' },
		{ type: 'number', min: 0, message: '高中费用不能小于0', trigger: 'blur' },
	],
	jzxFee: [
		{ required: true, message: '技职校费用不能为空', trigger: 'blur' },
		{ type: 'number', min: 0, message: '技职校费用不能小于0', trigger: 'blur' },
	],
	remarks: [{ min: 1, max: 100, message: '备注长度不大于100个字符', trigger: 'blur' }],
};

/**
 * 判断市平台招生专业是否占用,占用不可选
 */
// const isCityDisable = (id: string) => {
//   if (!dataForm.cityPlanIds || !Array.isArray(dataForm.cityPlanIds)) {
//     return false
//   }
//   return dataForm.cityPlanIds.some(e => e == id)
// }

// 设置费用默认值
const setFeeDefaults = () => {
	if (tuitionFeeList.value.length > 0) {
		// 初中费用：字典值 1
		const czFeeItem = tuitionFeeList.value.find((item: any) => item.label === '1');

		if (czFeeItem) {
			dataForm.czFee = Number(czFeeItem.value) || 0;
		}
		// 高中费用：字典值 2
		const gzFeeItem = tuitionFeeList.value.find((item: any) => item.label === '2');
		if (gzFeeItem) {
			dataForm.gzFee = Number(gzFeeItem.value) || 0;
		}
		// 技职校费用：字典值 3
		const jzxFeeItem = tuitionFeeList.value.find((item: any) => item.label === '3');
		if (jzxFeeItem) {
			dataForm.jzxFee = Number(jzxFeeItem.value) || 0;
		}
	}
};

// 初始化数据
const initData = (id: string | null) => {
	// 查询二级学院信息
	getDeptList().then((data: any) => {
		deptList.value = data.data;
	});

	// 获取招生计划列表
	getList().then((data: any) => {
		planList.value = data.data;
		// 新增时，默认选中第一个招生计划
		if (!id && data.data && data.data.length > 0) {
			dataForm.groupId = data.data[0]?.id || '';
		}
	});

	// 获取正式专业代码列表
	getMajorNameList().then((data: any) => {
		offcialZydmList.value = data.data;
	});

	// 获取数据字典（一次获取多个）
	getDictsByTypes(['basic_major_years', 'basic_major_level', 'tuition_fee']).then((res: any) => {
		majorYears.value = res.data?.basic_major_years || [];
		ccList.value = res.data?.basic_major_level || [];
		tuitionFeeList.value = res.data?.tuition_fee || [];

		// 新增时，根据学费字典设置费用默认值
		if (!id) {
			setFeeDefaults();
		}
	});

	//查询专业目录树结构
	majorCateTree({}).then((res: any) => {
		majorCateTreeData.value = res.data;
	});
};

// 表单提交
const dataFormSubmit = () => {
	// if (dataForm.cityPlanId != null) {
	//   cityPlanIdList.value.forEach(e => {
	//     if (e.id == dataForm.cityPlanId) {
	//       dataForm.cityPlanName = e.schoolMajorName
	//       dataForm.cityPlanYear = e.educational
	//     }
	//   })
	// }
	dataFormRef.value?.validate((valid: boolean) => {
		if (valid) {
			canSubmit.value = false;
			if (dataForm.id) {
				putObj(dataForm)
					.then(() => {
						ElNotification.success({
							title: '成功',
							message: '修改成功',
						});
						visible.value = false;
						emit('refreshDataList');
					})
					.catch(() => {
						canSubmit.value = true;
					});
			} else {
				addObj(dataForm)
					.then(() => {
						ElNotification.success({
							title: '成功',
							message: '添加成功',
						});
						visible.value = false;
						emit('refreshDataList');
					})
					.catch(() => {
						canSubmit.value = true;
					});
			}
		}
	});
};

const handleChange = (value: any) => {
	dataForm.standardMajorCode = value[0];
	dataForm.standardMajorTwoCode = value[1];
};

// 初始化方法
const init = (id: string | null) => {
	visible.value = true;
	canSubmit.value = true;
	dataForm.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	initData(id);

	// 获取详情数据
	if (id) {
		dataForm.id = id;
		getObj(id)
			.then((response: any) => {
				if (response && response.data) {
					Object.assign(dataForm, response.data);
					if (dataForm.standardMajorCode && dataForm.standardMajorTwoCode) {
            chooseMajorCate.value = [dataForm.standardMajorCode, dataForm.standardMajorTwoCode];
					}else{
            chooseMajorCate.value = [];
          }
					// 获取市平台对应年份下的招生计划
					// getCityPlan({ id: dataForm.id }).then((data: any) => {
					//   cityPlanIdList.value = data.data
					// })
				}
			})
			.catch(() => {
				// 错误处理
			});
	} else {
		// 新增模式：initData 中已处理默认招生计划和费用默认值
	}
};

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

<style lang="scss" scoped>
.form-item-cascader {
	:deep(.el-form-item__content) {
		flex: 1;
		min-width: 0;
	}
	:deep(.el-cascader) {
		width: 100%;
		min-width: 360px;
	}
}
.dialog-footer {
	text-align: right;
}
.el-row {
	margin-bottom: 18px !important;
}
</style>
