<template>
  <view class="container">
    <scroll-view scroll-y class="scroll-body">
      
      <!-- 历史搜索 -->
      <view class="section" v-if="historyList.length > 0">
        <view class="section-header">
          <text class="title">历史搜索</text>
          <image src="/static/icons/icon-delete.svg" class="delete-icon" mode="aspectFit" @click="clearHistory"></image>
        </view>
        <view class="tags-row">
          <view 
            class="tag" 
            :class="{ active: selectedHistory === item }"
            v-for="(item, index) in historyList" 
            :key="index"
            @click="selectedHistory = item"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 岗位类型 -->
      <view class="section">
        <view class="section-header">
          <text class="title">岗位类型</text>
        </view>
        <view class="tags-row">
          <view 
            class="tag" 
            :class="{ active: selectedJobType === item.dictValue }"
            v-for="(item, index) in jobTypes" 
            :key="index"
            @click="selectedJobType = item.dictValue"
          >
            {{ item.dictLabel }}
          </view>
        </view>
      </view>

      <!-- 期望薪资 -->
      <view class="section">
        <view class="section-header">
          <text class="title">期望薪资 (K)</text>
        </view>

        <view class="salary-display">
          <text>{{ minSalary }} - {{ maxSalary }}K</text>
        </view>

        <view class="range-slider-wrap">
          <movable-area class="slider-track-area">
            <view class="slider-bg"></view>
            <view class="slider-active" :style="{ left: (minX + thumbHalf) + 'px', width: (maxX - minX) + 'px' }"></view>
            <movable-view class="slider-thumb" direction="horizontal" :x="minX" @change="onMinMove" :animation="false"></movable-view>
            <movable-view class="slider-thumb" direction="horizontal" :x="maxX" @change="onMaxMove" :animation="false"></movable-view>
          </movable-area>
        </view>
      </view>

      <!-- 工作经验 -->
      <view class="section">
        <view class="section-header">
          <text class="title">工作经验</text>
        </view>
        <view class="tags-row">
          <view 
            class="tag"
            :class="{ active: selectedExperience === item.dictValue }"
            v-for="(item, index) in experiences" 
            :key="index"
            @click="selectedExperience = item.dictValue"
          >
            {{ item.dictLabel }}
          </view>
        </view>
      </view>

      <!-- 工作地点 -->
      <view class="section">
        <view class="section-header">
          <text class="title">工作地点</text>
        </view>
        <picker mode="region" @change="onRegionChange" :value="selectedRegion">
          <view class="location-picker">
            <text class="location-text" :class="{ 'placeholder': !selectedCity }">
              {{ selectedCity ? (selectedRegion[0] + ' ' + selectedRegion[1] + ' ' + selectedRegion[2]) : '请选择工作地点' }}
            </text>
            <image src="/static/icons/chevron-right.svg" class="arrow-icon" mode="aspectFit"></image>
          </view>
        </picker>
      </view>

      <!-- 学历要求 -->
      <view class="section">
        <view class="section-header">
          <text class="title">学历要求</text>
        </view>
        <view class="tags-row">
          <view 
            class="tag"
            :class="{ active: selectedEducation === item.dictValue }"
            v-for="(item, index) in educations" 
            :key="index"
            @click="selectedEducation = item.dictValue"
          >
            {{ item.dictLabel }}
          </view>
        </view>
      </view>

      <!-- 底部安全距离 -->
      <view style="height: 160rpx;"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="btn reset-btn" @click="resetFilters">重置</view>
      <view class="btn confirm-btn" @click="confirmFilters">确定</view>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref, onMounted } from 'vue';
import { getDicts } from '../../api/dict.js';

// 历史搜索数据
const historyList = ref([]);
const selectedHistory = ref('');

// 岗位类型
const jobTypes = ref([]);
const selectedJobType = ref('');

// 期望薪资滑块状态
const minSalary = ref(0);
const maxSalary = ref(50);
const minX = ref(0);
const maxX = ref(0);
const sliderWidth = ref(0);
const thumbHalf = ref(0);
const MAX_SALARY = 50; // 上限 50K

// 工作经验
const experiences = ref([]);
const selectedExperience = ref('');

// 学历要求
const educations = ref([]);
const selectedEducation = ref('');

// 地理位置
const selectedRegion = ref(['', '', '']);
const selectedCity = ref('');

const onRegionChange = (e) => {
  selectedRegion.value = e.detail.value;
  selectedCity.value = e.detail.value[1]; // 取城市名作为核心过滤条件
};

const loadDictionaries = () => {
  getDicts('main_position_type').then(res => {
    if (res.data) {
      jobTypes.value = res.data;
    }
  });
  getDicts('main_experience').then(res => {
    if (res.data) {
      experiences.value = res.data;
    }
  });
  getDicts('main_education').then(res => {
    if (res.data) {
      educations.value = res.data;
    }
  });
};

onMounted(() => {
  // 加载搜索历史
  const historyStr = uni.getStorageSync('search_history');
  if (historyStr) {
    try {
      historyList.value = JSON.parse(historyStr);
    } catch(e){}
  }

  loadDictionaries();
  
  // 延迟一小会儿，确保 DOM 已经挂载好
  setTimeout(() => {
    uni.createSelectorQuery().select('.slider-track-area').boundingClientRect(res => {
      if (res && res.width) {
        const thumbW = uni.upx2px(40);
        thumbHalf.value = thumbW / 2;
        sliderWidth.value = res.width - thumbW;
        updateThumbPositions();
      }
    }).exec();
  }, 300);
});

