<template>
	<view class="add-expectation">
		<!-- 顶部导航 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<u-icon name="arrow-leftward" color="rgba(51, 51, 51, 1)" style="font-size: 38rpx;"></u-icon>
			</view>
			<view class="nav-title">{{id==""||id==0?'添加':'编辑'}}求职期望</view>
			<view class="nav-right"></view>
		</view>

		<!-- 表单内容 -->
		<view class="form-container">
			<!-- 工作职位 -->
			<view class="form-item">
				<text class="form-label">工作职位</text>
				<view class="form-input" @click="selectJob">
					<text class="input-text">{{ jobTitle || '请选择' }}</text>
					<u-icon name="arrow-right" color="#999" size="24"></u-icon>
				</view>
			</view>

			<!-- 工作城市 -->
			<view class="form-item">
				<text class="form-label">工作城市</text>
				<view class="form-input" @click="selectCity">
					<text class="input-text">{{ city || '请选择' }}</text>
					<u-icon name="arrow-right" color="#999" size="24"></u-icon>
				</view>
			</view>

			<!-- 期望薪酬 -->
			<view class="form-item">
				<text class="form-label">期望薪酬</text>
				<view class="salary-container">
					<view class="salary-inputs">
						<view class="salary-input">
							<text class="currency">¥</text>
							<input v-model="minSalary" type="number" placeholder="8000" class="salary-field" />
						</view>
						<view class="salary-input">
							<text class="currency">¥</text>
							<input v-model="maxSalary" type="number" placeholder="10000" class="salary-field" />
						</view>
					</view>
					<!-- 范围滑块 -->
					<view class="range-slider-container">
						<view class="range-slider-track" @click="onTrackClick">
							<view class="range-slider-progress" :style="progressStyle"></view>
							<view 
								class="range-slider-thumb range-slider-thumb-left"
								:style="leftThumbStyle"
								@touchstart="onLeftThumbStart"
								@touchmove="onLeftThumbMove"
								@touchend="onLeftThumbEnd"
							></view>
							<view 
								class="range-slider-thumb range-slider-thumb-right"
								:style="rightThumbStyle"
								@touchstart="onRightThumbStart"
								@touchmove="onRightThumbMove"
								@touchend="onRightThumbEnd"
							></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 工作类型 -->
			<view class="form-item">
				<text class="form-label">工作类型</text>
				<view class="job-type-container">
					<view 
						class="job-type-btn" 
						:class="{ active: jobType === 'fulltime' }"
						@click="selectJobType('fulltime')"
					>
						<text>全职</text>
					</view>
					<view 
						class="job-type-btn" 
						:class="{ active: jobType === 'parttime' }"
						@click="selectJobType('parttime')"
					>
						<text>兼职</text>
					</view>
				</view>
			</view>

			<!-- 从事方向 -->
			<view class="form-item">
				<text class="form-label">从事方向</text>
				<view class="form-input" @click="selectIndustry">
					<text class="input-text">{{ industry || '请选择' }}</text>
					<u-icon name="arrow-right" color="#999" size="24"></u-icon>
				</view>
			</view>
		</view>
		<view class="footer">
		  <u-button
		    type="primary"
		    @click="saveWorkExperience"
		    :customStyle="{
		      height: '90rpx',
		      fontSize: '32rpx',
		      borderRadius: '45rpx',
		      margin: '40rpx 0',
		    }"
		    >提交</u-button
		  >
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			id:0,
			jobId:0,
			jobTitle: '',
			city: '',
			minSalary: '8000',
			maxSalary: '10000',
			jobType: 'fulltime',
			industry: '',
			// 范围滑块相关数据
			minValue: 8000,
			maxValue: 10000,
			sliderMin: 5000,
			sliderMax: 50000,
			step: 1000,
			trackWidth: 0,
			draggingThumb: null, // 'left' 或 'right' 或 null
			startX: 0,
			startValue: 0
		}
	},
	computed: {
		// 左侧滑块位置百分比
		leftPercent() {
			return ((this.minValue - this.sliderMin) / (this.sliderMax - this.sliderMin)) * 100
		},
		// 右侧滑块位置百分比
		rightPercent() {
			return ((this.maxValue - this.sliderMin) / (this.sliderMax - this.sliderMin)) * 100
		},
		// 进度条样式
		progressStyle() {
			return {
				left: this.leftPercent + '%',
				width: (this.rightPercent - this.leftPercent) + '%'
			}
		},
		// 左侧滑块样式
		leftThumbStyle() {
			return {
				left: this.leftPercent + '%'
			}
		},
		// 右侧滑块样式
		rightThumbStyle() {
			return {
				left: this.rightPercent + '%'
			}
		}
	},
	methods: {
		getData(){
			var that=this
			this.$Request.getT("/app/intention/getIntentionInfo", {intentionId:this.id}).then((res) => {
			  if (res.code == 0) {
				  res=res.data
			     that.jobId=res.ruleClassifyId
				 that.jobTitle=res.ruleClassifyName
				 that.jobType=res.postType=='全职'?'fulltime':'parttime'
				 that.city=res.citys
				 that.industry=res.industry
				 var salaryRange=res.salaryRange.split('-')
				 that.minValue=salaryRange[0]?parseInt(salaryRange[0]):0
				 that.maxValue=salaryRange[1]?parseInt(salaryRange[1]):0
				 that.minSalary=salaryRange[0]?salaryRange[0]:0
				 that.maxSalary=salaryRange[1]?salaryRange[1]:0
			  } else {
			    uni.showToast({
			      title: res.msg,
			      icon: "none",
			    });
			  }
			});
		},
		goBack() {
			uni.navigateBack()
		},
		selectJob() {
			uni.navigateTo({
				url: '/package/jobIntention/jobList'
			})
		},
		selectCity() {
			uni.navigateTo({
				url: '/package/jobIntention/city'
			})
		},
		selectIndustry() {
			if(this.jobId==''||this.jobId==0)
				return this.$queue.showToast('请先选择岗位')
			uni.navigateTo({
				url: '/package/jobIntention/preferenceSetting?jobId='+this.jobId+'&jobTitle='+this.jobTitle+'&selectedPreferences='+encodeURIComponent(JSON.stringify(this.industry==''||this.industry==null?[]:this.industry.split('/')))
			})
		},
		selectJobType(type) {
			this.jobType = type
		},
		// 获取滑块轨道宽度
		getTrackWidth() {
			uni.createSelectorQuery().in(this).select('.range-slider-track').boundingClientRect(data => {
				this.trackWidth = data.width
			}).exec()
		},
		// 将像素位置转换为数值
		pixelToValue(pixel) {
			const percent = (pixel / this.trackWidth) * 100
			const value = this.sliderMin + (percent / 100) * (this.sliderMax - this.sliderMin)
			return Math.round(value / this.step) * this.step
		},
		// 左侧滑块开始拖拽
		onLeftThumbStart(e) {
			this.draggingThumb = 'left'
			this.startX = e.touches[0].clientX
			this.startValue = this.minValue
			e.preventDefault()
		},
		// 左侧滑块拖拽中
		onLeftThumbMove(e) {
			if (this.draggingThumb !== 'left') return
			
			const deltaX = e.touches[0].clientX - this.startX
			const deltaPercent = (deltaX / this.trackWidth) * 100
			const deltaValue = (deltaPercent / 100) * (this.sliderMax - this.sliderMin)
			let newValue = this.startValue + deltaValue
			
			// 限制范围
			newValue = Math.max(this.sliderMin, Math.min(newValue, this.maxValue - this.step))
			newValue = Math.round(newValue / this.step) * this.step
			
			this.minValue = newValue
			this.minSalary = newValue.toString()
			e.preventDefault()
		},
		// 左侧滑块结束拖拽
		onLeftThumbEnd(e) {
			this.draggingThumb = null
			e.preventDefault()
		},
		// 右侧滑块开始拖拽
		onRightThumbStart(e) {
			this.draggingThumb = 'right'
			this.startX = e.touches[0].clientX
			this.startValue = this.maxValue
			e.preventDefault()
		},
		// 右侧滑块拖拽中
		onRightThumbMove(e) {
			if (this.draggingThumb !== 'right') return
			
			const deltaX = e.touches[0].clientX - this.startX
			const deltaPercent = (deltaX / this.trackWidth) * 100
			const deltaValue = (deltaPercent / 100) * (this.sliderMax - this.sliderMin)
			let newValue = this.startValue + deltaValue
			
			// 限制范围
			newValue = Math.max(this.minValue + this.step, Math.min(newValue, this.sliderMax))
			newValue = Math.round(newValue / this.step) * this.step
			
			this.maxValue = newValue
			this.maxSalary = newValue.toString()
			e.preventDefault()
		},
		// 右侧滑块结束拖拽
		onRightThumbEnd(e) {
			this.draggingThumb = null
			e.preventDefault()
		},
		// 点击轨道
		onTrackClick(e) {
			if (this.draggingThumb) return
			
			const rect = e.currentTarget.getBoundingClientRect()
			const clickX = e.detail.x - rect.left
			const clickPercent = (clickX / rect.width) * 100
			const clickValue = this.sliderMin + (clickPercent / 100) * (this.sliderMax - this.sliderMin)
			
			// 判断点击位置更靠近哪个滑块
			const distanceToLeft = Math.abs(clickValue - this.minValue)
			const distanceToRight = Math.abs(clickValue - this.maxValue)
			
			if (distanceToLeft < distanceToRight) {
				// 更靠近左侧滑块
				let newValue = Math.round(clickValue / this.step) * this.step
				newValue = Math.max(this.sliderMin, Math.min(newValue, this.maxValue - this.step))
				this.minValue = newValue
				this.minSalary = newValue.toString()
			} else {
				// 更靠近右侧滑块
				let newValue = Math.round(clickValue / this.step) * this.step
				newValue = Math.max(this.minValue + this.step, Math.min(newValue, this.sliderMax))
				this.maxValue = newValue
				this.maxSalary = newValue.toString()
			}
		},
		saveWorkExperience() {
		  if (!this.jobId) {
		    uni.showToast({ title: "请选择工作职位", icon: "none" });
		    return;
		  }
		  if (!this.city) {
		    uni.showToast({ title: "请选择城市", icon: "none" });
		    return;
		  }
		  if (!this.industry) {
		    uni.showToast({ title: "请选择从事方向", icon: "none" });
		    return;
		  }
			let data={
				intentionId:this.id,
				ruleClassifyId:this.jobId,
				ruleClassifyName:this.jobTitle,
				citys:this.city,
				salaryRange:this.minSalary+'-'+this.maxSalary,
				postType:this.jobType === 'fulltime'?'全职':'兼职',
				industry:this.industry,
				"createTime": "",
				  "industryId": 201,
				  "industryOneId": 200,
				  "classifyOneId": 0,
				  "classifyTwoId": 0,
				  "isDefault": 1
			}
		  uni.showLoading({ title: "提交中..." });
		  this.$Request.postJson("/app/intention/saveUpdate", data).then((res) => {
			  uni.hideLoading();
		    if (res.code == 0) {
		        uni.showToast({ title: "保存成功", icon: "none" });
		        // 实际开发中可以在这里添加跳转逻辑
				uni.$emit('updateResume')
		      setTimeout(() => {
		        uni.navigateBack()
		      }, 1000);
		    } else {
		      uni.showToast({
		        title: res.msg,
		        icon: "none",
		      });
		    }
		  });
		},
	},
	mounted() {
		// 初始化滑块轨道宽度
		this.$nextTick(() => {
			this.getTrackWidth()
		})
	},
	onLoad(options) {
		this.id=options&&options.id?options.id:""
		// 监听选择结果
		uni.$on('jobs', (data) => {
			this.jobTitle = data.ruleClassifyName
			this.jobId = data.ruleClassifyId
		})
		uni.$on('city', (data) => {
			console.log(data)
			this.city = data.city
		})
		/* uni.$on('industry', (data) => {
			this.industry = data.industry
		}) */
		// 监听技能设置更新
		uni.$on('preferenceUpdated', (data) => {
			this.industry=data.preferences.join('/')
		})
		if(this.id!=0&&this.id!='')
		this.getData()
	},
	onUnload() {
		// 移除监听
		uni.$off('jobs')
		uni.$off('city')
		/* uni.$off('industry') */
		uni.$off('preferenceUpdated')
	}
}
</script>

