<template>
	<view class="switch-roles">
		<nav-bar title="岗位要求" color="#000"></nav-bar>
		<view class="roles-content">
			<view class="content">
				<view class="title">继续填写</view>
				<view class="step-progress flex align-center">
					<view class="circle-wrapper">
						<view class="check-icon check-active">
							<u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
						</view>
						<view class="step-progress-text">填写基本信息</view>
					</view>
					<view class="line blue"></view>
					<view class="line blue"></view>
					<view class="circle-wrapper">
						<view class="check-icon check-active">
							<u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
						</view>
						<view class="step-progress-text">填写岗位要求</view>
					</view>
				</view>

				<!-- 经验要求 -->
				<view class="check-title-big">经验要求</view>
				<view class="check-select" @click="showExper = true">
					<view class="select-txt">{{ selectedExper || "请选择经验要求" }}</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>

				<!-- 最低学历 -->
				<view class="check-title-big">最低学历</view>
				<view class="check-select" @click="showLevel = true">
					<view class="select-txt">{{ selectedLevel || "请选择学历" }}</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>

				<!-- 薪资范围 -->
				<view class="check-title-big">薪资范围</view>
				<view class="check-select" @click="showMoney = true">
					<view class="select-txt">
						<template v-if="selectedSalary">{{ selectedSalary + ' · ' + salaryTimes }}</template>
						<template v-else>请选择合理的薪资范围</template>
					</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>
				
				<!-- 跨境标签 -->
				<view class="check-title-big">跨境标签</view>
				<view class="check-select" @click="goJobSkill">
					<view class="select-txt">{{ positionTag && positionTag.length > 0 ? positionTag.join(',') :
						"被选中的关键词将突出展示给牛人" }}</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>

				<!-- 福利待遇 -->
				<view class="check-title-big">福利待遇（选填）</view>
				<view class="check-select" @click="goFund">
					<view class="select-txt">{{ welfareValue || "请填写奖金绩效" }}</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>

				<!-- 工作地址 -->
				<view class="check-title-big">工作地址</view>
				<view class="check-select" @click="goAddAddress">
					<view class="select-txt">{{ address || stationName.fullText || "请填写精确的工作地点" }}</view>
					<u-icon name="arrow-down" color="#D3D3D6" size="22"></u-icon>
				</view>

				<view class="txt-desc">
					温馨提示：职位类型、职位名称和工作城市发布后不可修改，请您确保信息正确 <br /><br />
					发布职位即表示同意遵守《招聘行为管理规范》，如违反规则将导致账号被锁定
				</view>
			</view>
		</view>

		<view class="button-section">
			<view class="link-btn" v-if="showNotPushBtn" @click="handleToIndex">稍后发布</view>
			<view class="submit-btn" @click="submitPost">发布</view>
		</view>

		<!-- 经验选择器 -->
		<u-select v-model="showExper" :list="listExper" title="请选择经验" @confirm="onExperConfirm"
			@cancel="showExper = false"></u-select>

		<!-- 学历选择器 -->
		<u-select v-model="showLevel" :list="listLevel" title="请选择学历" @confirm="onLevelConfirm"
			@cancel="showLevel = false"></u-select>

		<!-- 薪资选择器 -->
		<u-select v-model="showMoney" mode="mutil-column" :list="listMoney" title="请选择月薪范围" @confirm="onMoneyConfirm"
			@cancel="showMoney = false"></u-select>
	</view>
</template>

