<!--
 * @Date: 2024-10-08 14:29:36
 * @LastEditors: shirlwang
 * @LastEditTime: 2025-11-04 14:16:11
-->
<template>

	<view class="input-outer-part">
		<scroll-view scroll-y="true" :style="{height: edit?'calc(100vh - 150px)':'calc(100vh - 144px)'}">
			<view class="inner">
				<view class="part-title" style="display: flex;justify-content: space-between;">服务信息
					<view v-if="!edit&&formData.id" class="btn" style="font-weight: normal;display: flex;"
						@click="edit=true">编辑<u-icon name="edit-pen" color="#A6A6A6"></u-icon></view>
				</view>
				<view class="inner-part">
					<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm" class="self-form"
						labelWidth="110">
						<u-form-item label="姓名" prop="personName" required>
							<view style="width: 100%;" @click="openPersonChooser"
								:class="{disabledLine: !edit, noValue: !formData.personName}">
								{{ formData.personName || '请选择' }}
							</view>
							<u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon>
						</u-form-item>
						<!-- <u-form-item label="人员状态" prop="personStatus">
              <view style="width: 100%;" @click="showPicker('personStatus')" :class="{disabledLine: !edit, noValue: !formData.personStatus}">{{ getDictLabel(formData.personStatus, dict.personStatus)||'请选择' }}</view>
              <u-icon slot="right" name="arrow-down" color="#A6A6A6" ></u-icon>
            </u-form-item> -->
						<u-form-item label="培训人员" prop="trainingStaff" required>
							<u--input :disabled="!edit" v-model="formData.trainingStaff" border="none"
								placeholder="请输入"></u--input>
							<u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon>
						</u-form-item>
						<u-form-item label="培训时间" prop="time" required>
							<view style="width: 100%;" @click="showPicker('time')"
								:class="{disabledLine: !edit, noValue: !formData.time}">{{ formData.time||'请选择' }}
							</view>
							<u-icon slot="right" name="arrow-down" color="#A6A6A6"></u-icon>
						</u-form-item>
						<u-form-item label="培训题目" prop="trainingTopic" required>
							<u-textarea :disabled="!edit" v-model="formData.trainingTopic"
								placeholder="请输入"></u-textarea>
						</u-form-item>
						<u-form-item label="培训内容" prop="trainingContent" required>
							<u-textarea :disabled="!edit" v-model="formData.trainingContent"
								placeholder="请输入"></u-textarea>
						</u-form-item>
					</u--form>
				</view>
			</view>
			<view class="inner">
				<view class="part-title" style="margin-top: 32rpx;">附件信息</view>
				<view class="inner-part">
					<u--form labelPosition="left" class="self-form" labelWidth="110">
						<u-form-item label="附件" prop="fileUrl">
							<ImageUpload :fileList="fileList" @update="changeFile" :maxCount="6" />
						</u-form-item>
					</u--form>
				</view>
			</view>
			<!-- 办理完成后 需求说明 -->
			<req-comp :form="{
				actualSolveDate: formData.actualSolveDate,
				actualSolvePeople: formData.actualSolvePeople,
				solveDesc: formData.solveDesc,
				fileUrl: formData.fileUrl
			}" />

		</scroll-view>
		<u-datetime-picker :show="show.time" v-model="dates.time" mode="date" @confirm="confirmDate('time', $event)"
			@cancel="cancelPicker('time')"></u-datetime-picker>
		<u-datetime-picker :show="show.actualSolveDate" v-model="dates.actualSolveDate" mode="date"
			@confirm="confirmDate('actualSolveDate', $event)"
			@cancel="cancelPicker('actualSolveDate')"></u-datetime-picker>
		<!-- <u-picker :show="show.personStatus" :columns="[dict.personStatus]" keyName="dictLabel" @confirm="pickerConfirm('personStatus', $event)" @cancel="cancelPicker('personStatus')"></u-picker> -->
		<choose-person :choiceType="4" ref="personChooser" @confirm="personNameConfirm" />
		<u-popup :show="openDeal" style="position: relative;z-index: 2;">
			<u--form class="self-form popup" labelPosition="top" :model="formData" :rules="rules" ref="uForm"
				labelWidth="300" style="width: calc(100% - 64rpx);margin: 0 auto;">
				<u-form-item label="实际办理时间" prop="actualSolveDate" required>
					<view class="bordered" style="width: 100%;" @click="showPicker('actualSolveDate')"
						:class="{noValue: !formData.actualSolveDate}">{{ formData.actualSolveDate||'请选择' }}</view>
					<u-icon slot="right" name="arrow-down" color="#A6A6A6"></u-icon>
				</u-form-item>
				<u-form-item label="办理说明" prop="solveDesc" required>
					<u-textarea v-model="formData.solveDesc" placeholder="请输入"></u-textarea>
				</u-form-item>
			</u--form>
			<view class="button-area" style="width: 100%;margin-left: 0;box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);">
				<view class="btn" @click="openDeal = false">取消</view>
				<view class="btn reset" @click="form.actualSolveDate = '';formData.solveDesc = ''">重置</view>
				<!-- <view class="btn save" @click="saveDeal">办结</view> -->
			</view>
		</u-popup>
		<view class="button-area" v-if="edit">
			<view class="btn" @click="cancelPage">取消</view>
			<!-- <view class="btn save" @click="finishSkillTrain">办结</view> -->
			<view class="btn save" @click="formData.skillTrainingStatus='2';saveInfo()">保存</view>
		</view>
	</view>
