<template>
  <view class="container">
    <!-- 固定顶部区域 -->
    <view class="fixed-header">

      <!-- ① 蓝色渐变搜索区域 -->
      <view class="gradient-section" :style="{ paddingTop: (statusBarHeight + titleBarMargin) + 'px' }">
        <view class="search-wrap" :style="{ height: menuButtonHeight + 'px' }">
          <view class="search-bar">
            <image src="/static/icons/search.svg" class="search-icon" mode="aspectFit"></image>
            <input 
              type="text" 
              placeholder="请输入关键字" 
              class="search-input" 
              placeholder-class="ph-color"
              v-model="keyword"
              @confirm="handleSearchConfirm"
              @input="handleSearch"
            />
          </view>
        </view>
      </view>

      <!-- ② 白色区域：职位类别 Tab + 筛选 -->
      <view class="white-section">
        <view class="horizontal-tabs-wrap">
          <view class="main-tabs">
            <view 
              class="main-tab" 
              :class="{ active: currentJobType === index }"
              v-for="(tab, index) in jobTypeTabs" 
              :key="index"
              @click="currentJobType = index"
            >
              {{ tab }}
            </view>
          </view>
          <view class="filter-btn" @click="goToFilter">
            <text class="filter-text">筛选 {{ activeFilterCount > 0 ? '· ' + activeFilterCount : '' }}</text>
          </view>
        </view>

        <!-- 排序选项：综合 / 最新 -->
        <view class="sub-tabs">
          <view 
            class="sub-tab" 
            :class="{ active: sortType === 'comprehensive' }"
            @click="sortType = 'comprehensive'"
          >综合</view>
          <view 
            class="sub-tab" 
            :class="{ active: sortType === 'latest' }"
            @click="sortType = 'latest'"
          >最新</view>
        </view>

        <!-- 渐变阴影遮罩 -->
        <view class="fade-mask"></view>
      </view>

    </view>

    <!-- 可滚动的列表内容 (关闭滚动条显示) -->
    <view class="loading-box" v-if="isLoading && jobList.length === 0">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    <scroll-view 
      v-else
      class="scroll-body" 
      scroll-y 
      :style="{ top: scrollTop + 'px' }"
      :show-scrollbar="false"
      :enhanced="true"
      @scrolltolower="loadMore"
    >
      <view class="job-list">
        <view 
          class="job-card" 
          v-for="(item, index) in jobList" 
          :key="item.id || index"
          :class="{ 'first-card': index === 0 }"
          @click="goToDetail(item)"
        >
          <view class="job-header">
            <view class="job-title-box">
              <text class="job-title">{{ item.title }}</text>
              <text class="urge-tag" v-if="item.isUrgent">急招</text>
            </view>
            <text class="job-salary">{{ item.salaryText }}</text>
          </view>

          <view class="tags-row">
            <text class="tag" v-for="(tag, tagIdx) in item.tags" :key="tagIdx">{{ tag }}</text>
          </view>

          <view class="info-row">
            <image src="/static/icons/user.svg" class="info-icon" mode="aspectFit"></image>
            <text class="info-text">招录 {{ item.count }} 人</text>
          </view>
          <view class="info-row">
            <image src="/static/icons/time.svg" class="info-icon" mode="aspectFit"></image>
            <text class="info-text">截止时间：{{ item.deadline }}</text>
            <text class="danger-text" v-if="item.isExpiring">即将截止</text>
          </view>

          <view class="company-row">
            <view class="company-info-wrap">
              <image :src="item.logo" class="company-logo" mode="aspectFill"></image>
              <view class="company-text-col">
                <view class="company-name-box">
                  <text class="company-name">{{ item.company }}</text>
                  <image src="/static/icons/verified.svg" class="verified-icon" mode="aspectFit"></image>
                </view>
                <text class="company-location">{{ item.location }}</text>
              </view>
            </view>
            <image src="/static/icons/close.svg" class="close-icon" mode="aspectFit" @click.stop="openFeedbackPopup(item)"></image>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-wrap" v-if="jobList.length === 0">
           <text class="empty-text">暂时没有符合条件的岗位</text>
        </view>
      </view>

      <!-- 底部提醒 -->
      <view class="load-end-wrap" v-if="jobList.length > 0 && !hasMore">
        <view class="load-end-line"></view>
        <text class="load-end-text">已加载全部</text>
        <view class="load-end-line"></view>
      </view>
      <view class="tabbar-placeholder"></view>
    </scroll-view>

    <!-- Custom Tabbar -->
    <custom-tabbar :activeIndex="0"></custom-tabbar>

    <!-- 反馈弹窗 (移动到这里以实现真正的全屏遮罩) -->
    <view class="popup-mask" v-if="showPopup" @click="closePopup" @touchmove.stop.prevent>
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">为什么不感兴趣？</text>
          <image src="/static/icons/close.svg" class="popup-close" mode="aspectFit" @click="closePopup"></image>
        </view>
        <view class="popup-body">
          <view class="feedback-btn" @click="handleDislikePosition()">
            <text>不喜欢这个岗位</text>
          </view>
          <view class="feedback-btn" @click="handleDislikeCompany()">
            <text>不喜欢这个公司</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import CustomTabbar from '../../components/custom-tabbar/custom-tabbar.vue';
