<template>
	<view class="todo-page">
		<view class="card">
			<view class="background"></view>
			<view>
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules" ref="wForm" errorType="border-bottom" class="demo-ruleForm">
					<u-form-item required label="培训名称：" prop="Nav_Notify.NAME" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.NAME" border="none" slot="right" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="培训类型：" prop="Nav_TrainType.NAME" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.Nav_TrainType.NAME" placeholder="培训类型" border="none" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
						</u-icon>
					</u-form-item>
					<u-form-item label="培训级别：" prop="LEVEL" borderBottom>
						<u--input v-if="model.Nav_Notify" :value="model.Nav_Notify.LEVEL_SHOW" border="none" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="组织部门：" prop="LEVEL" borderBottom>
						<u--input v-if="model.Nav_Notify" :value="model.Nav_Notify.Nav_LaunchDepartment.NAME" border="none" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="开始时间" required prop="Nav_Notify.TRAIN_START_TIME" @click="showCheckDate({ name: 'TRAIN_START_TIME'})" borderBottom>
						<u--input v-if="model.Nav_Notify" disabledColor="#fff" v-model="model.Nav_Notify.TRAIN_START_TIME" disabled placeholder="请选择开始时间" suffixIcon="arrow-down" suffixIconStyle="font-size:12px"
							fontSize="14px" border="none" customStyle="margin:0px;display:flex;padding:3px 0px" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="结束时间" required prop="Nav_Notify.TRAIN_END_TIME" @click="showCheckDate({name: 'TRAIN_END_TIME'})" borderBottom>
						<u--input v-if="model.Nav_Notify" disabledColor="#fff" v-model="model.Nav_Notify.TRAIN_END_TIME" border="none" disabled placeholder="请选择结束时间" suffixIcon="arrow-down"
							suffixIconStyle="font-size:12px" fontSize="14px" customStyle="margin:0px;display:flex;padding:3px 0px" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="培训地点：" prop="TRAIN_ADDR" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.TRAIN_ADDR" border="none" slot="right" inputAlign="right" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="培训学时：" prop="HOURS" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.HOURS" type="number" border="none" slot="right" inputAlign="right" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="培训老师：" prop="TRAIN_TEACHER" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.TRAIN_TEACHER" border="none" slot="right" inputAlign="right" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="培训形式：" prop="TRAIN_MODEL" borderBottom>
						<u--input v-if="model.Nav_Notify" :value="model.Nav_Notify.TRAINTYPE_SHOW" border="none" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item label="考核方式：" prop="Nav_TrainCheckType.NAME" borderBottom>
						<u--input v-if="model.Nav_Notify" v-model="model.Nav_Notify.CHECKTYPE_SHOW" border="none" inputAlign="right" disabled disabledColor="#fff" fontSize="14px"></u--input>
					</u-form-item>
					<u-form-item class="custom-form-item" label="培训内容：" prop="DetailPost" :borderBottom="false">
					</u-form-item>
					<u-textarea v-html="model.Nav_TrainContentList_SHOW" style="font-size: 14px;"></u-textarea>
					<view class="upload-title">附件：</view>
					<full-upload v-model="model.Nav_Files" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>
				</u--form>
			</view>
		</view>
		<u-sticky offset-top="20">
			<view class="sub-form">
				<view class="sub-form-wrap">
					<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom" ref="sForm">
						<!-- <u-collapse :border="false" accordion> -->
						<view style="margin-bottom: 16px;" v-for="(item, index) in model.Nav_Users">
							<u-form-item :label="(index+1)+'. '+ item.Nav_User.NAME">
								<u-subsection activeColor="#0eacf5" mode="subsection" :list="list" :current="item.STATUS" @change="sectionChange($event,item)"></u-subsection>
							</u-form-item>
						</view>
						<!-- </u-collapse> -->
					</u--form>
				</view>
			</view>
		</u-sticky>
		<query-selector :show="showPopup" :lists="Lists" @close="handleClosePopup" @search="handleSearch" @select="handleSelected" />
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" mode="datetime" v-model='dateTimePickerInfo.defaultDateTime' :formatter="formatter" @confirm="handleCheckDate"
			@close="dateTimePickerInfo.showCheckDate = false;" @cancel="dateTimePickerInfo.showCheckDate = false;"></u-datetime-picker>
		<view class="bottom-button">
			<u-button type="primary" @click="submit" color="#3d4b70">提交</u-button>
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		getEnum
	} from '../../../../services/common';
	export default {
		data() {
			return {
				Lists: [],
				listPropUpload: ['RECORD_ID'],
				listPropValUpload: [],
				model: {
					Nav_Users: [],
					ORG_ID: "",
					Nav_Files: [],
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				list: ['参与', '请假', '缺席'],
				showPopup: false,
				tableKey: '0',
				TaskID: '',
				isLoadOK: false,
				ORG_ID: uni.getStorageSync('orgId'),
				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					value: '',
					name: ''
				},
				currItem: '',
				formatter: null,
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {}, // 存储枚举文本列表（用于下拉选择等场景）
			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.tableKey = option.tableKey ? option.tableKey : '0';
			this.fetchEnums(['TrainType', 'PlanCheckType','FMDepartmentType']);
		},
		methods: {
			async fetchEnums(enumNames) {
				try {
					// 存储所有枚举请求的Promise
					const enumPromises = enumNames.map(name => {
						return getEnum({
							name
						}).then(res => {
							// 统一处理枚举格式：添加name/code字段，便于后续映射
							return {
								enumName: name,
								data: res.map(item => ({
									...item,
									name: item.NAME, // 统一显示名称字段
									code: item.ID // 统一值字段
								}))
							};
						});
					});

					// 等待所有枚举请求完成
					const results = await Promise.all(enumPromises);
					// 存储枚举结果到data中（键为枚举名称，值为处理后的数据）
					results.forEach(({
						enumName,
						data
					}) => {
						this.enumsData[enumName] = data;
						// 生成文本列表（如需要）
						this.enumsText[enumName] = data.map(item => item.name);
					});
					// 所有枚举获取完成后，执行loadData
					this.loadData();
				} catch (error) {
					console.error('枚举请求失败:', error);
					uni.showToast({
						title: '枚举数据加载失败',
						icon: 'none'
					});
				}
			},
			sectionChange(index, item) {
				item.STATUS = index;
			},
			//时间start
			showCheckDate(p) {
				if (p.name === 'TRAIN_START_TIME') {
					if (this.model.Nav_Notify.TRAIN_START_TIME == null) {
						this.model.Nav_Notify.TRAIN_START_TIME = uni.$u.timeFormat(new Date(),
							'yyyy-mm-dd hh:MM:ss')
					}
					this.dateTimePickerInfo = {
						showCheckDate: true,
						dataIndex: p.dataIndex,
						defaultDateTime: this.model.Nav_Notify.TRAIN_START_TIME,
						name: p.name
					}
				} else if (p.name === 'TRAIN_END_TIME') {
					if (this.model.Nav_Notify.TRAIN_END_TIME == null) {
						this.model.Nav_Notify.TRAIN_END_TIME = uni.$u.timeFormat(new Date(),
							'yyyy-mm-dd hh:MM:ss')
					}
					this.dateTimePickerInfo = {
						showCheckDate: true,
						dataIndex: p.dataIndex,
						defaultDateTime: this.model.Nav_Notify.TRAIN_END_TIME,
						name: p.name
					}
				}
			},
			handleCheckDate(e) {
				const {
					name,
					dataIndex
				} = this.dateTimePickerInfo
				if (name === 'TRAIN_START_TIME') {
					this.model.Nav_Notify.TRAIN_START_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
				if (name === 'TRAIN_END_TIME') {
					this.model.Nav_Notify.TRAIN_END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
				this.dateTimePickerInfo.showCheckDate = false
			},
			//时间end
			loadData() {
				const json = initFilter(this.ORG_ID, "", "")
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendInclude(json, 'Nav_Notify');
				extendInclude(json, 'Nav_Notify.Nav_TrainContentList.Nav_Point');
				extendInclude(json, 'Nav_Notify.Nav_LaunchDepartment');
				// extendInclude(json, 'Nav_Notify.Nav_LaunchUser');
				extendInclude(json, 'Nav_Notify.Nav_TrainType');
				// extendInclude(json, 'Nav_Notify.Nav_TrainCheckType');
				extendInclude(json, 'Nav_Users.Nav_User');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');
				extendInclude(json, 'Nav_Users');
				extendRule(json, 'ID', 1, this.model.ID)
				getRequest(json, "/SE/TrainRecord/Get").then(res => {
					this.model = res
					// if (this.model.Nav_Notify.LEVEL == 0) {
					// 	this.model.Nav_Notify.LEVEL_SHOW = "部门";
					// } else if (this.model.Nav_Notify.LEVEL == 1) {
					// 	this.model.Nav_Notify.LEVEL_SHOW = "车间";
					// } else if (this.model.Nav_Notify.LEVEL == 2) {
					// 	this.model.Nav_Notify.LEVEL_SHOW = "班组";
					// } else if (this.model.Nav_Notify.LEVEL == 3) {
					// 	this.model.Nav_Notify.LEVEL_SHOW = "公司";
					// }
					this.model.Nav_Notify.LEVEL_SHOW= res.Nav_Notify.LEVEL !== undefined ? this.enumsData['FMDepartmentType'].find(item => item.code === res.Nav_Notify.LEVEL)?.name : '';
					this.model.Nav_Notify.TRAINTYPE_SHOW = res.Nav_Notify.TRAINTYPE !== undefined ? this.enumsData['TrainType'].find(item => item.code === res.Nav_Notify.TRAINTYPE)?.name : '';
					this.model.Nav_Notify.CHECKTYPE_SHOW = res.Nav_Notify.CHECKTYPE !== undefined ? this.enumsData['PlanCheckType'].find(item => item.code === res.Nav_Notify.CHECKTYPE)?.name : '';
					this.model.Nav_Notify.TRAIN_MODEL_SHOW = "";
					if (this.model.Nav_Notify.TRAIN_MODEL.indexOf(1) > 0) {
						this.model.Nav_Notify.TRAIN_MODEL_SHOW += "讲授法 ";
					} else if (this.model.Nav_Notify.TRAIN_MODEL.indexOf(2) > 0) {
						this.model.Nav_Notify.TRAIN_MODEL_SHOW += "视听法 ";
					} else if (this.model.Nav_Notify.TRAIN_MODEL.indexOf(3) > 0) {
						this.model.Nav_Notify.TRAIN_MODEL_SHOW += "研讨法 ";
					} else if (this.model.Nav_Notify.TRAIN_MODEL.indexOf(4) > 0) {
						this.model.Nav_Notify.TRAIN_MODEL_SHOW += "演示法 ";
					}
					this.model.Nav_TrainContentList_SHOW = "";
					for (let i = 0; i < this.model.Nav_Notify.Nav_TrainContentList.length; i++) {
						this.model.Nav_TrainContentList_SHOW += (i + 1) + "." + this.model.Nav_Notify
							.Nav_TrainContentList[i].Nav_Point.NAME + "<br/>";
					}
					this.model.Nav_Users_SHOW = "";
					for (let i = 0; i < this.model.Nav_Users.length; i++) {
						this.model.Nav_Users_SHOW += (i + 1) + "." + this.model.Nav_Users[i].Nav_User.NAME +
							"<br/>";
					}
				})
			},
			submit() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					this.model.PUBLISH = "SaveAndNotify";
					if (this.TaskID != "") {
						this.model.TaskID = this.TaskID;
					}
					if (this.model.ORG_ID == "") {
						this.model.ORG_ID = this.ORG_ID;
					}
					this.model.Nav_Users.forEach(item => {
						item.Nav_User = null;
					});
					this.model.Nav_TrainType = null;
					this.model.Nav_TrainCheckType = null;
					this.model.Nav_Files.forEach(item => {
						if (item.RECORD_ID == undefined) {
							item.RECORD_ID = this.model.ID;
						}
						if (item.ORG_ID == undefined) {
							item.ORG_ID = this.model.ORG_ID;
						}
					});
					getRequest(this.model, "/SE/SETrainRecord/FullUpdate").then(res => {
						if (res) {
							uni.$showMsgFunc('操作成功!', () => {
								uni.navigateBack()
							}, 'success', 1000)
						}
					})
				}).catch(err => {
					uni.$showErrorInfo('请检查必填项，必填项不能为空')
				})
			},

		}
	}
