<template>
	<view class="page">
		<view class="page-header">
			<view class="title df_flex" style="text-align: left;padding:50rpx 32rpx;">
				<u-icon name="arrow-left" color="#fff" size="38rpx" @tap="$tab.navigateBack()"></u-icon>
				<text style="margin-left: 30rpx;" class="df_flex_1">需求列表</text>
				<u-icon v-show="$store.getters.roles.includes('shequn')" @tap="$store.commit('SET_SHOWEXITPOPUP', true)" name="list"  size="44rpx" color="#fff"></u-icon>
			</view>
		</view>
		<view class="input-outer-part"
			style="padding-top: 12rpx;margin-top: 16rpx;padding-bottom: 0;max-height: unset;">
			<view class="search-line">
				<u-input placeholder="请输入群众姓名进行搜索" v-model="queryParams.searchValue" border="none" />
				<img src="https://rc.jinan.gov.cn/qcwjyH5/static/images/person/search.png" class="search-icon" @click="search()" />
			</view>
			<view class="inner"
				style="width: calc(100% + 64rpx);margin-left: -32rpx;height: 122rpx;position: relative;z-index: 2;">
				<PopupList :checkData="checkData" @searchCheck="search" ref="PopupList" @popupSearch="popupSearch" />
			</view>
			<view v-if="total" style="position: relative;padding-bottom: 16px;color: #000;">
				<text>共 {{ total }} 条</text>
			</view>
			<scroll-view :scroll-y="true" style="height: calc(100vh - 422rpx);position: relative;z-index: 1;"
				@scrolltolower="getBottomList">
				<u-swipe-action>
					<u-swipe-action-item @click="clickDelete(item)" v-for="(item, index) in tableData" :key="index"
						style="margin-bottom: 24rpx;border-radius: 16rpx;" :options="options1">
						<view class="job-item">
							<view class="top-container" @click="goNeedsDetail(item)">
								<view class="title-line">
									<view class="title">{{ item.personName }}</view>
								</view>
							<!-- 	<view class="status-card" v-if="item.currentStatus == 3">已完成服务</view>
								<view class="status-card in" v-else-if="item.untreatedCount <= 7">7天以内</view>
								<view class="status-card out"
									v-else-if="item.untreatedCount > 7&&item.untreatedCount <= 14">大于7天</view>
								<view class="status-card far" v-else>已超期</view> -->
								<view class="info"><text>状态：</text><text
										:class="item.currentStatus == 1 ? 'not' : item.currentStatus == 2 ? 'ing' : item.currentStatus == 3 ? 'finish' : '' ">
										{{ getDictLabel(item.currentStatus, currentStatusList) }}
									</text></view>
								<view class="info" v-if="queryParams.needsType == 1">
									<text>需求工种：</text>{{ item.jobWorkTypeName }}
								</view>
								<view class="info" v-if="queryParams.needsType == 3">
									<text>需求名称：</text>{{ item.serviceRequirementTitle }}
								</view>
								<view class="info"
									v-if="queryParams.needsType == 2||queryParams.needsType == 4||queryParams.needsType == 5">
									<text>需求名称：</text>{{ item.demandTitle }}
								</view>
							</view>
							<!--
								item.currentStatus = 1 待处理、2 处理中、 3 已完成
								queryParams.needsType 1 求职需求  2 援助需求、 3 创业需求、 4 培训需求 5其他需求 展示办结按钮

								item.currentStatus = 1待处理 、 item.currentStatus = 2 处理中
									求职需求列表(queryParams.needsType = 1) 展示 推荐、办理
									培训需求列表(queryParams.needsType = 4) 展示 培训、办理
									援助、创业、其他列表  展示办理
								item.currentStatus = 3 已完成
									统一展示 服务追溯
							-->

							<view class="item_btn df_flex df_align_center df_justify_center">
							<!-- 需求已处理完成的 展示服务追溯 -->
							<view v-if="item.currentStatus == 3" class="df_flex_1">
								<u-button type="primary" :plain="true" color="#BF5818" text="服务追溯"
									@click="serviceTraceButton(item)" :customStyle="{border: 'none'}"></u-button>
							</view>
							<!-- 需求处于待处理、处理中  -->
							<view v-else class="df_flex_1">
								<!-- 求职需求 -->
								<view v-if="queryParams.needsType == 1" class="df_flex">
									<u-button type="primary" :plain="true" color="#BF5818" text="推荐"
										:customStyle="{border: 'none'}"
										@click="requirementTraining(item, 1)"></u-button>
										<view class="line"></view>
									<u-button type="primary" :plain="true" color="#BF5818" text="办理"
										:customStyle="{border: 'none'}" @click="requirementHandling(item)"></u-button>
								</view>
								<!-- 培训需求 -->
								<view v-else-if="queryParams.needsType == 4" class="df_flex">
									<u-button type="primary" :plain="true" color="#BF5818" text="培训"
										:customStyle="{border: 'none'}"
										@click="requirementTraining(item, 4)"></u-button>
										<view class="line"></view>
									<u-button type="primary" :plain="true" color="#BF5818" text="办理"
										:customStyle="{border: 'none'}" @click="requirementHandling(item)"></u-button>
								</view>
								<!-- 其他需求 -->
								<view v-else>
									<u-button type="primary" :plain="true" color="#BF5818" text="办理"
										:customStyle="{border: 'none'}" @click="requirementHandling(item)"></u-button>
								</view>
								</view>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
				<view style="padding-bottom: 24rpx;">
					<img v-if="!total&&!loading" src="https://rc.jinan.gov.cn/qcwjyH5/static/images/person/empty.png"
						style="width: 100%;display: block;margin: 0 auto;" />
					<view v-if="loading"><u-loading-icon></u-loading-icon>
						<view style="text-align: center;color: #8E8E8E;font-size: 24rpx;">加载中~</view>
					</view>
					<view v-else-if="showMorePage" style="text-align: center;color: #1A62CE;font-size: 24rpx;">加载更多
					</view>
					<view style="text-align: center;color: #8E8E8E;font-size: 24rpx;" v-else>没有更多数据了~</view>
				</view>  
			</scroll-view>
		</view>
		<u-popup :show="openDeal" style="position: relative;z-index: 100;" closeOnClickOverlay @close="openDeal=false">
			<u--form class="self-form" labelPosition="top" :model="formData" :rules="rules" ref="uForm"
				labelWidth="300">
				<u-form-item label="实际解决时间" prop="actualSolveDate" required>
					<view class="bordered" style="width: 100%;" @click="showTime=true"
						: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="fileUrl" >
					<ImageUpload :fileList="fileList" @update="changeFile" :maxCount="6" />
				</u-form-item>

				<u-form-item label="解决说明" prop="solveDesc" required>
					<u-textarea v-model="formData.solveDesc" placeholder="请输入"></u-textarea>
					<u-icon slot="right" name="edit-pen" color="#A6A6A6"></u-icon>
				</u-form-item>
			</u--form>
			<view class="button-area">
				<view class="btn" @click="openDeal = false">取消</view>
				<view class="btn reset" @click="formData.actualSolveDate = '';formData.solveDesc = ''">重置</view>
				<view class="btn save" @click="finishJobRecommend">办结</view>
			</view>
		</u-popup>
		<view class="addNeeds" @click="goAddNeeds()">
			<img src="https://rc.jinan.gov.cn/qcwjyH5/static/images/person/addNeeds.png" />
		</view>
		<!-- <u-datetime-picker style="position: relative;z-index: 100;" :show="showTime" v-model="hopeSolveDate"
			mode="datetime" @confirm="confirmDate" closeOnClickOverlay @close="showTime=false"
			@cancel="showTime=false"></u-datetime-picker> -->


		<u-datetime-picker
			style="position: relative;z-index: 100;"
			:show="showTime"
			v-model="hopeSolveDate"
			mode="datetime"
			closeOnClickOverlay
			@confirm="confirmDate"
			@cancel="showTime=false"
			@close="showTime=false"
		></u-datetime-picker>


			<!-- 社区端 - 显示隐藏退出组件 -->
			<exitPopup />
	</view>