import { getPositionList, dislikePosition, dislikeCompany } from '../../api/position.js';

// 获取当前登录学员ID（从本地存储读取）
const getStudentId = () => {
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo) return null;
  // 兼容不同的字段名（id 或 studentId）
  const id = userInfo.id || userInfo.studentId || null;
  console.log('[getStudentId] userInfo:', JSON.stringify(userInfo), '=> id:', id);
  return id;
};

const statusBarHeight = ref(20);
const titleBarMargin = ref(8);
const menuButtonHeight = ref(32);

// 搜索、排序与筛选状态
const keyword = ref('');
const sortType = ref('comprehensive');
const currentJobType = ref(0); 
const jobTypeTabs = ref(['全部']); // 将通过字典获取
const jobTypeValue = ref(['']); // 对应的字典值/label

// 引入获取字典方法
import { getDicts } from '../../api/dict.js';

// 获取字典数据
const loadDicts = () => {
  getDicts('main_position_type').then(res => {
    if (res.data && res.data.length > 0) {
      jobTypeTabs.value = ['全部岗位', ...res.data.map(item => item.dictLabel)];
      jobTypeValue.value = ['', ...res.data.map(item => item.dictValue)];
    } else {
      jobTypeTabs.value = ['全部岗位', '全职', '实习', '兼职'];
      jobTypeValue.value = ['', '0', '1', '2'];
    }
  });
};

// 分页与列表数据状态
const jobList = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const isLoading = ref(false);

// 弹窗状态
const showPopup = ref(false);
const activeJob = ref(null);

const openFeedbackPopup = (job) => {
  activeJob.value = job;
  showPopup.value = true;
};

const closePopup = () => {
  showPopup.value = false;
};

// 屏蔽岗位
const handleDislikePosition = () => {
  if (!activeJob.value) return;
  const studentId = getStudentId();
  const job = activeJob.value;
  closePopup();
  // 本地立即从列表移除
  jobList.value = jobList.value.filter(item => item.id !== job.id);
  // 调用后端持久化（若未登录则仅本地过滤）
  if (studentId) {
    dislikePosition(studentId, job.id).catch(() => {});
  }
  uni.showToast({ title: '已屏蔽该岗位', icon: 'none' });
};

// 屏蔽公司
const handleDislikeCompany = () => {
  if (!activeJob.value) return;
  const studentId = getStudentId();
  const job = activeJob.value;
  closePopup();
  // 本地立即移除该公司所有岗位
  jobList.value = jobList.value.filter(item => item.rawTenantId !== job.rawTenantId);
  // 调用后端持久化
  if (studentId && job.rawTenantId) {
    dislikeCompany(studentId, job.rawTenantId).catch(() => {});
  }
  uni.showToast({ title: '已屏蔽该公司', icon: 'none' });
};

// 基础筛选条件记录
const filterCriteria = ref({
  jobType: '',
  minSalary: 0,
  maxSalary: 50,
  experience: '',
  education: '',
  workCity: '',
  workProvince: '',
  workDistrict: ''
});