// 计算位置同步到界面
const updateThumbPositions = () => {
  if (sliderWidth.value > 0) {
    minX.value = (minSalary.value / MAX_SALARY) * sliderWidth.value;
    maxX.value = (maxSalary.value / MAX_SALARY) * sliderWidth.value;
  }
};

const onMinMove = (e) => {
  if (e.detail.source === 'touch') {
    let newX = e.detail.x;
    if (newX > maxX.value) newX = maxX.value; 
    minX.value = newX;
    minSalary.value = Math.round((newX / sliderWidth.value) * MAX_SALARY);
  }
};

const onMaxMove = (e) => {
  if (e.detail.source === 'touch') {
    let newX = e.detail.x;
    if (newX < minX.value) newX = minX.value; 
    maxX.value = newX;
    maxSalary.value = Math.round((newX / sliderWidth.value) * MAX_SALARY);
  }
};

// 清除历史记录
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确认清空历史搜索？',
    success: (res) => {
      if (res.confirm) {
        historyList.value = [];
        selectedHistory.value = '';
        uni.removeStorageSync('search_history');
      }
    }
  });
};

// 确定筛选项
const confirmFilters = () => {
  // 匹配选中的字典标签，若包含“不限”则重置为空字符串传给后端
  const expItem = experiences.value.find(i => i.dictValue === selectedExperience.value);
  const userExp = (expItem && expItem.dictLabel && expItem.dictLabel.includes('不限')) ? '' : selectedExperience.value;

  const eduItem = educations.value.find(i => i.dictValue === selectedEducation.value);
  const userEdu = (eduItem && eduItem.dictLabel && eduItem.dictLabel.includes('不限')) ? '' : selectedEducation.value;

  // 发送给岗位列表页面进行筛选
  const filterParams = {
    keyword: selectedHistory.value,
    jobType: selectedJobType.value,
    minSalary: minSalary.value,
    maxSalary: maxSalary.value,
    experience: userExp,
    education: userEdu,
    workCity: selectedCity.value,
    workProvince: selectedRegion.value[0]
  };
  
  uni.$emit('updateFilters', filterParams);
  
  uni.showToast({
    title: '筛选已应用',
    icon: 'success'
  });
  setTimeout(() => {
    uni.navigateBack();
  }, 800);
};

// 重置过滤器
const resetFilters = () => {
  selectedHistory.value = '';
  selectedJobType.value = '';
  minSalary.value = 0;
  maxSalary.value = 50; 
  updateThumbPositions();
  selectedExperience.value = '';
  selectedEducation.value = '不限';
  selectedRegion.value = ['', '', ''];
  selectedCity.value = '';
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  background-color: #FFFFFF;
  display: flex;
  flex-direction: column;
}

.scroll-body {
  flex: 1;
  overflow-y: auto;
  padding: 24rpx 40rpx;
  box-sizing: border-box;
}

.section {
  margin-bottom: 40rpx;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #1A1A1A;
    }

    .delete-icon {
      width: 32rpx;
      height: 32rpx;
      opacity: 0.4;
      padding: 10rpx;
    }
  }

  .tags-row {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;

    .tag {
      background-color: #FFFFFF;
      color: #555555;
      font-size: 24rpx;
      padding: 12rpx 30rpx;
      border-radius: 100rpx;
      border: 2rpx solid #E4E7ED;
      min-width: 130rpx;
      text-align: center;
      box-sizing: border-box;

      &.active {
        background-color: #1F6CFF;
        color: #FFFFFF;
        border-color: #1F6CFF;
      }
    }
  }
}

.location-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #F8F9FB;
  padding: 24rpx 30rpx;
  border-radius: 12rpx;
  border: 2rpx solid #E4E7ED;

  .location-text {
    font-size: 26rpx;
    color: #1A1A1A;

    &.placeholder {
      color: #BBBBBB;
    }
  }

  .arrow-icon {
    width: 24rpx;
    height: 24rpx;
    opacity: 0.3;
  }
}

.salary-display {
  text-align: center;
  font-size: 28rpx;
  color: #1F6CFF;
  margin-bottom: 24rpx;
  font-weight: bold;
}
.range-slider-wrap {
  width: 100%;
  height: 60rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
}
.slider-track-area {
  width: 100%;
  height: 100%;
  position: relative;
}
.slider-bg {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 8rpx;
  background-color: #F0F2F5;
  transform: translateY(-50%);
  border-radius: 4rpx;
}
.slider-active {
  position: absolute;
  top: 50%;
  height: 8rpx;
  background-color: #1F6CFF;
  transform: translateY(-50%);
  border-radius: 4rpx;
}
.slider-thumb {
  width: 40rpx;
  height: 40rpx;
  background-color: #FFFFFF;
  border-radius: 50%;
  border: 4rpx solid #1F6CFF;
  box-shadow: 0 2rpx 6rpx rgba(31, 108, 255, 0.2);
  top: 50%;
  margin-top: -20rpx;
  box-sizing: border-box;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 110rpx;
  background-color: #FFFFFF;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  padding: 0 40rpx;
  padding-bottom: env(safe-area-inset-bottom);
  gap: 30rpx;
  z-index: 100;

  .btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    height: 72rpx;
    border-radius: 100rpx;
    font-weight: 500;
  }

  .reset-btn {
    background-color: #FFFFFF;
    color: #666666;
    border: 2rpx solid #E4E7ED;
    box-sizing: border-box;
  }

  .confirm-btn {
    background-color: #1F6CFF;
    color: #FFFFFF;
  }
}
</style>