</template>
<script>
	import PopupList from "packageRc/components/PopupLists.vue";
	import ImageUpload from '/packageRc/components/ImageUpload'
	import {
		requirementCompletion
	} from '@/apiRc/company'
	import {
		listJobService,
		delJobService
	} from '@/apiRc/needs/jobService'
	import {
		listAssistService,
		delAssistService,
		finishAssistService
	} from '@/apiRc/needs/assistService'
	import {
		listEntrepreneurshipService,
		delEntrepreneurshipService,
		finishEntrepreneurshipService
	} from '@/apiRc/needs/entrepreneurshipService'
	import {
		listTrainService,
		delTrainService
	} from '@/apiRc/needs/trainService'
	import {
		listOtherService,
		delOtherService,
		finishOtherService
	} from '@/apiRc/needs/otherService'
	export default {
		components: {
			PopupList,
			ImageUpload
		},
		data() {
			return {
				checkData: [],
				options1: [{
					text: '删除'
				}],
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					needsType: 1
				},
				total: 0,
				showMorePage: true,
				tableData: [],
				person: {},
				loading: false,
				openDeal: false,
				showTime: false,
				formData: {
					actualSolveDate: '',
					solveDesc: ''
				},
				rules: {
					actualSolveDate: [{
						required: true,
						message: '请选择实际解决时间',
						trigger: ['blur', 'change'],
					}, ],
					solveDesc: [{
						required: true,
						message: '请填写解决说明',
						trigger: ['blur', 'change'],
					}, ],
				},
				hopeSolveDate: Number(new Date()),
				currentStatusList: [],
				fileList: [],
			}
		},
		onLoad({
			dictValue
		}) {
			this.queryParams.needsType = dictValue
			this.getCheckData()
		},
		onShow() {
			this.search();
		},
		methods: {
			// 新增需求
			goAddNeeds() {
				this.$tab.navigateTo(`/pages/needs/needDetail?activeType=${this.queryParams.needsType}&showTab=1`)
			},

			confirmDate(e) {
				this.showTime = false;
				// 获取选中的日期
				const date = e.value;
				// 使用 uView 的 uTime 方法格式化日期，包含时分秒
				const formattedDateTime = uni.$u.timeFormat(date, 'yyyy-mm-dd hh:MM:ss');
				// 设置表单数据
				this.formData.actualSolveDate = formattedDateTime;
			},

			// 需求推荐/培训
			requirementTraining(item, index) {
				if (index == 1) {
					this.$tab.navigateTo(
						`/pages/services/serviceDetail?personName=${item.personName}&personId=${item.personId}&jobDemandInfoId=${item.id}&jobWorkType=${item.jobWorkType}&type=3&showTab=1`
					)
				} else {
					this.$tab.navigateTo(
						`/pages/services/serviceDetail?personName=${item.personName}&personId=${item.personId}&skillTrainingId=${item.id}&personStatus=${item.personStatus}&type=4&showTab=1`
					)
				}
			},

			clickDelete(item) {
				this.loading = true;

				if (this.queryParams.needsType == 1) {
					delJobService(item.id).then((res) => {
						this.deleteFinish(res)
					});
				} else if (this.queryParams.needsType == 2) {
					delAssistService(item.id).then((res) => {
						this.deleteFinish(res)
					});
				} else if (this.queryParams.needsType == 3) {
					delEntrepreneurshipService(item.id).then((res) => {
						this.deleteFinish(res)
					});
				} else if (this.queryParams.needsType == 4) {
					delTrainService(item.id).then((res) => {
						this.deleteFinish(res)
					});
				} else if (this.queryParams.needsType == 5) {
					delOtherService(item.id).then((res) => {
						this.deleteFinish(res)
					});
				}
			},
			deleteFinish() {
				uni.showToast({
					title: '删除成功'
				})
				this.search()
			},
			goNeedsDetail(item) {
				uni.navigateTo({
					url: `/pages/needs/needDetail?id=${item.id}&type=${this.queryParams.needsType}&showTab=1`
				})
			},
			getDictLabel(value, list) {
				if (list) {
					let arr = list.filter(ele => ele.dictValue == value)
					if (arr.length) {
						return arr[0].dictLabel
					} else {
						return '--'
					}
				}
			},
			async getCheckData() {
				let workExperienceYears
				await this.getDicts('qcjy_gznx').then(res => {
					workExperienceYears = res.data
				})
				await this.getDicts('qcjy_xqlc').then(res => {
					this.currentStatusList = res.data;
					console.log(res.data)
				})
				this.checkData = [
					// {
					// 	name: "需求类型",
					// 	type: "needsType",
					// 	data: [{dictLabel: '求职需求', dictValue: '1'},{dictLabel: '援助需求', dictValue: '2'},{dictLabel: '创业需求', dictValue: '3'},{dictLabel: '培训需求', dictValue: '4'},{dictLabel: '其他需求', dictValue: '5'}],
					// 	activeIndex: 0,
					// },
					{
						name: "需求状态",
						type: "currentStatus",
						data: [{
							dictLabel: '全部',
							dictValue: ''
						}].concat(this.currentStatusList),
						activeIndex: 0,
					},
					// {
					// 	name: "工作经验",
					// 	type: "workExperienceYears",
					// 	data: [{dictLabel: '全部', dictValue: ''}].concat(workExperienceYears),
					// 	activeIndex: 0,
					// },

				];
			},
			popupSearch(queryParams) {
				queryParams.forEach((item, index) => {
					if (item.data[item.activeIndex].dictLabel == "全部") {
						this.queryParams[item.type] = "";
					} else {
						this.queryParams[item.type] = item.data[item.activeIndex].dictValue;
					}
				});
				this.search()
			},
			search() {
				this.showMorePage = true;
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 10;
				this.tableData = [];
				this.total = 0;
				this.getList();
			},

			// 服务追溯
			serviceTraceButton(item) {
				// 定义需求类型与对应的字符串映射
				const demandTypeMap = {
					1: 'job', // 求职需求
					2: 'assist', // 援助需求
					3: 'entrepreneurship', // 创业需求
					4: 'train', // 培训需求
					5: 'other' // 其他需求
				};
				// 获取当前的需求类型字符串
				const demandType = demandTypeMap[this.queryParams.needsType] || 'other';
				// 使用映射后的字符串构建URL并导航
				this.$tab.navigateTo(`/pages/services/serviceTraceability?id=${item.id}&demandType=${demandType}`);
			},
			// 触底加载
			getBottomList() {
				if (
					this.queryParams.pageNum * this.queryParams.pageSize >=
					this.total
				) {
					this.showMorePage = false;
				} else if (
					this.queryParams.pageNum * this.queryParams.pageSize <
					this.total
				) {
					this.queryParams.pageNum++;
					this.getList();
					if (
						this.queryParams.pageNum * this.queryParams.pageSize >=
						this.total
					) {
						this.showMorePage = false;
					}
				}
			},
			// 获取列表
			async getList() {
				this.loading = true;
				if (this.queryParams.needsType == 1) {
					listJobService(this.queryParams).then((res) => {
						this.gettedData(res)
					});
				} else if (this.queryParams.needsType == 2) {
					listAssistService(this.queryParams).then((res) => {
						this.gettedData(res)
					});
				} else if (this.queryParams.needsType == 3) {
					listEntrepreneurshipService(this.queryParams).then((res) => {
						this.gettedData(res)
					});
				} else if (this.queryParams.needsType == 4) {
					listTrainService(this.queryParams).then((res) => {
						this.gettedData(res)
					});
				} else if (this.queryParams.needsType == 5) {
					listOtherService(this.queryParams).then((res) => {
						this.gettedData(res)
					});
				}
			},
			gettedData(res) {
				if (res.code == 200) {
					if (res.rows.length < 10) {
						this.showMorePage = false;
					}
					this.loading = false;
					this.tableData = this.tableData.concat(res.rows);
					this.total = res.total;
				} else {
					this.loading = false;
					uni.showToast({
						title: res.msg,
						icon: "none",
					});
				}
			},

			// 需求办结
			requirementHandling(item) {
				this.openDeal = true;
				this.formData = {
					id: item.id,
					currentStatus: '3'
				}
			},

			// 需求推荐
			requirementRecommendation(item) {
				this.$tab.navigateTo(
					`/pages/services/serviceDetail?personName=${item.personName}&personId=${item.personId}&jobDemandInfoId=${item.id}&jobWorkType=${item.jobWorkType}&type=3&showTab=1`
				)
			},

			// 办结按钮
			async finishJobRecommend() {
				try {
					// 检查必填项
					if (!this.formData.actualSolveDate) {
						throw new Error('解决时间不能为空');
					}
					if (!this.formData.solveDesc) {
						throw new Error('解决说明不能为空');
					}
					// 显示全局加载
					this.$showLoading();
					// 根据 queryParams.needsType 获取对应的 URL
					const obj = {
						1: '/demand/personJobDemandInfo/JdJobDemandDone',
						2: '/demand/personAssistDemandInfo/assistDone',
						3: '/demand/personEntrepreneurshipDemandInfo/entrepreneurshipDone',
						4: '/demand/personTrainDemandInfo/JdTrainDemandDone',
						5: '/demand/personOtherDemandInfo/otherDemandDone',
					};

					const url = obj[this.queryParams.needsType];
					if (!url) {
						throw new Error('无效的需求类型');
					}
					const {
						code,
						msg
					} = await requirementCompletion(url, this.formData);

					// 检查响应码是否为200
					if (code === 200) {
						// 显示成功的提示信息
						this.$u.toast(msg);
						this.openDeal = false;
						this.search();
					}
				} catch (error) {
					// 处理错误并显示提示信息
					this.$u.toast('请检查必填项填写');
					console.error('完成需求时发生错误:', error);
				} finally {
					// 确保加载页总是会被隐藏
					this.$hideLoading();
				}
			},
			// async finishJobRecommend() {
			// 	this.openDeal = true;
			// 	const obj = {
			// 		1: '/demand/personJobDemandInfo/JdJobDemandDone',
			// 		2: '/demand/personAssistDemandInfo/assistDone',
			// 		3: '/demand/personEntrepreneurshipDemandInfo/entrepreneurshipDone',
			// 		4: '/demand/personTrainDemandInfo/JdTrainDemandDone',
			// 		5: '/demand/personOtherDemandInfo/otherDemandDone',
			// 	}
			// 	if (!this.formData.actualSolveDate) return this.$u.toast('解决时间不能为空');
			// 	if (!this.formData.solveDesc) return this.$u.toast('解决说明不能为空');
			// 	const {
			// 		code,
			// 		data,
			// 		msg
			// 	} = await requirementCompletion(obj[this.queryParams.needsType], this.formData)
			// 	if (code == 200) {
			// 		this.$u.toast(msg)
			// 		this.openDeal = false
			// 		this.search()
			// 	}
			// },

			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)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.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;
	}

	.search-line {
		border-radius: 32px;
		background: #FFFFFF;
		box-sizing: border-box;
		border: 1px solid #107AFD;
		height: 64rpx;
		border-radius: 32rpx;
		padding: 0 32rpx;
		display: flex;
		align-items: center;
		position: relative;
		z-index: 1;
		margin-top: 24rpx;

		.search-icon {
			width: 40rpx;
		}
	}

	.job-item {
		position: relative;
		.item_btn{
			height: 100rpx;
			border-top: 1px solid #e3e8ee;
		}
		.line{
			position: absolute;
			right: 50%;
			bottom: 20rpx;
			width: 1px;
			height: 60rpx;
			background-color: #e3e8ee;
		}
		.status-card {
			position: absolute;
			right: 0;
			top: 0;
			border-radius: 0 16rpx 0 16rpx;
			width: 160rpx;
			line-height: 40rpx;
			text-align: center;
			color: #fff;
			background: #B2C0D1;
			border: 1px solid #9BA9B9;
			font-size: 24rpx;

			&.in {
				background: #29D297;
				border: 1px solid #1BBA83;
			}

			&.out {
				background: #ECB83D;
				border: 1px solid #D7892B;
			}

			&.far {
				background: #EC7737;
				border: 1px solid #C24F1A;
			}
		}

		.top-container {
			background: #fff;
			border-radius: 16rpx;
			padding: 32rpx;

			// margin-bottom: 24rpx;
			.title-line {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 16rpx;

				.type-tag {
					line-height: 40rpx;
					width: 128rpx;
					font-size: 24rpx;
					color: #fff;
					text-align: center;

					&.qz {
						background: #28CB5E;
					}

					&.yz {
						background: #DD6728;
					}

					&.cy {
						background: #23B5C5;
					}

					&.px {
						background: #DDA728;
					}

					&.qt {
						background: #2870DD;
					}
				}

				.title {
					color: #3D3D3D;
					width: calc(100% - 137rpx);
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					line-height: 40rpx;
				}

				.salary {
					width: 33%;
					color: #FA6553;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					text-align: right
				}
			}

			.info {
				color: #3D3D3D;
				margin-bottom: 7rpx;
				font-size: 28rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;

				text {
					color: #8E8E8E;
				}

				.not {
					color: #EC7737;
					font-weight: bold;
				}

				.ing {
					color: #ECB83D;
					font-weight: bold;
				}

				.finish {
					color: #21C88D;
					font-weight: bold;
				}
			}
		}

		.function-btn {
			color: #BF5818;
			border-top: 1px solid #E2E8EF;
			padding-bottom: 6rpx;
			line-height: 90rpx;
			text-align: center;
		}
	}

	.self-form {
		padding: 32rpx;

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

	.button-area {
		padding: 24rpx 32rpx 68rpx;
		background: #fff;
		display: flex;
		box-sizing: border-box;
		border-radius: 16px 16px 0px 0px;
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

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

	.addNeeds {
		position: fixed;
		right: 0;
		bottom: 150rpx;
		width: 150rpx;
		overflow: hidden;
		z-index: 10;
		border-radius: 44rpx;
		border-radius: 75rpx;

		img {
			display: block;
			width: 100%;
		}
	}
</style>
