<!--
 * @Date: 2024-10-08 14:29:36
 * @LastEditors: shirlwang
 * @LastEditTime: 2025-11-04 16:18:33
-->
<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-blqksm: 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="类型" v-if="!userId" required>
							<view class="status_radio df_flex df_flex_1">
								<u-radio-group v-model="formData.type" placement="column">
									<u-radio v-for="(item, index) in validType" :key="index" :label="item.label"
										:name="item.value">
									</u-radio>
								</u-radio-group>
							</view>
						</u-form-item>

						<u-form-item label="被服务对象" prop="serviceObjectName" required v-if="formData.type == 0">
							<view class="picker-view" :class="{selected: formData.serviceObjectName}" @click="openPersonChooser">
								<text :class="formData.serviceObjectName ? 'picker-text' : 'picker-placeholder'">
									{{ formData.serviceObjectName || '请选择被服务对象' }}
								</text>
							</view>
						</u-form-item>

						<u-form-item label="被服务对象" prop="serviceObjectName" required v-else>
							<view class="picker-view" :class="{selected: formData.serviceObjectName}" @click="$refs.enterpriseChooser.open()">
								<text :class="formData.serviceObjectName ? 'picker-text' : 'picker-placeholder'">
									{{ formData.serviceObjectName || '请选择被服务对象' }}
								</text>
							</view>
						</u-form-item>

						<u-form-item label="服务时间" prop="practicalSolutionTime" required>
							<view class="picker-view" :class="{selected: formData.practicalSolutionTime}" @click="showPicker('practicalSolutionTime')">
								<text :class="formData.practicalSolutionTime ? 'picker-text' : 'picker-placeholder'">
									{{ formData.practicalSolutionTime || '请选择服务时间' }}
								</text>
							</view>
						</u-form-item>
						<u-form-item label="经办人" prop="agentUserName" required>
							<u--input :disabled="!edit" v-model="formData.agentUserName" border="none"
								placeholder="请输入"></u--input>
							<u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon>
						</u-form-item>
						<u-form-item label="服务类型" prop="demandType" required>
							<view class="picker-view" :class="{selected: formData.demandType}" @click="showPicker('demandType')">
								<text :class="formData.demandType ? 'picker-text' : 'picker-placeholder'">
									{{ getDictLabel(formData.demandType, dict.demandType) || '请选择服务类型' }}
								</text>
							</view>
						</u-form-item>
						<u-form-item label="服务内容" prop="serviceContent" required>
							<view class="picker-view" :class="{selected: formData.serviceContent}" @tap="showServiceContentSelect">
								<text :class="formData.serviceContent ? 'picker-text' : 'picker-placeholder'">
									{{ getMultiDictLabel(formData.serviceContent, dict.serviceContent) || '请选择服务内容' }}
								</text>
							</view>
						</u-form-item>
						<u-form-item label="电话沟通结果" prop="dhgtjg" v-if="formData.demandType == '5'" required>
							<view class="picker-view" :class="{selected: formData.dhgtjg}" @click="showPicker('dhgtjg')">
								<text :class="formData.dhgtjg ? 'picker-text' : 'picker-placeholder'">
									{{ getDictLabel(formData.dhgtjg, dict.dhgtjg) || '请选择电话沟通结果' }}
								</text>
							</view>
						</u-form-item>

						<!-- 新增：人员状态，展示方式与服务类型一致 -->
						<u-form-item label="人员状态" prop="personStatus" required >
							<view class="picker-view" :class="{selected: formData.personStatus}" @click="showPicker('personStatus')">
								<text :class="formData.personStatus ? 'picker-text' : 'picker-placeholder'">
									{{ getDictLabel(formData.personStatus, dict.personStatus) || '请选择人员状态' }}
								</text>
							</view>
						</u-form-item>
						<u-form-item label="服务情况说明" prop="blqksm" required>
							<u-textarea :disabled="!edit" v-model="formData.blqksm" 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.practicalSolutionTime" v-model="hopeSolveDate" mode="date" @confirm="confirmDate('practicalSolutionTime', $event)"
			@cancel="cancelPicker('practicalSolutionTime')" @close="cancelPicker('practicalSolutionTime')" closeOnClickOverlay></u-datetime-picker>

		<choose-person ref="personChooser" @confirm="personNameConfirm" />

		<enterprise-list-pop ref="enterpriseChooser" @confirm="enterpriseConfirm" />

		<u-picker :show="show.dhgtjg" :columns="[dict.dhgtjg]" keyName="dictLabel"
				  @confirm="pickerConfirm('dhgtjg', $event)" @cancel="cancelPicker('dhgtjg')"></u-picker>

		<u-picker :show="show.demandType" :columns="[dict.demandType]" keyName="dictLabel"
				  @confirm="pickerConfirm('demandType', $event)" @cancel="cancelPicker('demandType')"></u-picker>

		<u-picker :show="show.personStatus" :columns="[dict.personStatus]" keyName="dictLabel"
			  @confirm="pickerConfirm('personStatus', $event)" @cancel="cancelPicker('personStatus')"></u-picker>

		<u-popup :show="show.serviceContent" mode="bottom" @close="cancelSelect">
			<view class="select-content">
				<view class="select-header">
					<text @tap="cancelSelect">取消</text>
					<text class="title">服务内容</text>
					<text @tap="confirmSelect">确定</text>
				</view>
				<scroll-view scroll-y class="checkbox-scroll">
					<view class="checkbox-group">
						<u-checkbox-group v-model="tempServiceContent" placement="column">
							<view 
								v-for="(item, index) in dict.serviceContent" 
								:key="index" 
								class="checkbox-item"
							>
								<u-checkbox 
									:name="item.dictValue"
									:label="item.dictLabel"
								></u-checkbox>
							</view>
						</u-checkbox-group>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<view class="button-area" v-if="edit">
			<view class="btn" @click="cancelPage">取消</view>
			<view class="btn reset" @click="formData = {}" v-if="!formData.id">重置</view>
			<view class="btn save" @click="saveInfo">保存</view>
		</view>
	</view>