const activeFilterCount = computed(() => {
  let count = 0;
  // 这里不再统计 jobType，因为融合到了顶部Tab
  // if (filterCriteria.value.jobType) count++;
  if (filterCriteria.value.experience) count++;
  if (filterCriteria.value.education) count++;
  if (filterCriteria.value.minSalary > 0 || filterCriteria.value.maxSalary < 50) count++;
  if (filterCriteria.value.workCity) count++;
  if (filterCriteria.value.workDistrict) count++;
  return count;
});

// 从后端获取岗位列表数据
const fetchJobs = (reset = false) => {
  if (isLoading.value) return;
  if (reset) {
    pageNum.value = 1;
    hasMore.value = true;
    jobList.value = [];
  }
  if (!hasMore.value) return;

  isLoading.value = true;

  // 综合 Tab 里的类型或 Filter 里的类型
  // 如果顶部选了具体的类型（不是全部），就以顶部为准，如果顶部是全部，以 filter 里选的为准
  let postTypeStr = jobTypeValue.value[currentJobType.value] || '';
  if (!postTypeStr && filterCriteria.value.jobType) {
    postTypeStr = filterCriteria.value.jobType;
  }

  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    postName: keyword.value.trim(), 
    postType: postTypeStr, 
    schoolRequirement: filterCriteria.value.education || '',
    gradeRequirement: filterCriteria.value.experience || '',
    minSalary: filterCriteria.value.minSalary,
    maxSalary: filterCriteria.value.maxSalary,
    workCity: filterCriteria.value.workCity || '',
    workProvince: filterCriteria.value.workProvince || '',
    workDistrict: filterCriteria.value.workDistrict || ''
  };

  // 只有登录状态下才附带 studentId，避免传 "undefined" 字符串给后端
  const currentStudentId = getStudentId();
  if (currentStudentId) {
    params.studentId = currentStudentId;
  }

  if (sortType.value === 'latest') {
    params.orderByColumn = 'createTime';
    params.isAsc = 'desc';
  }

  getPositionList(params).then(res => {
    if (res.code === 200) {
      const rows = res.rows || [];
      let formattedRows = rows.map(item => ({
         id: item.id,
         title: item.postName,
         salaryText: item.salaryRange || '面议',
         // 使用后端翻译好的 Label 字段（如"全职"、"本科"、"3-5年"），而不是原始字典 value
         tags: [item.workCity + (item.workDistrict ? ' ' + item.workDistrict : ''), item.educationRequirementLabel || item.educationRequirement, item.gradeRequirementLabel || item.gradeRequirement].filter(Boolean),
         isUrgent: item.isUrgent === 1,
         count: item.recruitNum || 1,
         deadline: item.registrationEndDate ? item.registrationEndDate.split(' ')[0] : '长期有效',
         isExpiring: false,
         company: item.companyName || '平台推荐',
         rawTenantId: item.tenantId, // 保留原始 tenantId 用于屏蔽公司
         location: (item.workProvince || '') + (item.workCity ? '·' + item.workCity : '') + (item.workDistrict ? ' ' + item.workDistrict : ''),
         logo: item.companyAvatar || '/static/images/default-company.svg'
      }));

      
      jobList.value = reset ? formattedRows : [...jobList.value, ...formattedRows];
      if (jobList.value.length >= res.total || rows.length < pageSize.value) {
        hasMore.value = (formattedRows.length >= pageSize.value);
      } else {
        pageNum.value++;
      }
    }
  }).finally(() => {
    isLoading.value = false;
  });
};

const loadMore = () => {
  fetchJobs(false);
};

const handleSearch = () => {
  fetchJobs(true);
};

const handleSearchConfirm = () => {
  if (keyword.value.trim()) {
    let history = uni.getStorageSync('search_history');
    if (!history) history = [];
    else history = JSON.parse(history);
    
    // 如果已经存在，先移除旧的，再放到最前面
    history = history.filter(item => item !== keyword.value.trim());
    history.unshift(keyword.value.trim());
    
    // 最多保存 10 条
    if (history.length > 10) history = history.slice(0, 10);
    
    uni.setStorageSync('search_history', JSON.stringify(history));
  }
  fetchJobs(true);
};