<script>
import navBar from "@/components/nav-bar/index.vue";
export default {
	data() {
		return {
			// 选中值（用于页面渲染）
			selectedExper: "", // 经验
			selectedLevel: "", // 学历
			selectedSalary: "", // 薪资范围
			welfareTag: "", // 福利待遇
			welfareText: '', // 福利待遇描述
			positionTag: "", // 职位关键词
			stationName: [],
			companyName: "",
			companyId: "",
			status: 1,
			pid: "",
			address: "",
			salaryTimes: "",
			jobTitle: '',

			// 选择器显示控制
			showExper: false,
			showLevel: false,
			showMoney: false,
			// isBack: false,

			// 经验选择数据源
			listExper: [{
				label: "不限",
				value: "不限"
			},
			{
				label: "1年以内",
				value: "1年以内"
			},
			{
				label: "1-3年",
				value: "1-3年"
			},
			{
				label: "3-5年",
				value: "3-5年"
			},
			{
				label: "5-8年",
				value: "5-8年"
			},
			{
				label: "8年以上",
				value: "8年以上"
			},
			],

			// 学历选择数据源
			listLevel: [{
				label: "不限",
				value: "不限"
			},
			{
				label: "专科",
				value: "专科"
			},
			{
				label: "本科",
				value: "本科"
			},
			{
				label: "硕士",
				value: "硕士"
			},
			{
				label: "博士",
				value: "博士"
			},
			],

			// 薪资选择数据源（修正格式）
			listMoney: [
			  [
			    { value: "3k", label: "3k" },
			    { value: "4k", label: "4k" },
			    { value: "5k", label: "5k" },
			    { value: "6k", label: "6k" },
				{ value: "7k", label: "7k" },
			    { value: "8k", label: "8k" },
			    { value: "10k", label: "10k" },
			    { value: "12k", label: "12k" },
			    { value: "15k", label: "15k" },
			    { value: "18k", label: "18k" },
			    { value: "20k", label: "20k" },
				{ value: "25k", label: "25k" },
				{ value: "30k", label: "30k" },
				{ value: "35k", label: "35k" },
				{ value: "40k", label: "40k" },
				{ value: "45k", label: "45k" },
				{ value: "50k", label: "50k" },
				{ value: "55k", label: "55k" },
				{ value: "60k", label: "60k" },
				{ value: "65k", label: "65k" },
				{ value: "70k", label: "70k" },
				{ value: "75k", label: "75k" },
				{ value: "80k", label: "80k" },
				{ value: "85k", label: "85k" },
				{ value: "90k", label: "90k" },
				{ value: "95k", label: "95k" },
				{ value: "100k", label: "100k" }
			  ],
			  [
			    { value: "3k", label: "3k" },
			    { value: "4k", label: "4k" },
			    { value: "5k", label: "5k" },
			    { value: "6k", label: "6k" },
				{ value: "7k", label: "7k" },
			    { value: "8k", label: "8k" },
			    { value: "10k", label: "10k" },
			    { value: "12k", label: "12k" },
			    { value: "15k", label: "15k" },
			    { value: "18k", label: "18k" },
			    { value: "20k", label: "20k" },
			    { value: "25k", label: "25k" },
			    { value: "30k", label: "30k" },
			    { value: "35k", label: "35k" },
			    { value: "40k", label: "40k" },
			    { value: "45k", label: "45k" },
			    { value: "50k", label: "50k" },
			    { value: "55k", label: "55k" },
			    { value: "60k", label: "60k" },
			    { value: "65k", label: "65k" },
			    { value: "70k", label: "70k" },
			    { value: "75k", label: "75k" },
			    { value: "80k", label: "80k" },
			    { value: "85k", label: "85k" },
			    { value: "90k", label: "90k" },
			    { value: "95k", label: "95k" },
			    { value: "100k", label: "100k" }
			  ],
			  [
			    { value: "12薪", label: "12薪" },
			    { value: "13薪", label: "13薪" },
			    { value: "14薪", label: "14薪" },
			    { value: "15薪", label: "15薪" },
			    { value: "16薪", label: "16薪" },
			    { value: "17薪", label: "17薪" },
			    { value: "18薪", label: "18薪" },
			    { value: "19薪", label: "19薪" },
			    { value: "20薪", label: "20薪" },
			    { value: "21薪", label: "21薪" },
			    { value: "22薪", label: "22薪" },
			    { value: "23薪", label: "23薪" }
			  ]
			],

			numList: [{
				name: "填写基本信息"
			},
			{
				name: "选择职位要求"
			},
			],
			type: '',
			ruleClassifyId:'',//岗位id
			dataInfo:{},
			companyAddressInfo:{},
			isAdmin: true,
			companyInfo: {},
		};
	},
	components: {
		navBar,
	},
	computed: {
		welfareValue() {
			return this.welfareTag + this.welfareText
		},
		// 显示稍后发布按钮
		showNotPushBtn() {
			// 显示条件
			// 1. 管理员，企业是待审核状态
			// 2. 员工申请加入是待审核状态
			let adminStatus = this.isAdmin && this.status != 2
			let employeeStatus = !this.isAdmin && this.companyInfo?.companyUser?.status == 1
			if (adminStatus || employeeStatus) {
				return true
			}
			return false
		}
	},
	onLoad(options) {
		console.log(options)
		if(options.dataInfo){
			this.dataInfo = JSON.parse(options.dataInfo)
		}
		if(options.ruleClassifyId){
			this.ruleClassifyId = options.ruleClassifyId;
		}
		// if (options.isBack == 'true') {
		// 	this.isBack = true;
		// }
		// 接收上个页面传递的公司名称参数
		// if (options.companyName) {
		// 	this.companyName = decodeURIComponent(options.companyName);
		// 	console.log('接收的公司名称：', this.companyName);
		// }
		this.getcompanystatus()

		// if (options.status) {
		// 	this.status = decodeURIComponent(options.status);
		// 	console.log('接收的公司状态：', this.status);
		// } else {
		// 	//this.status = uni.getStorageSync('companyStatus')
		// 	this.getcompanystatus()
		// }
		if(options.companyAddressInfo){
			this.companyAddressInfo = JSON.parse(decodeURIComponent(options.companyAddressInfo));
		}
		if (options.workData) {
			let workData = JSON.parse(decodeURIComponent(options.workData));
			this.selectedExper = workData.experience;
			this.selectedLevel = workData.education;
			this.selectedSalary = workData.salaryRange || '';
			this.salaryTimes = workData.salaryTimes || '';
			this.welfareTag = workData.welfareTag || '';
			this.welfareText = workData.welfareText || '';
			this.positionTag = workData.positionTag ? workData.positionTag.split (',') : [];
			this.address = workData.address || this.companyAddressInfo.address;
			this.stationName.fullText = workData.address || this.companyAddressInfo.fullText, //地址
			this.stationName.latitude = workData.lat || this.companyAddressInfo.latitude
			this.stationName.longitude = workData.lng || this.companyAddressInfo.longitude
			this.stationName.province = workData.province || this.companyAddressInfo.province
			this.stationName.city = workData.city || this.companyAddressInfo.city
			this.stationName.district = workData.county || this.companyAddressInfo.district
			this.jobTitle = workData.ruleClassifyName
			console.log(11111,this.$queue.getData('companyAddress'))
			console.log(this.address)
		}
		this.fundListener = uni.$on("fundData", (data) => {
			console.log("接收到的福利数据：", data);
			this.welfareText = data.text
			this.welfareTag = data.tagText; // 赋值给当前页面变量
		});
		this.fundListener = uni.$on("skillsUpdated", (data) => {
			console.log("接收到的职位技能数据：", data);
			this.positionTag = data.selectedTags; // 赋值给当前页面变量
		});
		this.fundListener = uni.$on("addressData", (data) => {
			this.address = data.fullText;
			this.stationName = data;
			this.stationName.fullText = data.fullText;
		});
		if (options.companyId) {
			this.companyId = options.companyId;
			console.log('接收的公司ID：', this.companyId);
		} else {
			this.companyId = uni.getStorageSync('companyId') || ""
		}





		if (options.pid) {
			this.pid = options.pid;
			this.type = options.type;
			if (options.type && options.type == 'updata') {
				this.getInfo()
			}
			console.log('接收PID：', this.pid);
		} 
		this.getcompanystatus()
	},
	onUnload() {
		// 页面关闭时移除监听，避免内存泄漏
		if (this.fundListener) {
			uni.$off("fundData");
		}
	},
	methods: {
		// 处理经验选择（核心修复：直接接收选中的label）
		onExperConfirm(selectedItem) {
			// 不同版本u-select返回格式可能是对象或数组，这里兼容处理
			if (Array.isArray(selectedItem)) {
				this.selectedExper = selectedItem[0]?.label || "";
			} else {
				this.selectedExper = selectedItem?.label || "";
			}
			this.showExper = false; // 关闭选择器
		},

		// 处理学历选择（核心修复）
		onLevelConfirm(selectedItem) {
			if (Array.isArray(selectedItem)) {
				this.selectedLevel = selectedItem[0]?.label || "";
			} else {
				this.selectedLevel = selectedItem?.label || "";
			}
			this.showLevel = false;
		},


		/**
				 * 获取岗位详情
				 */
		getInfo() {
			this.$Request.getT("/app/postPush/selectPostPushDetails", {
				// userId:uni.getStorageSync('userId'),
				postPushId: this.pid
			}).then(res => {
				if (res.code == 0) {
					this.selectedExper = res.data.experience
					this.selectedLevel = res.data.education
					this.selectedSalary = res.data.salaryRange
					this.welfareTag = res.data.welfareTag
					this.welfareText = res.data.welfareText
					this.positionTag = res.data.positionTag
					this.address = res.data.address
					this.stationName.fullText = res.data.address
					this.stationName.latitude = res.data.lat
					this.stationName.longitude = res.data.lng
					this.stationName.province = res.data.province
					this.stationName.city = res.data.city
					this.stationName.district = res.data.county
					this.salaryTimes = res.data.salaryTimes
				} else {
					uni.showToast({
						title: '数据有误',
						icon: 'none',  // 注意这里需要加引号
						duration: 2000, // 可选：设置提示框显示时长
						complete() {    // 正确的回调函数写法
							uni.navigateBack();
						}
					});

				}
			})
		},

		// 查询用户企业状态
		getcompanystatus() {
			this.$Request.get("/app/company/selectCompanyByUserId", "")
				.then((res) => {
					if (res.code != 0) {
						uni.showToast({
							title: res.msg || "查询状态失败",
							icon: "none"
						});
						return;
					}
					if (res.data?.companyUser?.isAdmin != 1) {
						this.isAdmin = false
					}
					this.companyInfo = res.data
					this.status = res.data.status || "";
					this.companyName = res.data.companyAllName || '';
					this.$queue.setData('companyId', res.data.companyId);
					this.$queue.setData('companyStatus', res.data.companyStatus);
					console.log("查询用户企业状态", this.status)
				})
				.catch((err) => {
					console.error("查询失败：", err);
					uni.showToast({
						title: "网络异常",
						icon: "none"
					});
				});
		},



		// 处理薪资范围选择（核心修复）
		onMoneyConfirm(selectedItems) {
			let minSalary = selectedItems[0].value.replace('k', '')
			let maxSalary = selectedItems[1].value.replace('k', '')
			if (Number(minSalary) > Number(maxSalary)) {
				return this.$queue.showToast('最低薪资不能大于最高薪资')
			}
			// 多列选择器返回数组，取每列选中的label拼接
			console.log(selectedItems)
			if (Array.isArray(selectedItems) && selectedItems.length >= 2) {
				const min = selectedItems[0]?.label || "";
				const max = selectedItems[1]?.label || "";
				const xin = selectedItems[2]?.label || "";
				this.selectedSalary = `${min}-${max}`;
				this.salaryTimes = `${xin}`
			}
			this.showMoney = false;
		},

		// 跳转页面并接收参数（福利待遇）
		goFund() {
			let tag = ''
			let text = ''
			if (this.welfareTag) {
				tag = this.welfareTag;
			}
			if (this.welfareText) {
				text = this.welfareText
			}
			uni.navigateTo({
				url: `/package/jobIntention/fund?tag=${encodeURIComponent(tag)}&text=${encodeURIComponent(text)}`,
				events: {
					// 监听子页面发送的福利数据
					fundData: (data) => {
						this.welfareTag = data;
					},
				},
			});
		},

		// 跳转页面并接收参数（职位关键词）
		goJobSkill() {
			uni.navigateTo({
				url: "/package/jobIntention/jobSkills?tag=" + encodeURIComponent(this.positionTag) + '&jobTitle=' + this.jobTitle + '&ruleClassifyId=' + this.ruleClassifyId,
				events: {
					skillsUpdated: (data) => {
						this.positionTag = data.selectedTags;
					},
				},
			});
		},

		// 跳转页面并接收参数（工作地址）
		goAddAddress() {
			let address = {
				...this.stationName
			}
			uni.navigateTo({
				url: "/package/jobIntention/addAddress?address=" + JSON.stringify(address),
				events: {
					addressData: (data) => {
						let value = {
							...data
						}
						this.stationName = value;
						this.stationName.fullText = value.fullText;
						this.address = value.fullText;
					},
				},
			});
		},

		// 提交表单
		submitPost() {
			// 验证必填项
			if (!this.selectedExper) {
				return uni.showToast({
					title: "请选择经验要求",
					icon: "none"
				});
			}
			if (!this.selectedLevel) {
				return uni.showToast({
					title: "请选择最低学历",
					icon: "none"
				});
			}
			if (!this.selectedSalary) {
				return uni.showToast({
					title: "请选择薪资范围",
					icon: "none"
				});
			}
			if (!this.stationName.fullText && !this.address) {
				return uni.showToast({
					title: "请填写工作地址",
					icon: "none"
				});
			}
			if (this.type && this.type == 'updata' && !this.stationName.longitude) {
				return uni.showToast({
					title: "请选择位置",
					icon: "none"
				});
			}
			if (!this.positionTag) {
				return uni.showToast({
					title: "请选择职位标签",
					icon: "none"
				});
			}

			var positionTag = this.positionTag
			const str = positionTag.join(',');
			// 构造提交数据
			const data = {
				type: this.dataInfo.type,
				isDue: this.dataInfo.isDue,
				positionDetails: this.dataInfo.positionDetails,
				ruleClassifyId:this.dataInfo.ruleClassifyId,
				ruleClassifyName: this.dataInfo.ruleClassifyName,
				orderid: 1,
				postPushId: this.pid,
				experience: this.selectedExper, //工作经验
				education: this.selectedLevel, //学历
				salaryRange: this.selectedSalary, //薪资范围
				welfareTag: this.welfareTag, //福利相关标签
				welfareText: this.welfareText,
				positionTag: str, //职位技能
				address: this.stationName.fullText || this.address, //地址
				lat: this.stationName.latitude,
				lng: this.stationName.longitude,
				province: this.stationName.province,
				city: this.stationName.city,
				county: this.stationName.district,
				// companyId: (this.companyId === undefined || this.companyId === 'undefined') ? '' : this.companyId,
				salaryTimes: this.salaryTimes
			};
			// 调用接口提交
			uni.showLoading({
				title: "提交中..."
			});
			this.$Request.postJson("/app/postPush/savePostPush", data)
				.then((res) => {
					uni.hideLoading();
					if (res.code === 0) {
						uni.showToast({
							title: "提交成功",
							icon: "success"
						});
						//这里要选择跳转，第一次是要跳公司页，如果是二次就到职位管理页
						if (this.status == 1) { //审核中
							uni.navigateTo({
								url: "/package/jobIntention/companyImg?companyName=" + this.companyName +
									'&companyId=' + this.companyId
							});
						} else if (this.status == 2) {//审核通过
							// 判断是否是管理员
							if (this.companyInfo.companyUser.isAdmin != 1 && this.companyInfo.companyUser.status == 1) {
								// 非管理员，状态是待审核
								uni.navigateTo({
									url: '/package/jobIntention/completeMsg'
								});
							} else {
								uni.navigateTo({
									url: '/pages/jobManagement/jobManagement'
								})								
							}
						} else {
							// uni.navigateTo({
							// 	url: '/my/renzheng/editCompany'
							// })
							uni.navigateTo({
								url: '/pages/jobManagement/jobManagement'
							})

						}



					} else {
						uni.showToast({
							title: res.msg || "提交失败",
							icon: "none"
						});
					}
				})
				.catch((err) => {
					uni.hideLoading();
					console.error("提交失败：", err);
					uni.showToast({
						title: "网络异常",
						icon: "none"
					});
				});
		},
		
		// 跳转至公司认证页面
		handleToIndex() {
			if (!this.isAdmin) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				uni.navigateTo({
					url: `/package/jobIntention/companyImg?companyName=${this.companyName}&companyId=${this.companyId}`
				})
			}
		}
	},
};
</script>