</template>

<script>
	import {
		addInvestigate,
		updateInvestigate,
		getInvestigate
	} from "@/packageRc/apiRc/service/investigate";
	import ImageUpload from '@/packageRc/components/ImageUpload'
	import ChoosePerson from './choosePerson.vue';
	export default {
		components: {
			ChoosePerson,
			ImageUpload,
		},
		props: {
			userId: {
				type: String,
				default: ''
			},
			name:{
				type: String,
				default: ''
			}
		},
		data() {
			return {
				edit: true,
				personBase: {},
				dates: {},
				hopeSolveDate: Number(new Date()),
				formData: {
					type: 0,
					serviceContent: [],
					personStatus: '' // 新增字段
				},
				rules: {
					serviceObjectName: [{
						required: true,
						message: '请选择被服务人员',
						trigger: ['blur', 'change'],
					}, ],
					unitName: [{
						required: true,
						message: '请选择被服务对象',
						trigger: ['blur', 'change'],
					}],
					practicalSolutionTime: [{
						required: true,
						message: '请选择服务时间',
						trigger: ['blur', 'change'],
					}, ],
					agentUserName: [{
						required: true,
						message: '请填写服务人员',
						trigger: ['blur', 'change'],
					}, ],
					demandType: [{
						required: true,
						message: '请填写服务类型',
						trigger: ['blur', 'change'],
					}, ],
					blqksm:[{
						required: true,
						message: '请填写服务情况说明',
						trigger: ['blur', 'change'],
					}],
					dhgtjg: [
						{
							required: false,
							validator: (rule, value, callback) => {
								if (this.formData.demandType === '5' && (!value || value === '')) {
									callback(new Error('请输入电话沟通结果'));
								} else {
									callback();
								}
							},
							trigger: ['blur', 'change'],
						}
					],
					personStatus: [{
						required: true,
						message: '请选择人员状态',
						trigger: ['blur', 'change'],
					}]
				},
				dict: {
					serviceContent: [],
					personStatus: [] // 新增
				},
				show: {
					serviceContent: false,
					personStatus: false // 新增
				},
				loading: false,
				fileList: [],
				validType: [{
						label: "个人",
						value: "0",
					},
					{
						label: "企业",
						value: "1",
					},
				],
				serviceContentList: [],
				tempServiceContent: [],
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		created() {
			this.serviceontent();
			this.loading = true;
			let arr = [{
				key: 'qyjy_dhgtjg',
				prop: 'dhgtjg'
			},
			{
				key: 'qyjy_zdfwlx',
				prop: 'demandType'
			},
			// 新增人员状态字典
			{
				key: 'qcjy_ryzt', // 如有实际key请替换
				prop: 'personStatus'
			},
			]
			arr.forEach(ele => {
				this.$getDict(ele.key).then(res => {
					this.dict[ele.prop] = res.data
					this.$forceUpdate();
				})
			})
			this.$getDict("qcjy_fwnr").then(res => {
				console.log("获取到的服务内容数据：", res.data);
				this.dict.serviceContent = res.data;
				this.$forceUpdate();
			});
		},
		mounted() {
			setTimeout(() => {
			this.setName()

			}, 0)

		},
		methods: {
			 serviceontent(){
				this.$getDict("qcjy_fwnr").then(res=>{
					console.log("服务内容列表",res.data)
				})
			},
			cancelPage() {
				if (this.formData.id) {
					this.edit = false;
					this.getDetail(this.formData.id)
				} else {
					uni.navigateBack()
				}
			},
			setName(){
			this.formData.serviceObjectName = this.name
			this.formData.serviceObjectId = this.userId
			this.formData.userId = this.userId

			this.$forceUpdate();
			},
			openPersonChooser() {
				if (this.edit) {
					this.$refs.personChooser.open();
				}
			},
			personNameConfirm(event) {
				this.formData.serviceObjectName = event.name
				this.formData.serviceObjectId = event.id
				this.$forceUpdate();
			},

			// 选择企业
			enterpriseConfirm({
				unitName,
				id
			}) {
				this.$set(this.formData, 'serviceObjectName', unitName)
				this.$set(this.formData, 'serviceObjectId', id)
			},
			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 = {
					type: "0"
				}
				this.edit = true
			},
			getDetail(id) {
				getInvestigate(id).then(res => {
					const data = res.data;
					// 处理服务内容为数组
					if (data.serviceContent) {
						data.serviceContent = typeof data.serviceContent === 'string' 
							? data.serviceContent.split(',').filter(Boolean)
							: data.serviceContent;
					} else {
						data.serviceContent = [];
					}
					this.formData = data;
					this.edit = false;
					this.fileList = this.$processFileUrl(this.formData.fileUrl);
				})
			},
			confirmDate(type, e) {
				this.show[type] = false;
				// 获取选中的日期
      			const date = e.value;
      			// 使用 uView 的 uTime 方法格式化日期，包含时分秒
      			const formattedDateTime = uni.$u.timeFormat(date, "yyyy-mm-dd hh:MM:ss");
				this.formData[type] = formattedDateTime
				this.$forceUpdate();
			},

			goBack() {
				uni.navigateBack();
			},
			cancelPicker(type) {
				this.show[type] = false
				this.$forceUpdate();
			},
			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;
				if (type === 'serviceContent') {
					// 多选处理
					this.formData[type] = event.value.map(item => item.dictValue);
				} else {
					// 其他字段保持原样
					this.formData[type] = event.value[0].dictValue;
				}
				this.$forceUpdate();
			},
			showPicker(type) {
				if (this.edit) {
					this.show[type] = true
					this.$forceUpdate()
				}
			},
			async saveInfo() {
				try {
					const isValid = await this.$refs.uForm.validate();
					if (!isValid) {
						throw new Error('请检查必填项填写');
					}
					
					let demandType = this.formData.demandType;
					// 确保 serviceContent 是数组并且有值
					if (!Array.isArray(this.formData.serviceContent) || this.formData.serviceContent.length === 0) {
						this.$u.toast("请选择服务内容！");
						return;
					}
					
					// 处理服务内容数组
					this.formData.fwnr = this.formData.serviceContent.join(',');
					
					// 显示全局加载
					this.$showLoading();

					// 根据 formData 是否有 id 来决定是更新还是新增
					let response;
					let successMessage;
					if (this.formData.id) {
						response = await updateInvestigate(this.formData);
						successMessage = '修改成功';
					} else {
						console.log("h5表单",this.formData)
						delete this.formData.type
						response = await addInvestigate(this.formData);
						successMessage = '保存成功';
					}

					// 检查响应码是否为200
					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("请填写完整内容");
				} finally {
					// 确保加载页总是会被隐藏
					this.$hideLoading();
				}
			},
			getMultiDictLabel(values, list) {
				if (!values || !list) return '';
				const valueArray = typeof values === 'string' ? values.split(',') : values;
				if (!Array.isArray(valueArray)) return '';
				
				return valueArray.map(value => {
					const item = list.find(ele => ele.dictValue == value);
					return item ? item.dictLabel : '';
				}).filter(Boolean).join('、');
			},
			checkboxGroupChange(values) {
				this.formData.serviceContent = values;
				this.$forceUpdate();
			},
			processServiceContentList() {
				this.serviceContentList = this.dict.serviceContent.map(item => ({
					label: item.dictLabel,
					value: item.dictValue
				}));
			},
			showServiceContentSelect() {
				console.log("点击了服务内容");
				if (this.edit) {
					this.tempServiceContent = Array.isArray(this.formData.serviceContent) 
						? [...this.formData.serviceContent] 
						: [];
					this.show.serviceContent = true;
					this.$forceUpdate();
				}
			},
			cancelSelect() {
				console.log("取消选择");
				this.show.serviceContent = false;
				this.$forceUpdate();
			},
			confirmSelect() {
				console.log("确认选择", this.tempServiceContent);
				this.formData.serviceContent = [...this.tempServiceContent];
				this.show.serviceContent = false;
				this.$forceUpdate();
			},
		}
	}
