<template>
  <view class="container">
    <scroll-view class="offer-scroll" scroll-y refresher-enabled @refresherrefresh="fetchOfferList">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text>加载中...</text>
      </view>
      
      <!-- 无数据提示 -->
      <view v-else-if="offers.length === 0" class="empty-state">
        <image src="/static/icons/empty.png" class="empty-icon" mode="aspectFit"></image>
        <text class="empty-text">暂无Offer记录</text>
      </view>
      
      <view v-else class="offer-list">
        <view v-for="(offer, index) in offers" :key="index" class="offer-card">
          <!-- 卡片头部：公司 + 状态标签 -->
          <view class="card-top">
            <view class="company-info">
              <text class="company-name">{{ offer.company }}</text>
              <text class="job-name">{{ offer.jobName }}</text>
            </view>
            <view :class="['status-badge', offer.enterpriseStatus === 'pending' ? 'pending' : (offer.enterpriseStatus === 'adopted' ? 'adopted' : 'rejected')]">
              <text>{{ getStatusBadge(offer) }}</text>
            </view>
          </view>

          <!-- 投递时间 -->
          <view class="card-meta">
            <text class="meta-time">投递时间：{{ offer.createTime }}</text>
          </view>

          <!-- 企业已处理 - 审核结果区域 -->
          <view v-if="offer.enterpriseStatus !== 'pending'" class="result-section">
            <view class="result-row">
              <view class="result-left">
                <image v-if="offer.enterpriseStatus === 'adopted'" src="/static/icons/success.svg" class="result-icon" mode="aspectFit"></image>
                <image v-else src="/static/icons/fail.svg" class="result-icon" mode="aspectFit"></image>
                <text :class="['result-text', offer.enterpriseStatus]">{{ getResultDesc(offer.enterpriseStatus) }}</text>
              </view>

              <!-- 操作按钮 -->
              <view class="action-btns" v-if="offer.enterpriseStatus === 'adopted' && offer.studentStatus === 'pending'">
                <button class="btn btn-outline" @click="handleReject(offer)">拒绝</button>
                <button class="btn btn-primary" @click="handleAccept(offer)">接受Offer</button>
              </view>
              <view :class="['student-status-tag', offer.studentStatus]" v-else-if="offer.studentStatus !== 'pending'">
                <text>{{ offer.statusText }}</text>
              </view>
            </view>
          </view>

          <!-- 签约文件 -->
          <view v-if="offer.enterpriseStatus === 'adopted' && offer.fileUrl" class="file-link" @click="openFile(offer.fileUrl)">
            <image src="/static/icons/pdf.svg" class="file-icon"></image>
            <text class="file-name">{{ offer.fileName }}</text>
            <text class="file-arrow">></text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 接受Offer确认协议弹窗 -->
    <view class="modal-mask" v-if="showAcceptModal">
      <view class="modal-content protocol-modal">
        <view class="modal-header">确认接受Offer?</view>
        <scroll-view class="protocol-body" scroll-y>
          <view class="rich-text-container">
            <rich-text :nodes="protocolHtml"></rich-text>
          </view>
        </scroll-view>
        <view class="modal-footer">
          <view class="btns-row">
            <button class="btn-cancel" @click="showAcceptModal = false">取消</button>
            <button class="btn-confirm" :disabled="countdown > 0" @click="confirmAccept">
              {{ countdown > 0 ? (countdown + 's后确认接受') : '已阅读，确认接受' }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 拒绝Offer确认弹窗 -->
    <view class="modal-mask" v-if="showRejectModal">
      <view class="modal-content confirm-modal">
        <view class="confirm-title">确认拒绝?</view>
        <view class="confirm-desc">拒绝后不可恢复</view>
        <view class="confirm-footer">
          <button class="btn-cancel" @click="showRejectModal = false">取消</button>
          <button class="btn-danger" @click="confirmReject">确认拒绝</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getOfferList, acceptOffer, rejectOffer } from '../../api/offer.js';
import request from '../../utils/request.js';

const showAcceptModal = ref(false);
const showRejectModal = ref(false);
const countdown = ref(10);
let timer = null;

const currentOffer = ref(null);
const offers = ref([]);
const loading = ref(false);

// Offer协议内容（从 main_agreement 表 type=offer 读取，与总控页面共用）
const protocolHtml = ref('');

// 加载Offer协议
const loadOfferConfig = async () => {
  try {
    const res = await request({ url: '/miniapp/auth/agreement?type=offer', method: 'GET' });
    if (res.code === 200 && res.data && res.data.content) {
      protocolHtml.value = res.data.content;
    }
  } catch (e) {
    console.error('获取Offer协议失败', e);
  }
};

