<!--
 * @Date: 2024-10-08 14:29:36
 * @LastEditors: lip
 * @LastEditTime: 2025-05-06 16:56:20
-->
<template>
	<view class="container" style="background-color: #f7f7f7;">
		<scroll-view scroll-y="true" :style="{height: edit?'calc(90vh - 150px)':'calc(100vh - 144px)'}">
			<view class="inner">
				<view class="part-title" style="display: flex;justify-content: space-between;">创业需求信息
					<view v-if="!edit&&formData.id&&formData.currentStatus!=3" class="btn"
						style="font-weight: normal;display: flex;" @click="edit=true">编辑<view class="icon-right">✏️</view></view>
				</view>
				<view class="inner-part">
					<view class="self-form">
						<view class="form-item">
							<view class="form-label">姓名 <text class="required">*</text></view>
							<view v-if="name" style="width: 100%;"
								class="disabledLine">
								{{ formData.personName || '请选择' }}
							</view>
							<view v-else style="width: 100%;" @click="openPersonChooser"
								:class="{disabledLine: !edit||!canChoosePerson, noValue: !formData.personName}">
								{{ formData.personName || '请选择' }}
							</view>
							<view class="icon-right">✏️</view>
						</view>
						<view class="form-item">
							<view class="form-label">有无场地需求 <text class="required">*</text></view>
							<view class="radio-group">
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywcdxq = '是'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywcdxq === '是' }]"></view>
									<text>是</text>
								</view>
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywcdxq = '否'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywcdxq === '否' }]"></view>
									<text>否</text>
								</view>
								<view v-else>{{ formData.ywcdxq }}</view>
							</view>
						</view>
						<view class="form-item">
							<view class="form-label">场地面积</view>
							
							<input type="number" :disabled="!edit" v-model="formData.requiredOfficeSpace" placeholder="请输入" :class="['form-input', { 'form-input-disabled': !edit }]"/>
							<view class="icon-right">✏️</view>
						</view>
						<view class="form-item">
							<view class="form-label">办公人数</view>
							<input type="number" :disabled="!edit" v-model="formData.bgrs" placeholder="请输入" :class="['form-input', { 'form-input-disabled': !edit }]"/>
							<view class="icon-right">✏️</view>
						</view>
						<view class="form-item">
							<view class="form-label">办公位置</view>
							<input type="text" :disabled="!edit" v-model="formData.bgdd" placeholder="请输入" :class="['form-input', { 'form-input-disabled': !edit }]"/>
							<view class="icon-right">✏️</view>
						</view>
						<view class="form-item">
							<view class="form-label">有无创业培训需求 <text class="required">*</text></view>
							<view class="radio-group">
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywcypxxq = '是'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywcypxxq === '是' }]"></view>
									<text>是</text>
								</view>
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywcypxxq = '否'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywcypxxq === '否' }]"></view>
									<text>否</text>
								</view>
								<view v-else>{{ formData.ywcypxxq }}</view>
							</view>
						</view>
<!--						<u-form-item label="是否意向接受创业培训" prop="isInterestedEntrepreneurshipGuidance" required>-->
<!--							<u-radio-group :disabled="!edit" v-model="formData.isInterestedEntrepreneurshipGuidance"-->
<!--								placement="row">-->
<!--								<u-radio :customStyle="{marginRight: '16px'}" label="是" name="是"></u-radio>-->
<!--								<u-radio :customStyle="{marginRight: '16px'}" label="否" name="否"></u-radio>-->
<!--							</u-radio-group>-->
<!--						</u-form-item>-->
						<view class="form-item">
							<view class="form-label">有无资金需求 <text class="required">*</text></view>
							<view class="radio-group">
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywzjxq = '是'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywzjxq === '是' }]"></view>
									<text>是</text>
								</view>
								<view 
									:class="['radio-item', { 'radio-disabled': !edit }]"
									@click="formData.ywzjxq = '否'" 
									v-if="edit">
									<view :class="['radio', { 'radio-checked': formData.ywzjxq === '否' }]"></view>
									<text>否</text>
								</view>
								<view v-else>{{ formData.ywzjxq }}</view>
							</view>
						</view>
						<view class="form-item">
							<view class="form-label">需求说明 <text class="required">*</text></view>
							<textarea :disabled="!edit" v-model="formData.jobDescription" placeholder="请输入" :class="['form-textarea', { 'form-textarea-disabled': !edit }]"></textarea>
						</view>
					</view>
				</view>
			</view>
