<template>
	<el-dialog title="编辑培训计划" v-model="state.dialogVisible" draggable append-to-body destroy-on-close @close="close" width="800px">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px" v-loading="state.loading">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="计划名称" prop="name" :rules="[{ required: true, message: '请填写计划名称', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.name" placeholder="请填写计划名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="培训模板" prop="trainTemplateIds" :rules="[{ required: true, message: '请选择培训模板', trigger: 'change' }]">
                        <el-select v-model="state.ruleForm.trainTemplateIds" clearable filterable multiple placeholder="请选择培训模板" @change="selTrainTemplate">
                            <el-option v-for="item in state.trainTemplateData" :key='item.id' :label="item.name" :value="item.id"  />
                        </el-select>
                    </el-form-item>
				</el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="培训时间" prop="rangeTime" :rules="[{ required: true, message: '请选择培训时间', trigger: 'change' }]">
                        <el-date-picker v-model="state.ruleForm.rangeTime" type="datetimerange" class="w100" value-format="YYYY-MM-DD[T]HH:mm:ss" range-separator="-" start-placeholder="请选择培训开始时间" end-placeholder="请选择培训结束时间" :disabled-date="disabledDate" popper-class="no-atTheMoment" />
                    </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="培训人员" prop="trainRecordDtos" class="w100 tableFormItem" :rules="[{ required: true, message: '请选择培训人员', trigger: 'change' }]">
                        <vxe-toolbar
                            ref="toolbarRef"
                            custom
                        >
                            <template #buttons>
                                <el-button type="primary" @click="onAddUserTable">
                                    <SvgIcon name="ele-Plus" class="mr10" />新增
                                </el-button>
                            </template>
                        </vxe-toolbar>
                        <vxe-table
                            border
                            :data="state.ruleForm.trainRecordDtos"
                            :column-config="{ resizable: true }"
                            :row-config="{ height: 50, useKey: true }"
                            ref="tableRef"
                            height="300"
                            auto-resize
                            show-overflow
                            :scrollY="{ enabled: true, gt: 100 }"
                            id="userTable"
                            :custom-config="{ storage: true }"
                            showHeaderOverflow
                        >
                            <vxe-column field="name" title="姓名" min-width="100"></vxe-column>
                            <vxe-column field="fullOrgName" title="部门" min-width="100"></vxe-column>
                            <vxe-column title="操作" fixed="right" width="80" align="center" :show-overflow="false">
                                <template #default="{ row }">
                                    <el-button link type="danger" @click="onRowDelUserTable(row)" title="删除">
                                        删除
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </el-form-item>
				</el-col>
				<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="排序" prop="weight" :rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]">
                        <el-input v-model="state.ruleForm.weight" placeholder="请填写排序" clearable></el-input>
                    </el-form-item>
				</el-col> -->
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
			</span>
		</template>

        <!-- 选择培训人员 -->
		<examManage-users ref="ExamManageUsersRef" @choose="chooseUsers" />
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import Other from '@/utils/other';
import {getTrainTemplateAllList} from '@/api/examTrain/trainTemplate';
import {editTrainPlan, getTrainPlanDetail} from '@/api/examTrain/trainPlan';

// 引入组件
const ExamManageUsers = defineAsyncComponent(() => import('@/views/examTrain/exam/examManage/components/ExamManage-users.vue')); // 选择培训人员

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		name: '', // 模板名称
        trainStartTime: '', // 培训开始时间
        trainEndTime: '', // 培训结束时间
        rangeTime: [], // 培训时间范围
        trainTemplateIds: [], // 培训模板选择人员ids
		trainPlanTemplateDtos : [], // 培训模板
		trainRecordDtos: [], // 培训人员
	},
	loading: false, // 加载
	tableLoading: false, // 表格加载
    trainTemplateData: [], // 培训模板下拉数据
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
// 获取培训模板数据
const getTrainTemplateData = async () => {
	state.loading = true;
	try {
		const { result } = await getTrainTemplateAllList();
		state.trainTemplateData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
// 打开弹窗
const openDialog = async (row: any) => {
	state.dialogVisible = true;
    await getTrainTemplateData();
    try {
		const { result } = await getTrainPlanDetail(row.id);
		state.ruleForm = result;
		state.ruleForm.trainTemplateIds = state.ruleForm.trainPlanTemplateDtos.map(it => it.trainTemplateId);
		state.ruleForm.rangeTime = [state.ruleForm.trainStartTime, state.ruleForm.trainEndTime];
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
	state.ruleForm.trainTemplateIds = [];
	state.ruleForm.trainPlanTemplateDtos = [];
	state.ruleForm.trainRecordDtos = [];
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
	state.ruleForm.trainTemplateIds = [];
	state.ruleForm.trainPlanTemplateDtos = [];
	state.ruleForm.trainRecordDtos = [];
};
// 选择培训模板
const selTrainTemplate = async (value: any) => {
	state.ruleForm.trainPlanTemplateDtos = [];
    state.ruleForm.trainTemplateIds.forEach(item => {
        state.ruleForm.trainPlanTemplateDtos.push({trainTemplateId: item});
    })
};
// 设置培训开始时间选择范围
const disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 8.64e7; // - 8.64e7是今天可以选
};
// 选择培训人员
const ExamManageUsersRef = ref<RefType>();
const onAddUserTable = () => {
	ExamManageUsersRef.value.openDialog(state.ruleForm.trainRecordDtos);
};
// 删除参考人员
const onRowDelUserTable = (row: any) => {
	state.ruleForm.trainRecordDtos = state.ruleForm.trainRecordDtos.filter(it => it.userId !== row.userId );
    ElMessage.success('删除成功');
};
// 确定选择了参考人员
const chooseUsers = (data: any) => {
    state.ruleForm.trainRecordDtos = [];
	if (data) {
		data.forEach(it => state.ruleForm.trainRecordDtos.push({userId: it.userId, name: it.name, fullOrgName: it.fullOrgName}));
	}
};
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
        const submitObj = Other.deepClone(state.ruleForm);
        submitObj.trainStartTime = submitObj.rangeTime[0];
        submitObj.trainEndTime = submitObj.rangeTime[1];
        Reflect.deleteProperty(submitObj, 'rangeTime');
        Reflect.deleteProperty(submitObj, 'trainTemplateIds');
		console.log(submitObj);
		editTrainPlan(submitObj)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
	.tableFormItem .el-form-item__content{
		display: block;
	}
</style>