<!--
 * @Date: 2024-10-08 14:29:36
 * @LastEditors: shirlwang
 * @LastEditTime: 2025-11-04 17:33:17
-->
<template>
	<view class="input-outer-part">
		<scroll-view scroll-y="true" :style="{height: edit?'calc(100vh - 380rpx)':'calc(100vh - 194rpx)'}">
			<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">编辑<u-icon name="edit-pen"
							color="#A6A6A6"></u-icon></view>
				</view>
				<view class="inner-part">
					<uni-forms labelPosition="left" :model="formData" :rules="rules" ref="uForm" class="self-form"
						labelWidth="100">
						<uni-forms-item label="姓名" name="personName" required
						v-if="$store.getters.roles.includes('shequn'|| $store.getters.roles.includes('gly'))"
						>
							<view style="width: 100%;" @click="openPersonChooser"
								:class="{disabledLine: !edit||!canChoosePerson, noValue: !formData.personName}">
								{{ formData.personName || '请选择' }}
							</view>
							<!-- <u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon> -->
						</uni-forms-item>
						<!--
						<uni-forms-item label="服务需求标题" name="serviceRequirementTitle" required>
							<u--textarea :disabled="!edit" v-model="formData.serviceRequirementTitle"
								placeholder="请输入"></u--textarea>
							<u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon>
						</uni-forms-item> -->
						<uni-forms-item label="有无场地需求" name="ywcdxq" required>
							<!-- <radio-group :disabled="!edit" :value="formData.ywcdxq" placement="row">
								<radio :customStyle="{marginRight: '16px'}" label="是" value="是">是</radio>
								<radio :customStyle="{marginRight: '16px'}" label="否" value="否">否</radio>
							</radio-group> -->
							<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>
						</uni-forms-item>
						<uni-forms-item label="场地面积" name="cdmj">
							<input :disabled="!edit" v-model="formData.cdmj" border="none"
								placeholder="请输入"/>
							<!-- <u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon> -->
						</uni-forms-item>
						<uni-forms-item label="办公人数" name="bgrs">
							<input :disabled="!edit" v-model="formData.bgrs" border="none"
								placeholder="请输入"/>
							<!-- <u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon> -->
						</uni-forms-item>
						<uni-forms-item label="办公位置" name="bgdd">
							<input :disabled="!edit" v-model="formData.bgdd" border="none"
								placeholder="请输入"/>
							<!-- <u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon> -->
						</uni-forms-item>
						<uni-forms-item label="有无创业培训需求" name="ywcypxxq" required>
							<radio-group :disabled="!edit" :value="formData.ywcypxxq"
								placement="row">
								<radio :customStyle="{marginRight: '16px'}" label="是" value="是">是</radio>
								<radio :customStyle="{marginRight: '16px'}" label="否" value="否">否</radio>
							</radio-group>
						</uni-forms-item>
<!--						<uni-forms-item label="是否意向接受创业培训" name="isInterestedEntrepreneurshipGuidance" required>-->
<!--							<radio-group :disabled="!edit" v-model="formData.isInterestedEntrepreneurshipGuidance"-->
<!--								placement="row">-->
<!--								<radio :customStyle="{marginRight: '16px'}" label="是" name="是"></radio>-->
<!--								<radio :customStyle="{marginRight: '16px'}" label="否" name="否"></radio>-->
<!--							</radio-group>-->
<!--						</uni-forms-item>-->
						<uni-forms-item label="有无资金需求" name="ywzjxq" required>
							<radio-group :disabled="!edit" :value="formData.ywzjxq" placement="row">
								<radio :customStyle="{marginRight: '16px'}" label="是" value="是">是</radio>
								<radio :customStyle="{marginRight: '16px'}" label="否" value="否">否</radio>
							</radio-group>
						</uni-forms-item>
						<uni-forms-item label="需求说明" name="jobDescription" required>
							<textarea :disabled="!edit" v-model="formData.jobDescription" placeholder="请输入"></textarea>
						</uni-forms-item>
						<!-- 		<uni-forms-item label="希望解决日期" name="hopeSolveDate" required>
							<view style="width: 100%;" @click="showPicker('hopeSolveDate')"
								:class="{disabledLine: !edit, noValue: !formData.hopeSolveDate}">
								{{ formData.hopeSolveDate||'请选择' }}
							</view>
							<u-icon slot="right" name="arrow-down" color="#A6A6A6"></u-icon>
						</uni-forms-item> -->
					</uni-forms>
				</view>
			</view>