</script>

<style scoped>
	/* @import url("../../../../style/css/editTemplate.css"); */

	.todo-page {
		/* padding: 16px 16px 70px; */
		overflow: hidden;
	}

	.card {
		margin: 20px 16px 40px 16px;
		/* border: 1px solid #EBEEF5; */
		padding: 20px 30px 40px 30px;
		/* box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px; */
		background-color: #ffffff;
		border-radius: 10px;
	}

	.background {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #edf1fd;
		z-index: -1;
	}

	.upload-title {
		font-size: 14px;
		color: #8e8b9c;
		line-height: 22px;
		padding: 8px 0px;
	}

	.demo-ruleForm>>>.u-form-item__body__left__content__label {
		font-size: 14px;
		color: #8e8b9c;
		/* justify-content: flex-start; */
	}

	.demo-ruleForm>>>.u-form-item__body__left__content__ {
		left: -11px;
		top: 0px
	}

	.demo-ruleForm>>>.u-textarea__field {
		font-size: 14px;
	}

	.demo-ruleForm>>>.u-cell__title-text {
		font-size: 14px;
	}

	.sub-form {
		margin: 20px 16px 140px 16px;
		padding: 20px 10px 10px 10px;
		background-color: #ffffff;
		border-radius: 10px;
	}

	.sub-form>>>.u-form-item__body__left__content {
		margin-right: 10px;
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 10px 16px;
		box-sizing: border-box;
		background: #edf1fd;
		z-index: 999;
	}
</style>