<!--			<view class="inner" style="margin-top: 32rpx;">-->
<!--				<view class="inner-part">-->
<!--					<u&#45;&#45;form labelPosition="left" class="self-form" labelWidth="110">-->
<!--						<u-form-item label="需求说明" prop="qtxqsm">-->
<!--							<u-textarea :disabled="!edit" v-model="formData.qtxqsm" placeholder="请输入"></u-textarea>-->
<!--						</u-form-item>-->
<!--					</u&#45;&#45;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>
		<view class="button-area" v-if="edit">
			<view class="btn" @click="cancelPage">取消</view>
			<view class="btn reset" @click="formData.id ? getDetail(formData.id) : setDefaultValues()">重置</view>
			<view class="btn save" @click="saveInfo">保存</view>
		</view>
	</view>
</template>

<script>
	import {
		getPersonBase
	} from "@/packageRc/api/personinfo/index";
	import {
		addPersonDemand,
		updatePersonDemand,
		getPersonDemand
	} from "@/packageRc/api/needs/personDemand";
	import ImageUpload from './ImageUpload'
	import ChoosePerson from './choosePerson';
	import PlacePicker from "@/components/placePicker";
	 import dayjs from "dayjs";
	export default {
		components: {
	//		ChoosePerson,
		//	ImageUpload
		},
				props: {
					needId: {
				type: String,
				default: ''
			},
			name: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				edit: true,
				loading: false,
				canChoosePerson: false,
				formData: {
					id: '',
					personId: '',
					userId: '',
					personName: '',
					ywcdxq: '',
					requiredOfficeSpace: '',
					bgrs: '',
					bgdd: '',
					ywcypxxq: '',
					ywzjxq: '',
					jobDescription: '',
					actualSolveDate: '',
					solveDesc: '',
					actualSolvePeople: '',
					fileUrl: '',
					currentStatus: ''
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		async created() {
			this.loading = true;
			// await this.$delay(600)
			// this.setDefaultValues()
			// 		setTimeout(() => {
			// 	this.setName()
			// }, 0);
		},
		methods: {
			cancelPage() {
				if (this.formData.id) {
					this.edit = false;
					this.getDetail(this.formData.id)
				} else {
					uni.navigateBack()
				}
			},
			 			setName(){
			 	this.formData.personName = this.name
			 this.formData.personId = this.needId
			 this.formData.userId = this.needId
				console.log("this",this)
			
			 },
			openPersonChooser() {
				if (this.edit && this.canChoosePerson) {
					this.$refs.personChooser.open();
				}
			},
			personNameConfirm(event) {
				this.formData.personName = event.name
				this.formData.personId = event.id
				this.formData.userId = event.userId
				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.setDefaultValues()
				this.getPersonInfo()
				if(this.name){
					this.formData.personName = this.name
					this.formData.personId = this.needId
					this.formData.userId = this.needId
				}
				this.edit = true
			},
			getDetail(id) {
				getPersonDemand(id).then(res => {
					this.formData = res.data;
					this.edit = false
					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();
			},
			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()
				}
			},
			getPersonInfo() {
				this.loading = true;
				this.$store.dispatch("GetInfo").then((res) => {
					if (res.data.roles.indexOf('qunzhong') == -1) {
						this.canChoosePerson = true;
					} else {
						this.canChoosePerson = false;
						getPersonBase(res.data.user.userId).then(resp => {
							this.formData.personId = resp.data.id
							this.formData.userId = resp.data.userId
							this.formData.personName = resp.data.name
							this.formNameChange();
							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()}`
				const dayNew = dayjs(date).format("YYYY-MM-DD");
				this.formData.serviceRequirementTitle = `${this.formData.personName}_于${dayNew}_提出创业需求`
			},
			async saveInfo() {
				this.setName()
				try {
					// 验证必填项
					if (!this.formData.personName || this.formData.personName.trim() === '') {
						uni.showToast({ title: '请选择姓名！', icon: 'none' });
						return;
					}
					if (!this.formData.ywcdxq) {
						uni.showToast({ title: '请选择有无场地需求！', icon: 'none' });
						return;
					}
					if (!this.formData.ywcypxxq) {
						uni.showToast({ title: '请选择有无创业培训需求！', icon: 'none' });
						return;
					}
					if (!this.formData.ywzjxq) {
						uni.showToast({ title: '请选择有无资金需求！', icon: 'none' });
						return;
					}
					if (!this.formData.jobDescription || this.formData.jobDescription.trim() === '') {
						uni.showToast({ title: '请填写需求说明！', icon: 'none' });
						return;
					}

					// 显示全局加载
					uni.showLoading({ title: '保存中...' });
					// 根据 formData 是否有 id 来决定是更新还是新增
					let response;
					this.formData.demandType = 2;
					let successMessage;
					if (this.formData.id) {
						response = await updatePersonDemand(this.formData);
						successMessage = '修改成功';
					} else {
						response = await addPersonDemand(this.formData);
						successMessage = '保存成功';
					}

					// 检查响应码是否为200
					if (response.code === 200) {
						uni.showToast({ title: successMessage, icon: 'success' });
						// 如果是编辑模式，关闭编辑状态；否则返回上一页
						if (this.formData.id) {
							this.edit = false;
						} else {
							// 延迟1秒后返回上一页
							setTimeout(() => {
								uni.navigateBack();
							}, 1000);
						}
					}
				} catch (error) {
					console.error('保存失败:', error);
					uni.showToast({ title: '系统错误，请联系管理员！', icon: 'none' });
				} finally {
					// 确保加载页总是会被隐藏
					uni.hideLoading();
				}
			},

			// 设置默认选中
			setDefaultValues(){
				this.$set(this.formData, 'ywcdxq', '是')
				this.$set(this.formData, 'ywcypxxq', '是')
				this.$set(this.formData, 'isInterestedEntrepreneurshipGuidance', '是')
				this.$set(this.formData, 'ywzjxq', '是')
			},
			// 获取详情数据
			async getDetail(id) {
				try {
					this.loading = true;
					const response = await getPersonDemand(id);
					if (response.code === 200) {
						this.formData = { ...response.data };
					}
				} catch (error) {
					console.error('获取详情失败:', error);
					uni.showToast({ title: '获取详情失败', icon: 'none' });
				} finally {
					this.loading = false;
				}
			}
			// saveInfo() {
			// 	this.$refs.uForm.validate().then(res => {
			// 		if (this.formData.id) {
			// 			updateEntrepreneurshipService(this.formData).then(res => {
			// 				if (res.code == 200) {
			// 					uni.showToast({
			// 						title: '修改成功'
			// 					})
			// 					this.edit = false;
			// 				}
			// 			})
			// 		} else {
			// 			addEntrepreneurshipService(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: #3161c7;
		height: 100vh;
		background-image: url('https://rc.jinan.gov.cn/qcwjyH5/static/images/top.png');
		background-repeat: no-repeat;
		background-size: 100% auto;
	}

.inner {
  background: #eef1f5;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

}

.inner-part {
  width: 100%;
}

/* 为表单元素添加一些间距 */
.self-form {
  width: 100%;
}

/* 表单项目样式 */
.form-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24rpx;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 24rpx;
}

.form-label {
  width: 200rpx;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
  line-height: 48rpx;
}

.required {
  color: #f56c6c;
  margin-left: 4rpx;
}

.form-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #333;
  background: none;
  height: 48rpx;
  line-height: 48rpx;
}

.form-input-disabled {
  color: #909399;
  background-color: #f5f7fa;
}

.form-textarea {
  flex: 1;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #333;
  background: none;
  min-height: 120rpx;
  line-height: 40rpx;
}

.form-textarea-disabled {
  color: #909399;
  background-color: #f5f7fa;
}

.icon-right {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #A6A6A6;
  margin-left: 16rpx;
}

/* 单选框样式 */
.radio-group {
  flex: 1;
  display: flex;
  align-items: center;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 32rpx;
  cursor: pointer;
}

.radio-item.radio-disabled {
  cursor: not-allowed;
}

.radio {
  width: 28rpx;
  height: 28rpx;
  border-radius: 50%;
  border: 2rpx solid #dcdfe6;
  margin-right: 12rpx;
  position: relative;
}

.radio.radio-checked {
  border-color: #409eff;
  background-color: #409eff;
}

.radio.radio-checked::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #fff;
}

/* 调整按钮区域样式 */
.button-area {
  margin-top: 24rpx;
}
	.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;
	}
</style>