</script>

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

	.input-outer-part {
		.status_radio {
			.u-radio-group {
				display: flex;
				flex-direction: row;
			}

			.u-radio {
				margin-right: 50rpx;
			}
		}
	}

	.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);
	}

	.disabledLine {
		background: rgb(245, 247, 250);
		cursor: not-allowed;
	}
	
	// 改进选择器样式
	.picker-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding: 28rpx 36rpx;
		background: #ffffff;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		min-height: 88rpx;
		box-sizing: border-box;
		transition: all 0.3s ease;
		position: relative;
		
		&:active {
			background: #f8f9fa;
			border-color: #007aff;
			transform: scale(0.98);
		}
		
		&::after {
			content: '';
			position: absolute;
			right: 36rpx;
			top: 50%;
			transform: translateY(-50%);
			width: 0;
			height: 0;
			border-left: 12rpx solid transparent;
			border-right: 12rpx solid transparent;
			border-top: 12rpx solid #999999;
		}
		
		.picker-text {
			color: #333333;
			font-size: 28rpx;
			flex: 1;
		}
		
		.picker-placeholder {
			color: #999999;
			font-size: 28rpx;
		}
	}
	
	// 选中状态的样式
	.picker-view.selected {
		border-color: #1D64CF;
		background: #f0f8ff;
		
		&::after {
			border-top-color: #1D64CF;
		}
	}

	.checkbox-container {
		padding: 10rpx 0;
		
		.u-checkbox-group {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
		}
		
		.u-checkbox {
			margin-right: 30rpx;
			margin-bottom: 20rpx;
		}
	}

	.select-content {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		
		.select-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1px solid #EBEEF5;
			
			text {
				font-size: 28rpx;
				
				&:first-child {
					color: #909399;
					padding: 10rpx 20rpx;
				}
				
				&:last-child {
					color: #1D64CF;
					font-weight: 500;
					padding: 10rpx 20rpx;
				}
				
				&.title {
					font-size: 32rpx;
					color: #303133;
					font-weight: 500;
				}
			}
		}
		
		.checkbox-scroll {
			max-height: 700rpx;
			padding: 20rpx 0;
		}
		
		.checkbox-group {
			padding: 0 30rpx;
		}
		
		.checkbox-item {
			padding: 24rpx 0;
			border-bottom: 1px solid #F2F6FC;
			display: flex;
			align-items: center;
			
			&:last-child {
				border-bottom: none;
			}
			
			// 修改 checkbox 样式
			::v-deep .u-checkbox {
				width: 100%;
				margin: 0;
				display: flex;
				align-items: center;
				
				&__label {
					font-size: 28rpx;
					color: #303133;
					margin-left: 16rpx;
				}
				
				&__icon-wrap {
					width: 36rpx;
					height: 36rpx;
					border-radius: 6rpx;
					border: 2rpx solid #DCDFE6;
					display: flex;
					align-items: center;
					justify-content: center;
					
					&--checked {
						background-color: #1D64CF;
						border-color: #1D64CF;
					}
				}
			}
		}
	}

	// 增加选中态的样式
	::v-deep .u-checkbox__icon-wrap--checked {
		.u-checkbox__icon {
			color: #fff;
			transform: scale(0.8);
		}
	}
</style>