</template>

<script>
	import {
		addSkillTrain,
		updateSkillTrain,
		getSkillTrain
	} from "@/packageRc/apiRc/service/skillTrain";
	import ImageUpload from '@/packageRc/components/ImageUpload'
	import ChoosePerson from './choosePerson.vue';
	export default {
		components: {
			ChoosePerson,
			ImageUpload
		},
		data() {
			return {
				fileList: [],
				edit: true,
				personBase: {},
				dates: {},
				formData: {
					personName: '',
					trainingStaff: '',
					time: '',
					trainingTopic: '',
					trainingContent: '',
				},
				rules: {
					personName: [{
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change'],
					}, ],
					trainingStaff: [{
						required: true,
						message: '请填写培训人员',
						trigger: ['blur', 'change'],
					}, ],
					time: [{
						required: true,
						message: '请选择培训时间',
						trigger: ['blur', 'change'],
					}, ],
					trainingTopic: [{
						required: true,
						message: '请填写培训题目',
						trigger: ['blur', 'change'],
					}, ],
					trainingContent: [{
						required: true,
						message: '请填写培训内容',
						trigger: ['blur', 'change'],
					}, ],
				},
				dict: {},
				show: {},
				loading: false,
				openDeal: false,
				form: {},
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		created() {
			this.$getDict('qcjy_ryzt').then(res => {
				this.dict.personStatus = res.data
			})
			this.loading = true;
		},
		methods: {
			cancelPage() {
				if (this.formData.id) {
					this.edit = false;
					this.getDetail(this.formData.id)
				} else {
					uni.navigateBack()
				}
			},
			saveDeal() {
				if (!this.formData.actualSolveDate) {
					uni.showToast({
						title: '请填写实际解决时间!',
						icon: 'none'
					})
					return;
				}
				if (!this.formData.solveDesc) {
					uni.showToast({
						title: '请填写办理说明!',
						icon: 'none'
					})
					return;
				}
				this.formData.skillTrainingStatus = '3'
				this.openDeal = false;
				this.saveInfo()
			},
			finishSkillTrain() {
				this.$refs.uForm.validate().then(res => {
					this.openDeal = true;
				}).catch(() => {
					uni.showToast({
						title: '请检查必填项填写',
						icon: 'none'
					})
				})
			},
			openPersonChooser() {
				if (this.edit) {
					this.$refs.personChooser.open();
				}
			},
			personNameConfirm(event) {
				this.formData.personName = event.personName
				this.formData.personId = event.personId
				this.formData.skillTrainingId = event.id
				this.formNameChange();
				this.$forceUpdate();
			},
			changeFile(e) {
				// 清空当前的 fileUrl 数组
				this.formData.fileUrl = [];
				// 如果 e 有长度（即用户选择了文件）
				if (e.length) {
					// 遍历每个文件对象并获取其 url
					for (let data of e) {
						const url = data.data ? data.data.url : data.url;
						this.formData.fileUrl.push(url);
					}
				}
				this.formData.fileUrl = this.$arrayToString(this.formData.fileUrl)
			},
			addOne() {
				this.formData = {}
				this.edit = true
			},
			// addForPerson(options) {
			// 	this.formData = {
			// 		personName: options.personName,
			// 		personId: options.personId,
			// 		skillTrainingId: options.skillTrainingId
			// 	}
			// 	this.edit = true
			// },
			getDetail(id) {
				getSkillTrain(id).then(res => {
					this.formData = res.data || {};
					this.edit = false
					if(this.formData.fileUrl) {
						this.fileList = this.$processFileUrl(this.formData.fileUrl)
					}

				})
			},
			confirmDate(type, e) {
				this.show[type] = false;
				let date = new Date(e.value)
				this.formData[type] =
					`${date.getFullYear()}-${(date.getMonth()+1)>9?(date.getMonth()+1):('0'+(date.getMonth()+1))}-${date.getDate()>9?date.getDate():('0'+date.getDate())}`
				this.$forceUpdate();
			},
			goBack() {
				uni.navigateBack();
			},
			cancelPicker(type) {
				this.show[type] = false
				this.$forceUpdate();
			},

			// 单独设置 人员姓名 和 id
			setPersonName(data){
				this.formData.personName = data.personName
				this.formData.personId = data.personId
				this.formData.skillTrainingId = data.skillTrainingId
				// this.addForPerson(data)
			},

			getDictLabel(value, list) {
				if (list) {
					let arr = list.filter(ele => ele.dictValue == value)
					if (arr.length) {
						return arr[0].dictLabel
					} else {
						return '请选择'
					}
				}
			},
			pickerConfirm(type, event) {
				this.show[type] = false
				this.formData[type] = event.value[0].dictValue
				this.$forceUpdate();
			},
			showPicker(type) {
				if (this.edit) {
					this.show[type] = true
					this.$forceUpdate()
				}
			},
			formNameChange() {
				let date = new Date()
				let day =
					`${date.getFullYear()}-${(date.getMonth()+1) + 1 > 9 ? (date.getMonth()+1) + 1: '0'+((date.getMonth()+1) + 1)}-${date.getDate() > 9 ? date.getDate(): '0'+date.getDate()}`
				this.formData.trainingTopic =
					`${this.$store.state.user.nick}_于${day}对人员_${this.formData.personName}_进行XXXX培训`;
			},

			async saveInfo() {
				try {
					// 验证表单
					const isValid = await this.$refs.uForm.validate();
					if (!isValid) {
						throw new Error('请检查必填项填写');
					}
					// 显示全局加载
					this.$showLoading();
					// 根据 formData 是否有 id 来决定是更新还是新增
					let response;
					let successMessage;
					if (this.formData.id) {
						response = await updateSkillTrain(this.formData);
						successMessage = '修改成功';
					} else {
						response = await addSkillTrain(this.formData);
						successMessage = '保存成功';
					}

					if (response.code === 200) {
						this.$u.toast(successMessage);
						// 如果是编辑模式，关闭编辑状态；否则返回上一页
						if (this.formData.id) {
							this.edit = false;
						} else {
							await this.$delay(1000); // 延迟1秒后返回上一页
							uni.navigateBack();
						}
					}
				} catch (error) {
					// 处理错误并显示提示信息
					this.$u.toast('错误详情:' + error);;
				} finally {
					// 确保加载页总是会被隐藏
					uni.hideLoading();
				}
			},


			// saveInfo() {
			// 	this.$refs.uForm.validate().then(res => {
			// 		if (this.formData.id) {
			// 			updateSkillTrain(this.formData).then(res => {
			// 				if (res.code == 200) {
			// 					uni.showToast({
			// 						title: '修改成功'
			// 					})
			// 					this.edit = false;
			// 				}
			// 			})
			// 		} else {
			// 			addSkillTrain(this.formData).then(res => {
			// 				if (res.code == 200) {
			// 					uni.showToast({
			// 						title: '保存成功'
			// 					})
			// 					uni.navigateBack();
			// 				}
			// 			})
			// 		}
			// 	}).catch(() => {
			// 		uni.showToast({
			// 			title: '请检查必填项填写',
			// 			icon: 'none'
			// 		})
			// 	})
			// }
		}
	}
</script>

<style lang="scss">
	.page ::v-deep .u-navbar__content {
		background-color: transparent !important;
	}

	.page {
		background-color: #EEF1F5 !important;
		height: 100vh;
		background-image: url('https://rc.jinan.gov.cn/qcwjyH5/static/images/top.png');
		background-repeat: no-repeat;
		background-size: 100% auto;
	}

	.button-area {
		padding: 24rpx 32rpx 68rpx;
		width: calc(100% + 64rpx);
		margin-left: -32rpx;
		background: #fff;
		display: flex;
		box-sizing: border-box;
		margin-top: 40rpx;
		border-radius: 16px 16px 0px 0px;

		.btn {
			line-height: 72rpx;
			width: 176rpx;
			margin-right: 16rpx;
			font-size: 28rpx;
			border: 1px solid #B8C5D4;
			color: #282828;
			text-align: center;
			border-radius: 8rpx;
		}

		.reset {
			background: #DCE2E9;
		}

		.save {
			background: linear-gradient(103deg, #1D64CF 0%, #1590D4 99%);
			color: #fff;
			border: 0;
			flex-grow: 1;
		}
	}

	.noValue {
		color: rgb(192, 196, 204);
	}

	.self-form.popup {
		padding-top: 32rpx;

		.bordered {
			border: 1rpx solid #dadbde;
			padding: 9px;
			border-radius: 4px;
		}
	}

	.disabledLine {
		background: rgb(245, 247, 250);
		cursor: not-allowed;
	}
</style>