<style lang="scss" scoped>
/* 原有样式保持不变 */
.switch-roles {
	background-color: #fff;
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;

	.roles-content {
		width: 100%;
		flex: 1;
		overflow: auto;

		.content {
			padding: 32rpx 40rpx;

			.title {
				color: #333;
				font-size: 48rpx;
				font-weight: 700;
				margin-bottom: 40rpx;
				line-height: 60rpx;
			}

			.desc {
				color: #666;
				font-size: 28rpx;
				margin-bottom: 20rpx;
			}
			
			// 步骤条
			.step-progress {
				display: flex;
				justify-content: center;
				padding: 20rpx 0 60rpx;
				.circle-wrapper {
					position: relative;
					.check-icon {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 40rpx;
						height: 40rpx;
						border: 1px solid rgba(198, 198, 198, 1);
						border-radius: 40rpx;
					}
					.check-active {
						background: #016bf6;
						border-color: #016bf6;
					}
					.step-progress-text {
						position: absolute;
						left: 50%;
						bottom: -36rpx;
						width: 150rpx;
						font-size: 20rpx;
						font-weight: 500;
						line-height: 32rpx;
						color: rgba(111, 111, 111, 1);
						transform: translateX(-50%);
						text-align: center;
					}
				}
				.line {
					width: 220rpx;
					height: 1px;
					background: rgba(198, 198, 198, 1);
				}
				.blue {
					background: rgba(1, 107, 246, 1);
				}
			}

			.check-title-big {
				color: #3a3943;
				font-size: 36rpx;
				font-weight: 500;
				padding: 20rpx 0;
			}

			.check-select {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 32rpx 47rpx;
				border-radius: 12rpx;
				box-shadow: 0 16rpx 300rpx rgba(0, 0, 0, 0.06);
				background: #fff;
				margin-bottom: 20rpx;

				.select-txt {
					color: #999;
					font-size: 28rpx;
				}
			}

			.txt-desc {
				color: #666;
				font-size: 26rpx;
				margin-top: 20rpx;
				line-height: 1.5;
			}
		}
	}

	.step {
		padding: 32rpx 0;
	}

	.button-section {
		padding: 28rpx 40rpx;
		box-shadow: 0px -4px 16px 0px rgba(0, 0, 0, 0.04);
	}
	.submit-btn {
		flex-shrink: 0;
		border-radius: 999px;
		box-shadow: 0px -4px 16px 0px rgba(0, 0, 0, 0.04);
		background: linear-gradient(90deg, rgba(13, 39, 247, 1), rgba(19, 193, 234, 1) 100%);
		color: rgba(255, 255, 255, 1);
		font-family: DM Sans;
		font-size: 32rpx;
		font-weight: 400;
		line-height: 48rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 16rpx 32rpx;
		box-sizing: border-box;
	}
	.link-btn {
		text-align: center;
		color: rgba(1, 107, 246, 1);
		font-size: 16px;
		font-weight: 400;
		line-height: 16px;
		margin-bottom: 32rpx;
	}
}
</style>