<style lang="scss" scoped>
.add-expectation {
	min-height: 100vh;
	padding: 88rpx 40rpx 40rpx 40rpx;
}

.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;

	.nav-left {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-title {
		color: rgba(51, 51, 51, 1);
		font-family: DM Sans;
		font-size: 32rpx;
		font-weight: 700;
		line-height: 26px;
		text-align: center;
	}
}

.form-container {
	background: #ffffff;
	border-radius: 20rpx;
	margin-top: 30rpx;
}

.form-item {
	margin-bottom: 40rpx;

	&:last-child {
		margin-bottom: 0;
	}

	.form-label {
        color: rgba(58, 57, 67, 1);
        font-family: DM Sans;
        font-size: 36rpx;
        font-weight: 500;
        line-height: 24px;
        letter-spacing: 0px;
        text-align: left;
	}

	.form-input {
        height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 20rpx;
		border-radius: 12rpx;
        box-shadow: 0px 8px 150px 0px rgba(0, 0, 0, 0.06);
        background: rgba(255, 255, 255, 1);
        margin-top: 20rpx;

		.input-text {
			color: rgba(97, 110, 124, 1);
            font-family: DM Sans;
            font-weight: 400;
            line-height: 20px;
            letter-spacing: 0px;
            text-align: left;
			font-size: 28rpx;
		}
	}
}

