<template>
  <view class="select-resume-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="header-title">选择投递简历</text>
      <text class="header-subtitle">请选择一份附件简历进行投递</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-box" v-if="isLoading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 简历列表 -->
    <view class="resume-list" v-else-if="resumeList.length > 0">
      <view 
        class="resume-card" 
        :class="{ 'selected': selectedOssId === item.ossId }"
        v-for="(item, idx) in resumeList" 
        :key="item.id"
        @click="selectResume(item)"
      >
        <view class="card-left">
          <view class="file-icon-box">
            <image src="/static/icons/pdf.svg" mode="aspectFit" class="pdf-icon"></image>
          </view>
          <view class="file-info">
            <text class="file-name text-ellipsis">{{ item.name }}</text>
            <text class="file-size" v-if="item.fileSize">{{ formatFileSize(item.fileSize) }}</text>
          </view>
        </view>
        <view class="radio-box">
          <view class="radio-outer">
            <view class="radio-inner" v-if="selectedOssId === item.ossId"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image src="/static/icons/empty_resume.svg" mode="aspectFit" class="empty-icon" v-if="false"></image>
      <view class="empty-icon-text">
        <text>暂无附件简历</text>
      </view>
      <text class="empty-desc">请先在"我的"页面上传附件简历</text>
      <view class="empty-action" @click="goToUpload">
        <text>去上传简历</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="resumeList.length > 0">
      <button class="submit-btn" :class="{ 'disabled': !selectedOssId }" @click="handleDeliver">
        <text>{{ delivering ? '投递中...' : '确认投递' }}</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getAppendixList } from '../../api/student.js';
import { applyPosition } from '../../api/assessment.js';

const isLoading = ref(true);
const delivering = ref(false);
const resumeList = ref([]);
const selectedOssId = ref(null);
const postId = ref(null);

onLoad((options) => {
  if (options.postId) {
    postId.value = options.postId;
  }
  fetchResumeList();
});

const fetchResumeList = async () => {
  try {
    isLoading.value = true;
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' });
      }, 1000);
      return;
    }
    const res = await getAppendixList(userInfo.studentId);
    if (res && res.code === 200) {
      resumeList.value = res.data.map(item => ({
        id: item.id,
        name: item.fileName,
        url: item.url,
        ossId: item.ossId,
        fileSize: item.fileSize
      }));
      // 默认选中第一个
      if (resumeList.value.length > 0) {
        selectedOssId.value = resumeList.value[0].ossId;
      }
    }
  } catch (err) {
    console.error('获取简历列表失败:', err);
    uni.showToast({ title: '获取简历列表失败', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
};

const selectResume = (item) => {
  selectedOssId.value = item.ossId;
};

const formatFileSize = (size) => {
  if (!size) return '';
  if (size < 1024) return size + 'B';
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB';
  return (size / (1024 * 1024)).toFixed(1) + 'MB';
};

const handleDeliver = async () => {
  if (!selectedOssId.value || delivering.value) return;
  
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo || !userInfo.studentId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  try {
    delivering.value = true;
    uni.showLoading({ title: '投递中...' });
    const res = await applyPosition({ 
      postId: postId.value, 
      resumeOssId: selectedOssId.value 
    });
    uni.hideLoading();
    if (res.code === 200) {
      // 标记为已投递
      uni.setStorageSync(`candidate_applied_${postId.value}`, true);
      uni.showToast({ title: '投递成功', icon: 'success' });
      setTimeout(() => {
        // 返回岗位详情页并刷新状态
        const pages = getCurrentPages();
        if (pages.length > 1) {
          uni.$emit('resume_delivered', { postId: postId.value });
          uni.navigateBack();
        }
      }, 1500);
    } else if (res.msg && res.msg.includes('已投递')) {
      uni.setStorageSync(`candidate_applied_${postId.value}`, true);
      uni.showToast({ title: '您已投递过该岗位', icon: 'none' });
      setTimeout(() => {
        uni.$emit('resume_delivered', { postId: postId.value });
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({ title: res.msg || '投递失败', icon: 'none' });
    }
  } catch (err) {
    uni.hideLoading();
    console.error('投递失败:', err);
    const errMsg = String(err?.msg || err?.message || '');
    if (errMsg.includes('已投递')) {
      uni.setStorageSync(`candidate_applied_${postId.value}`, true);
      uni.showToast({ title: '您已投递过该岗位', icon: 'none' });
      setTimeout(() => {
        uni.$emit('resume_delivered', { postId: postId.value });
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({ title: '网络错误，投递失败', icon: 'none' });
    }
  } finally {
    delivering.value = false;
  }
};

const goToUpload = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.select-resume-container {
  min-height: 100vh;
  background-color: #F6F8FB;
  padding-bottom: 160rpx;
}

.page-header {
  padding: 40rpx 40rpx 20rpx;
  .header-title {
    display: block;
    font-size: 40rpx;
    font-weight: bold;
    color: #1A1A1A;
    margin-bottom: 12rpx;
  }
  .header-subtitle {
    font-size: 26rpx;
    color: #999999;
  }
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  .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); }
}

.resume-list {
  padding: 20rpx 30rpx;
}

.resume-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border: 2rpx solid #F0F2F5;
  transition: all 0.2s ease;

  &.selected {
    border-color: #1F6CFF;
    background: #F0F6FF;
    box-shadow: 0 4rpx 16rpx rgba(31, 108, 255, 0.1);
  }

  &:active {
    opacity: 0.9;
  }

  .card-left {
    display: flex;
    align-items: center;
    flex: 1;
    overflow: hidden;

    .file-icon-box {
      width: 80rpx;
      height: 80rpx;
      background: #FFF5F0;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 24rpx;
      flex-shrink: 0;
      .pdf-icon {
        width: 48rpx;
        height: 48rpx;
      }
    }

    .file-info {
      flex: 1;
      overflow: hidden;
      .file-name {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        color: #1A1A1A;
        margin-bottom: 8rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .file-size {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  .radio-box {
    flex-shrink: 0;
    margin-left: 20rpx;
    .radio-outer {
      width: 44rpx;
      height: 44rpx;
      border-radius: 50%;
      border: 3rpx solid #D0D0D0;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;
    }
    .radio-inner {
      width: 24rpx;
      height: 24rpx;
      border-radius: 50%;
      background: #1F6CFF;
    }
  }

  &.selected .radio-outer {
    border-color: #1F6CFF;
  }
}

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
  .empty-icon-text {
    width: 120rpx;
    height: 120rpx;
    background: #F0F2F5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
    text {
      font-size: 24rpx;
      color: #CCCCCC;
    }
  }
  .empty-desc {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }
  .empty-action {
    padding: 16rpx 48rpx;
    background: #1F6CFF;
    border-radius: 36rpx;
    text {
      font-size: 28rpx;
      color: #FFFFFF;
      font-weight: 500;
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 24rpx 40rpx calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 999;

  .submit-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #1F6CFF;
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 44rpx;
    text-align: center;
    border: none;
    box-shadow: 0 8rpx 16rpx rgba(31, 108, 255, 0.2);

    &::after {
      border: none;
    }

    &:active {
      opacity: 0.9;
    }

    &.disabled {
      background: #E0E0E0;
      box-shadow: none;
      color: #999;
      pointer-events: none;
    }
  }
}
</style>