watch([currentJobType, sortType], () => {
  fetchJobs(true);
});

const goToFilter = () => {
  uni.navigateTo({
    url: '/pages/jobs/filter'
  });
};

const goToDetail = (item) => {
  uni.navigateTo({
    url: '/pages/jobdetail/index?id=' + item.id
  });
};

const scrollTop = computed(() => {
  const gradientArea = titleBarMargin.value + menuButtonHeight.value + 8;
  const whiteArea = 82; 
  return statusBarHeight.value + gradientArea + whiteArea;
});

onPullDownRefresh(async () => {
  await fetchJobs(true);
  uni.stopPullDownRefresh();
});

onShow(() => {
  fetchJobs(true);
});

onMounted(() => {
  // 监听筛选页面发回的数据并重新请求
  uni.$on('updateFilters', (params) => {
    filterCriteria.value = params;
    if (params.keyword !== undefined) {
      keyword.value = params.keyword;
    }
    fetchJobs(true);
  });

  // 初始加载字典及请求数据
  loadDicts();

  // #ifdef MP-WEIXIN
  try {
    const sysInfo = uni.getSystemInfoSync();
    const menuInfo = uni.getMenuButtonBoundingClientRect();
    if (sysInfo && menuInfo) {
      statusBarHeight.value = sysInfo.statusBarHeight || 20;
      titleBarMargin.value = menuInfo.top - sysInfo.statusBarHeight;
      menuButtonHeight.value = menuInfo.height;
    }
  } catch (e) {}
  // #endif
});

onUnmounted(() => {
  uni.$off('updateFilters');
});

onPullDownRefresh(async () => {
  fetchJobs(true);
  // 等待一小段时间让请求发出
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 800);
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  background-color: #F8F9FB;
  position: relative;
  overflow: hidden;
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
  padding-top: 200rpx;
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #1F6CFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: transparent;
}

.gradient-section {
  background: linear-gradient(180deg, #1F6CFF 0%, #FFFFFF 100%);
  padding: 0 30rpx 16rpx;
}

.search-wrap {
  display: flex;
  align-items: center;
}

.search-bar {
  flex: 1;
  height: 100%;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.10);
  margin-right: 220rpx;

  .search-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
    opacity: 0.5;
  }

  .search-input {
    flex: 1;
    font-size: 28rpx;
  }

  .ph-color {
    color: #999999;
  }
}

.white-section {
  background-color: #FFFFFF;
  position: relative;
}

.horizontal-tabs-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx 10rpx;

  .main-tabs {
    display: flex;
    gap: 30rpx;

    .main-tab {
      /* 调整字体更小一点 */
      font-size: 30rpx;
      font-weight: bold;
      color: #777777;
      position: relative;
      padding-bottom: 4rpx;

      &.active {
        color: #1A1A1A;
        font-size: 30rpx; /* 选中和未选中字体一致 */
        &:after {
          content: "";
          position: absolute;
          left: 50%;
          bottom: -4rpx;
          transform: translateX(-50%);
          width: 32rpx;
          height: 5rpx;
          background: #1F6CFF;
          border-radius: 3rpx;
        }
      }
    }
  }

  .filter-btn {
    background-color: #EBF2FF;
    border-radius: 24rpx;
    padding: 8rpx 20rpx;
    display: flex;
    align-items: center;

    .filter-text {
      color: #1F6CFF;
      font-size: 24rpx;
      font-weight: 500;
    }
  }
}

.sub-tabs {
  display: flex;
  padding: 10rpx 30rpx 20rpx;
  gap: 40rpx;

  .sub-tab {
    font-size: 28rpx;
    color: #888888;
    padding-bottom: 6rpx;

    &.active {
      color: #1F6CFF;
      font-weight: bold;
      border-bottom: 4rpx solid #1F6CFF;
    }
  }
}