<!--			<view class="inner" style="margin-top: 32rpx;">-->
<!--				<view class="inner-part">-->
<!--					<u&#45;&#45;form labelPosition="left" class="self-form" labelWidth="110">-->
<!--						<uni-forms-item label="需求说明" name="qtxqsm">-->
<!--							<textarea :disabled="!edit" v-model="formData.qtxqsm" placeholder="请输入"></textarea>-->
<!--						</uni-forms-item>-->
<!--					</u&#45;&#45;form>-->
<!--				</view>-->
<!--			</view>-->
			<!-- 	<view class="inner">
				<view class="part-title" style="margin-top: 32rpx;">附件信息</view>
				<view class="inner-part">
					<uni-forms labelPosition="left" class="self-form" labelWidth="110">
						<uni-forms-item label="附件" name="fileUrl">
							<ImageUpload :fileList="fileList" @update="changeFile" :maxCount="6" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</view> -->

			<!-- 办理完成后 需求说明 -->
			<req-comp :form="{
				actualSolveDate: formData.actualSolveDate,
				actualSolvePeople: formData.actualSolvePeople,
				solveDesc: formData.solveDesc,
				fileUrl: formData.fileUrl
			}" />
		</scroll-view>
		<u-datetime-picker :show="show.hopeSolveDate" v-model="dates.hopeSolveDate" mode="date"
			@confirm="confirmDate('hopeSolveDate', $event)" @cancel="cancelPicker('hopeSolveDate')"></u-datetime-picker>
		<choose-person ref="personChooser" @confirm="personNameConfirm" />
		<view class="button-area" v-if="edit">
			<view class="btn" @click="cancelPage">取消</view>
			<view class="btn reset" @click="getPersonInfo()">重置</view>
			<view class="btn save" @click="saveInfo">保存</view>
		</view>
	</view>
</template>

<script>
	import {
		getPersonBase
	} from "@/apiRc/person";
		import {
		addPersonDemand,
		updatePersonDemand,
		getPersonDemand
	} from "@/apiRc/needs/personDemand";
	import ImageUpload from '/packageRc/components/ImageUpload'
	import ChoosePerson from '/packageRc/pages/needs/components/choosePerson';
	import dayjs from "dayjs";
	export default {
		components: {
			ChoosePerson,
			ImageUpload
		},
				props: {
					needId: {
				type: String,
				default: ''
			},
			name: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				fileList: [],
				edit: true,
				personBase: {},
				dates: {},
				formData: {
					jobDescription:"",
					demandType:"2",
					personName: '',
					personId:"",
					userId:"",
					serviceRequirementTitle: '',
					isAcceptAssistance: '',
					isAcceptApprovalResult: '',

				},
				rules: {

					ywcdxq: [{
						required: true,
						message: '请选择有无场地需求',
						trigger: ['blur', 'change'],
					}, ],
					ywcypxxq: [{
						required: true,
						message: '请选择有无创业培训需求',
						trigger: ['blur', 'change'],
					}, ],
					isInterestedEntrepreneurshipGuidance: [{
						required: true,
						message: '请选择是否意向接受创业培训',
						trigger: ['blur', 'change'],
					}, ],
					ywzjxq: [{
						required: true,
						message: '请选择有无资金需求',
						trigger: ['blur', 'change'],
					}, ],

				},
				dict: {},
				show: {},
				currentCityArr: [],
				originalDept: [],
				currentCity: '请选择',
				bysj: '',
				loading: false,
				jobTypeList: [],
				route: {},
				canChoosePerson: false,
			}
		},
		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

			// this.$forceUpdate();
			// },
			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(userId) {
				this.formData = {}
				this.setDefaultValues()
				this.getPersonInfo()
				if(this.name){
					this.formData.personName = this.name
					this.formData.userId = userId
				}
				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() {
				uni.showLoading()
				try {
					if (!this.formData.jobDescription || this.formData.jobDescription.trim() === '') {
						uni.showToast({title: '请填写需求说明！', icon: 'none'});
						return;
					}
					// 验证表单
					const isValid = await this.$refs.uForm.validate();
					if (!isValid) {
						throw new Error('请检查必填项填写');
					}
					// 显示全局加载
					// 根据 formData 是否有 id 来决定是更新还是新增
					let response;
					this.formData.demandType = 2;
					let successMessage;
					if (this.formData.id) {
						updatePersonDemand(this.formData).then(response => {
							uni.showToast({title: '修改成功', icon: 'none'});
							if (response.code == 200) {
								// 如果是编辑模式，关闭编辑状态；否则返回上一页
								if (this.formData.id) {
									this.edit = false;
								} else {
									setTimeout(() => {
										uni.navigateBack();
									}, 2000);
								}
							}
						})
					} else {
						addPersonDemand(this.formData).then(response => {
							uni.showToast({title: '保存成功', icon: 'none'});
							if (response.code == 200) {
								// 如果是编辑模式，关闭编辑状态；否则返回上一页
								if (this.formData.id) {
									this.edit = false;
								} else {
									setTimeout(() => {
										uni.navigateBack();
									}, 2000);
								}
							}
						})
					}
				} catch (error) {
					if(error.length){
						uni.showToast({title: '请填写完整信息！', icon: 'none'});
					}else{
						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', '是')
			}
			// 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">

	.noValue {
		color: rgb(192, 196, 204);
	}
/* 单选框样式 */
.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;
}

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