.salary-container {
	.salary-inputs {
		display: flex;
		align-items: center;
		margin: 20rpx 0 30rpx 0;
        gap: 50rpx;

		.salary-input {
			display: flex;
			align-items: center;
			flex: 1;
			padding: 20rpx;
			border-radius: 12rpx;
            box-shadow: 0px 8px 150px 0px rgba(0, 0, 0, 0.06);
            background: rgba(255, 255, 255, 1);

			.currency, .salary-field {
                color: rgba(97, 110, 124, 1);
                font-family: DM Sans;
                font-weight: 400;
                line-height: 20px;
                letter-spacing: 0px;
                text-align: left;
                font-size: 28rpx;
			}
		}

		.salary-separator {
			margin: 0 20rpx;
			color: rgba(153, 153, 153, 1);
			font-size: 28rpx;
		}
	}

	.range-slider-container {
		padding: 20rpx 10rpx;
	}

	.range-slider-track {
		position: relative;
		height: 6rpx;
		background-color: #E5E5EA;
		border-radius: 3rpx;
		cursor: pointer;
	}

	.range-slider-progress {
		position: absolute;
		top: 0;
		height: 100%;
		background-color: #007AFF;
		border-radius: 3rpx;
		transition: all 0.1s ease;
	}

	.range-slider-thumb {
		position: absolute;
		top: 50%;
		width: 40rpx;
		height: 40rpx;
		background-color: #007AFF;
		border-radius: 50%;
		border: 4rpx solid #ffffff;
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
		transform: translate(-50%, -50%);
		cursor: pointer;
		transition: all 0.1s ease;
	}

	.range-slider-thumb:active {
		transform: translate(-50%, -50%) scale(1.1);
		box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.4);
	}
}

.job-type-container {
	display: flex;
	gap: 50rpx;
    margin-top: 20rpx;

	.job-type-btn {
		flex: 1;
		padding: 24rpx 20rpx;
		border: 1rpx solid #E5E5EA;
		border-radius: 42rpx;
		text-align: center;

		text {
			color: rgba(97, 110, 124, 1);
			font-size: 28rpx;
		}

		&.active {
			background: #016BF6;

			text {
				color: #FFFFFF;
				font-weight: 400;
			}
		}
	}
}
</style>