.fade-mask {
  position: absolute;
  left: 0;
  right: 0;
  bottom: -40rpx;
  height: 40rpx;
  background: linear-gradient(180deg, #F8F9FB 0%, rgba(248, 249, 251, 0) 100%);
  pointer-events: none;
  z-index: 10;
}

.scroll-body {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
  background-color: #F8F9FB;
  box-sizing: border-box;
  
  /* 针对不同平台的隐藏滚动条样式 */
  &::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
  }
}

.job-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  padding: 0 30rpx;
  min-height: 200rpx;
}

.first-card {
  margin-top: 24rpx !important;
}

.job-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 30rpx;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03);

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

    .job-title-box {
      display: flex;
      align-items: center;

      .job-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #1A1A1A;
        margin-right: 16rpx;
      }

      .urge-tag {
        font-size: 20rpx;
        color: #FF3B30;
        border: 1rpx solid #FF3B30;
        padding: 2rpx 10rpx;
        border-radius: 12rpx;
      }
    }

    .job-salary {
      font-size: 32rpx;
      font-weight: bold;
      color: #1F6CFF;
    }
  }

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

    .tag {
      background: #F4F5F7;
      color: #666666;
      font-size: 22rpx;
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
    }
  }

  .info-row {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;

    .info-icon {
      width: 26rpx;
      height: 26rpx;
      margin-right: 12rpx;
      opacity: 0.5;
    }

    .info-text {
      font-size: 24rpx;
      color: #888888;
      margin-right: 16rpx;
    }

    .danger-text {
      font-size: 24rpx;
      color: #FF3B30;
    }
  }

  .company-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 24rpx;
    padding-top: 24rpx;
    border-top: 1rpx dashed #EEEEEE;

    .company-info-wrap {
      display: flex;
      align-items: center;

      .company-logo {
        width: 80rpx;
        height: 80rpx;
        border-radius: 16rpx;
        margin-right: 20rpx;
        background-color: #f5f5f5;
        border: 1rpx solid #f0f0f0;
      }

      .company-text-col {
        display: flex;
        flex-direction: column;

        .company-name-box {
          display: flex;
          align-items: center;
          margin-bottom: 6rpx;

          .company-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #1A1A1A;
            margin-right: 10rpx;
          }

          .verified-icon {
            width: 24rpx;
            height: 24rpx;
          }
        }

        .company-location {
          font-size: 24rpx;
          color: #888888;
        }
      }
    }

    .close-icon {
      width: 32rpx;
      height: 32rpx;
      opacity: 0.3;
    }
  }
}

.empty-wrap {
  padding: 100rpx 0;
  text-align: center;
  .empty-text {
    color: #999;
    font-size: 28rpx;
  }
}

.load-end-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 30rpx 40rpx;
  gap: 20rpx;

  .load-end-line {
    flex: 1;
    height: 1rpx;
    background-color: #E4E7ED;
  }

  .load-end-text {
    font-size: 22rpx;
    color: #BBBBBB;
  }
}

.tabbar-placeholder {
  height: 180rpx;
}

/* 反馈弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 60rpx;
}

.popup-content {
  width: 80%; /* 减小宽度，让整体更精致 */
  background: #FFFFFF; /* 改为白色背景 */
  border-radius: 32rpx;
  padding: 30rpx 40rpx 60rpx;
  position: relative;
  box-shadow: 0 20rpx 80rpx rgba(0,0,0,0.15);
}

.popup-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 30rpx;

  .popup-close {
    width: 36rpx;
    height: 36rpx;
    opacity: 0.3;
    /* 移除之前的 invert，现在容器是白的，图标应该是灰色的 */
  }
}

.popup-body {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  align-items: center;
}

.feedback-btn {
  width: 85%; /* 按钮调短一点 */
  height: 80rpx; /* 高度也微调 */
  background: #EBF2FF; /* 使用App主题浅蓝色背景，不深沉且统一 */
  border-radius: 100rpx; /* 全圆角符合app风格 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  
  text {
    font-size: 28rpx;
    color: #1F6CFF; /* 使用主题深蓝色文字 */
    font-weight: 500;
  }

  &:active {
    opacity: 0.8;
    transform: scale(0.98);
  }
}
</style>
