<template>
  <view class="container">
    <scroll-view scroll-y class="scroll-body">
      <!-- 头部卡片 -->
      <view class="header-card">
        <view class="title-row">
          <text class="title">{{ job.title }}</text>
          <text class="salary">{{ job.salaryText }}</text>
        </view>
        <view class="urgent-tag-wrap" v-if="job.isUrgent">
          <text class="urgent-tag">急招</text>
        </view>
        
        <view class="meta-info">
          <view class="meta-item">
            <image src="/static/icons/location.svg" class="meta-icon" mode="aspectFit"></image>
            <text>{{ job.location }}</text>
          </view>
          <view class="meta-item">
            <image src="/static/icons/user.svg" class="meta-icon" mode="aspectFit"></image>
            <text>招录 {{ job.count }} 人</text>
          </view>
          <view class="meta-item">
            <image src="/static/icons/time.svg" class="meta-icon" mode="aspectFit"></image>
            <text>截止：{{ job.deadline }}</text>
            <text class="danger-text" v-if="job.isExpiring"> 即将截止</text>
          </view>
        </view>
      </view>

      <!-- 企业/招聘官信息 -->
      <view class="hr-section">
        <image src="https://img.js.design/assets/smartFill/img341164da0af508.png" class="hr-avatar" mode="aspectFill"></image>
        <view class="hr-info">
          <view class="hr-name-row">
            <text class="hr-name">丁先生</text>
            <text class="hr-tag">招聘中</text>
          </view>
          <text class="hr-company">{{ job.company }} · 人事负责人</text>
        </view>
        <image src="/static/icons/verified.svg" class="verified-icon" mode="aspectFit"></image>
      </view>

      <!-- 岗位详情 -->
      <view class="detail-section">
        <view class="section-title">岗位详情</view>
        <view class="tags-cloud">
          <text class="tag-item" v-for="(tag, index) in job.tags" :key="index">{{ tag }}</text>
          <text class="tag-item">内部审计</text>
          <text class="tag-item">风险控制</text>
        </view>

        <view class="description-block">
          <text class="sub-title">职位描述：</text>
          <text class="content-text">
            我们需要一位经验丰富的审计师加入我们的团队。您将负责执行复杂的财务和运营审计，识别流程改进机会，并向高级管理层提供战略建议。
          </text>
        </view>

        <view class="description-block">
          <text class="sub-title">任职要求：</text>
          <view class="requirement-list">
            <view class="req-item" v-for="(req, index) in requirements" :key="index">
              <view class="dot"></view>
              <text class="req-text">{{ req }}</text>
            </view>
          </view>
        </view>

        <view class="description-block">
          <text class="sub-title">福利待遇：</text>
          <view class="requirement-list">
            <view class="req-item">
              <view class="dot"></view>
              <text class="req-text">提供行业领先的薪资水平；</text>
            </view>
            <view class="req-item">
              <view class="dot"></view>
              <text class="req-text">完善的五险一金及其它补充福利；</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-left" @click="handleCollect">
        <view class="icon-btn">
          <image :src="isCollected ? '/static/icons/star_filled.svg' : '/static/icons/star_hollow.svg'" class="btn-icon" mode="aspectFit"></image>
          <text>{{ isCollected ? '已收藏' : '收藏' }}</text>
        </view>
      </view>
      <view 
        class="main-btn" 
        :class="[jobState]" 
        @click="handleMainAction"
      >
        <text>{{ btnText }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { createOrGetSession } from '../../api/message.js';

const isCollected = ref(false);

// 岗位状态: 'initial', 'paid', 'assessed', 'added'
const jobState = ref('initial');

const btnText = computed(() => {
  switch (jobState.value) {
    case 'initial': return '咨询';
    case 'paid': return '开始测评';
    case 'assessed': return '加入意向岗位';
    case 'added': return '已加入意向岗位';
    default: return '咨询';
  }
});

const job = ref({
  id: 0,
  title: '高级审计师',
  salaryText: '13K-23K',
  location: '上海市·黄浦区',
  count: 1,
  deadline: '2025-12-12 24:00',
  isUrgent: true,
  isExpiring: true,
  company: '华财仁合',
  tags: ['全职', '五险一金', '本科', 'CPA']
});

const requirements = ref([
  '具备3年以上知名会计师事务所工作经验优先；',
  '精通财务审计准则及相关法律法规；',
  '出色的沟通表达能力与项目管理能力。'
]);

onShow(() => {
    // 检查是否已支付 (由 chat 页面设置)
    if (uni.getStorageSync('job_0_paid')) {
        if (jobState.value === 'initial') {
            jobState.value = 'paid';
        }
    }
    
    // 检查持久化状态
    const savedState = uni.getStorageSync('job_0_state');
    if (savedState) {
        jobState.value = savedState;
    }
});

const handleMainAction = async () => {
  if (jobState.value === 'initial') {
    try {
      uni.showLoading({ title: '正在连接客服...' });
      const userInfo = uni.getStorageSync('userInfo') || {};
      const userId = userInfo.studentId || null;
      const userName = userInfo.name || '用户';
      const userAvatar = userInfo.avatarUrl || '/static/images/user_avatar.png';
      const res = await createOrGetSession({
        sessionType: 1,
        fromUserId: userId,
        fromUserName: userName,
        fromUserAvatar: userAvatar,
        sourceId: 'job_' + (job.value?.id || '')
      });
      uni.hideLoading();
      if (res.data) {
        const session = res.data;
        uni.navigateTo({
          url: `/pages/chat/chat?sessionId=${session.sessionId}&sessionNo=${session.sessionNo || ''}&fromUserId=${userId || ''}&userName=${encodeURIComponent(userName)}`
        });
      } else {
        uni.showToast({ title: '创建会话失败', icon: 'none' });
      }
    } catch (err) {
      uni.hideLoading();
      console.error('创建会话失败:', err);
      uni.showToast({ title: '连接失败，请重试', icon: 'none' });
    }
  } else if (jobState.value === 'paid') {
    uni.showLoading({ title: '加载测评中...' });
    setTimeout(() => {
      uni.hideLoading();
      uni.showModal({
        title: '测评通过',
        content: '恭喜您完成测评并合格！',
        showCancel: false,
        success: () => {
          updateState('assessed');
        }
      });
    }, 1500);
  } else if (jobState.value === 'assessed') {
    uni.showLoading({ title: '加入中...' });
    setTimeout(() => {
      uni.hideLoading();
      uni.showToast({ title: '加入成功', icon: 'success' });
      updateState('added');
    }, 1000);
  }
};

const updateState = (state) => {
  jobState.value = state;
  uni.setStorageSync('job_0_state', state);
};

const handleCollect = () => {
  isCollected.value = !isCollected.value;
  uni.showToast({
    title: isCollected.value ? '收藏成功' : '已取消收藏',
    icon: 'none'
  });
};
</script>

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

.scroll-body {
  flex: 1;
}

.header-card {
  background-color: #FFFFFF;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;

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

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

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

  .urgent-tag-wrap {
    margin-bottom: 24rpx;
    .urgent-tag {
      background: #FFF2F0;
      color: #FF4D4F;
      font-size: 22rpx;
      padding: 4rpx 16rpx;
      border-radius: 6rpx;
    }
  }

  .meta-info {
    display: flex;
    flex-wrap: wrap;
    gap: 24rpx;

    .meta-item {
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #999999;

      .meta-icon {
        width: 28rpx;
        height: 28rpx;
        margin-right: 8rpx;
      }

      .danger-text {
        color: #FF4D4F;
        margin-left: 8rpx;
      }
    }
  }
}

.hr-section {
  background-color: #FFFFFF;
  padding: 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .hr-avatar {
    width: 90rpx;
    height: 90rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    background-color: #f0f0f0;
  }

  .hr-info {
    flex: 1;
    .hr-name-row {
      display: flex;
      align-items: center;
      margin-bottom: 6rpx;
      .hr-name {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-right: 12rpx;
      }
      .hr-tag {
        font-size: 20rpx;
        color: #FFFFFF;
        background: #1F6CFF;
        padding: 2rpx 10rpx;
        border-radius: 4rpx;
      }
    }
    .hr-company {
      font-size: 24rpx;
      color: #999;
    }
  }

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

.detail-section {
  background-color: #FFFFFF;
  padding: 40rpx 30rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #1A1A1A;
    margin-bottom: 24rpx;
    border-left: 8rpx solid #1F6CFF;
    padding-left: 20rpx;
  }

  .tags-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 30rpx;

    .tag-item {
      background: #F0F2F5;
      color: #777777;
      font-size: 24rpx;
      padding: 8rpx 20rpx;
      border-radius: 6rpx;
    }
  }

  .description-block {
    margin-bottom: 36rpx;

    .sub-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #444444;
      margin-bottom: 12rpx;
      display: block;
    }

    .content-text {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.6;
    }

    .requirement-list {
      .req-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10rpx;
        .dot {
          width: 8rpx;
          height: 8rpx;
          background: #1F6CFF;
          border-radius: 50%;
          margin-top: 15rpx;
          margin-right: 16rpx;
          flex-shrink: 0;
        }
        .req-text {
          font-size: 28rpx;
          color: #666666;
          line-height: 1.5;
        }
      }
    }
  }
}

.bottom-placeholder {
  height: 140rpx;
}

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

  .action-left {
    margin-right: 40rpx;
    .icon-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      .btn-icon {
        width: 40rpx;
        height: 40rpx;
        margin-bottom: 4rpx;
      }
      text {
        font-size: 20rpx;
        color: #999;
      }
    }
  }

  .main-btn {
    flex: 1;
    height: 80rpx;
    background: #FFB800; // 默认黄色 (咨询/开始测评)
    border-radius: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    text {
      color: #FFFFFF;
      font-size: 28rpx;
      font-weight: bold;
    }

    &.initial, &.paid {
        background: #FFB800;
    }

    &.assessed {
        background: #1F6CFF; // 测评合格后变为蓝色
    }

    &.added {
        background: #E0E0E0; // 已加入后禁用灰色
        pointer-events: none;
        text {
            color: #999;
        }
    }
  }
}
</style>