// 获取Offer列表
const fetchOfferList = async () => {
    loading.value = true;
    try {
        const res = await getOfferList();
        if (res.code === 200) {
            offers.value = res.data.map(item => ({
                id: item.id,
                jobName: item.postName || '未知岗位',
                company: item.companyName || '未知企业',
                fileName: item.offerFileName || 'offer.pdf',
                fileUrl: item.offerFileUrl,
                studentStatus: item.studentStatus || 'pending',
                enterpriseStatus: item.enterpriseStatus || 'pending',
                statusText: getStatusText(item.studentStatus, item.enterpriseStatus),
                status: item.studentStatus === 'pending' ? 'pending' : item.studentStatus,
                offerTime: item.offerTime,
                createTime: formatTime(item.createTime)
            }));
        }
    } catch (error) {
        uni.showToast({ title: '获取Offer列表失败', icon: 'none' });
    } finally {
        loading.value = false;
    }
};

const formatTime = (time) => {
    if (!time) return '--';
    const d = new Date(time);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hour = String(d.getHours()).padStart(2, '0');
    const minute = String(d.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
};

const getStatusBadge = (offer) => {
    if (offer.enterpriseStatus === 'pending') return '审核中';
    if (offer.enterpriseStatus === 'adopted') return '已录用';
    if (offer.enterpriseStatus === 'rejected') return '未通过';
    return '未知';
};

const getResultDesc = (enterpriseStatus) => {
    switch (enterpriseStatus) {
        case 'adopted': return '企业已录用，请确认Offer';
        case 'rejected': return '很遗憾，该岗位暂不匹配';
        default: return '';
    }
};

const getStatusText = (studentStatus, enterpriseStatus) => {
    if (enterpriseStatus === 'rejected') return '已拒绝';
    if (studentStatus === 'accepted') return '已接受';
    if (studentStatus === 'rejected') return '已拒绝';
    return '待确认';
};

const handleAccept = (offer) => {
    currentOffer.value = offer;
    showAcceptModal.value = true;
    startCountdown();
};

const handleReject = (offer) => {
    currentOffer.value = offer;
    showRejectModal.value = true;
};

const startCountdown = () => {
    countdown.value = 10;
    if (timer) clearInterval(timer);
    timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearInterval(timer);
        }
    }, 1000);
};

const confirmAccept = async () => {
    if (!currentOffer.value) return;
    try {
        const res = await acceptOffer(currentOffer.value.id);
        if (res.code === 200) {
            uni.showToast({ title: '已接受Offer', icon: 'success' });
            fetchOfferList();
        } else {
            uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
        }
    } catch (error) {
        uni.showToast({ title: '操作失败，请重试', icon: 'none' });
    } finally {
        showAcceptModal.value = false;
    }
};

const confirmReject = async () => {
    if (!currentOffer.value) return;
    try {
        const res = await rejectOffer(currentOffer.value.id);
        if (res.code === 200) {
            uni.showToast({ title: '已拒绝Offer', icon: 'none' });
            fetchOfferList();
        } else {
            uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
        }
    } catch (error) {
        uni.showToast({ title: '操作失败，请重试', icon: 'none' });
    } finally {
        showRejectModal.value = false;
    }
};

onMounted(() => {
    loadOfferConfig();
    fetchOfferList();
});

const openFile = (url) => {
    if (!url) {
        uni.showToast({ title: '文件链接无效', icon: 'none' });
        return;
    }
    const getFileType = (fileUrl) => {
        const match = fileUrl.match(/\.(\w+)(\?|$)/);
        return match ? match[1].toLowerCase() : 'pdf';
    };
    const fileType = getFileType(url);
    uni.showLoading({ title: '加载中...' });
    uni.downloadFile({
        url: url,
        success: (res) => {
            if (res.statusCode === 200) {
                const filePath = res.tempFilePath;
                uni.openDocument({
                    filePath: filePath,
                    fileType: fileType,
                    showMenu: true,
                    success: () => { uni.hideLoading(); },
                    fail: (err) => {
                        uni.hideLoading();
                        uni.showToast({ title: '预览失败', icon: 'none' });
                    }
                });
            }
        },
        fail: (err) => {
            uni.hideLoading();
            uni.showToast({ title: '下载失败', icon: 'none' });
        }
    });
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #F5F6F8;
}

.offer-list {
  padding: 24rpx 30rpx;
}

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

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 150rpx 0;
  .empty-icon { width: 200rpx; height: 200rpx; margin-bottom: 30rpx; }
  .empty-text { font-size: 28rpx; color: #999; }
}

.offer-card {
  background: #FFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04);

  .card-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16rpx;

    .company-info {
      flex: 1;
      min-width: 0;
      .company-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #1A1A1A;
        display: block;
        margin-bottom: 6rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .job-name {
        font-size: 26rpx;
        color: #888;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .status-badge {
      flex-shrink: 0;
      padding: 6rpx 20rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      font-weight: 500;
      margin-left: 16rpx;

      &.pending {
        background: #FFF7E6;
        color: #FA8C16;
      }
      &.adopted {
        background: #F0FFF4;
        color: #52C41A;
      }
      &.rejected {
        background: #FFF1F0;
        color: #FF4D4F;
      }
    }
  }

  .card-meta {
    .meta-time {
      font-size: 24rpx;
      color: #BBB;
    }
  }

  .result-section {
    margin-top: 24rpx;
    padding-top: 24rpx;
    border-top: 1rpx solid #F0F2F5;

    .result-row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .result-left {
        display: flex;
        align-items: center;
        flex: 1;
        min-width: 0;

        .result-icon {
          width: 36rpx;
          height: 36rpx;
          margin-right: 12rpx;
          flex-shrink: 0;
        }

        .result-text {
          font-size: 28rpx;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &.adopted { color: #52C41A; }
          &.rejected { color: #FF4D4F; }
        }
      }

      .action-btns {
        display: flex;
        gap: 16rpx;
        flex-shrink: 0;
        margin-left: 16rpx;

        .btn {
          height: 60rpx;
          line-height: 58rpx;
          font-size: 24rpx;
          border-radius: 30rpx;
          padding: 0 28rpx;
          margin: 0;
          &::after { border: none; }
          &.btn-outline { background: #FFF; color: #666; border: 1rpx solid #DDD; }
          &.btn-primary { background: #1F6CFF; color: #FFF; }
        }
      }

      .student-status-tag {
        flex-shrink: 0;
        padding: 6rpx 20rpx;
        border-radius: 20rpx;
        font-size: 22rpx;
        font-weight: 500;
        margin-left: 16rpx;

        &.accepted {
          background: #F0FFF4;
          color: #52C41A;
        }
        &.rejected {
          background: #FFF1F0;
          color: #FF4D4F;
        }
      }
    }
  }

  .file-link {
    margin-top: 24rpx;
    padding: 20rpx 24rpx;
    background: #F8F9FB;
    border-radius: 16rpx;
    display: flex;
    align-items: center;

    .file-icon { width: 40rpx; height: 40rpx; margin-right: 12rpx; flex-shrink: 0; }
    .file-name { font-size: 26rpx; color: #1F6CFF; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .file-arrow { font-size: 26rpx; color: #CCC; margin-left: 8rpx; flex-shrink: 0; }
  }
}

/* Modal */
.modal-mask {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.6); z-index: 1000;
  display: flex; align-items: center; justify-content: center;
}

.modal-content {
  background: #FFF; border-radius: 32rpx; overflow: hidden;
  &.protocol-modal { width: 620rpx; height: 1000rpx; display: flex; flex-direction: column; overflow: hidden; }
  &.confirm-modal { width: 540rpx; padding: 60rpx 40rpx; text-align: center; }
}

.modal-header { padding: 40rpx; text-align: center; font-size: 34rpx; font-weight: bold; flex-shrink: 0; }

.protocol-body {
  flex: 1; height: 0; min-height: 0;
  .rich-text-container { padding: 0 40rpx 40rpx; box-sizing: border-box; }
}

.modal-footer {
  flex-shrink: 0;
  padding: 24rpx 40rpx calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #F0F2F5;
  background: #FFF;
  .btns-row {
    display: flex; gap: 20rpx;
    button {
      height: 72rpx; line-height: 72rpx; border-radius: 36rpx; font-size: 26rpx;
      &::after { border: none; }
      &.btn-cancel { flex: 0 0 160rpx; background: #F5F5F7; color: #666; }
      &.btn-confirm { flex: 1; background: #1F6CFF; color: #FFF; &:disabled { opacity: 0.3; } }
    }
  }
}

.confirm-title { font-size: 36rpx; font-weight: bold; margin-bottom: 20rpx; }
.confirm-desc { font-size: 28rpx; color: #888; margin-bottom: 60rpx; }
.confirm-footer {
  display: flex; gap: 20rpx;
  button {
    flex: 1; height: 68rpx; line-height: 68rpx; border-radius: 34rpx; font-size: 26rpx;
    &::after { border: none; }
    &.btn-cancel { background: #F5F5F7; color: #666; }
    &.btn-danger { background: #1F6CFF; color: #FFF; }
  }
}
</style>
