<template>
  <view class="detail-container">
    <scroll-view scroll-y class="scroll-wrapper">
      <!-- 顶部基础信息 -->
      <view class="section header-section">
        <view class="title-line">
          <view class="left-box">
            <text class="job-name">{{ jobInfo.postName || '' }}</text>
            <text class="urgent-tag" v-if="jobInfo.isUrgent === 1">急招</text>
          </view>
          <text class="salary">{{ jobInfo.salaryRange || '面议' }}</text>
        </view>
        
        <view class="meta-list">
          <view class="meta-item">
            <image src="/static/icons/location.svg" class="icon" mode="aspectFit"></image>
            <text>{{ jobInfo.workProvince || '' }}{{ jobInfo.workCity ? '·' + jobInfo.workCity : '' }}{{ jobInfo.workDistrict ? '·' + jobInfo.workDistrict : '' }}</text>
          </view>
          <view class="meta-item">
            <image src="/static/icons/user.svg" class="icon" mode="aspectFit"></image>
            <text>招录 {{ jobInfo.recruitNum || 1 }} 人</text>
          </view>
          <view class="meta-item">
            <image src="/static/icons/time.svg" class="icon" mode="aspectFit"></image>
            <text>截止时间：{{ jobInfo.registrationEndDate ? jobInfo.registrationEndDate.split(' ')[0] : '长期有效' }}</text>
          </view>
        </view>
      </view>

      <!-- HR 信息 -->
      <view class="section hr-section">
        <image :src="jobInfo.companyAvatar || '/static/images/hr_avatar.svg'" class="hr-avatar" mode="aspectFill"></image>
        <view class="hr-content">
          <text class="hr-name">{{ jobInfo.companyName || '平台推荐' }}</text>
          <text class="hr-desc">人事负责人</text>
        </view>
      </view>

      <!-- 岗位详情内容 -->
      <view class="section detail-content">
        <view class="section-title">岗位详情</view>
        
        <!-- 标签云 -->
        <view class="tag-cloud">
          <text class="tag-label" v-for="tag in tags" :key="tag">{{ tag }}</text>
        </view>

        <!-- 岗位描述（富文本，来自数据库 post_description） -->
        <view class="rich-text-wrapper" v-if="jobInfo.postDescription">
          <rich-text :nodes="jobInfo.postDescription"></rich-text>
        </view>
        <view class="info-block" v-else>
          <text class="block-text">暂无岗位详情</text>
        </view>
      </view>

      <!-- 办公地址 - 接入动态地图并使用气泡显示地址 -->
      <view class="section address-section">
        <view class="section-title">办公地址</view>
        <view class="map-wrapper">
          <map 
            class="map-view" 
            :latitude="latitude" 
            :longitude="longitude" 
            :markers="markers"
            :scale="16"
            show-location
          ></map>
        </view>
      </view>

      <!-- 公司概况 -->
      <view class="section company-section">
        <view class="company-header">
          <image :src="jobInfo.companyAvatar || '/static/images/logo1.png'" class="company-logo" mode="aspectFit"></image>
          <text class="company-name">{{ jobInfo.companyName || '未知企业' }}</text>
        </view>
        <text class="company-desc">
          这是一段公司的概览信息，暂无详细内容。
        </text>
      </view>

      <!-- 到底提示 -->
      <view class="end-tip">
        <text>— 已到底啦~ —</text>
      </view>

      <view class="safe-bottom-holder"></view>
    </scroll-view>

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

<script setup lang="js">
import { ref, computed, onUnmounted } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { getPositionDetail } from '../../api/position.js';
import { createOrGetSession } from '../../api/message.js';
import { addCollection, delCollection, checkCollection } from '../../api/collection.js';
import { getAssessmentRecordList, getAssessmentList } from '../../api/assessment.js';

const isCollected = ref(false);
const collectionId = ref(null);
const jobInfo = ref({});
const tags = ref([]);

// 岗位状态: '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 positionId = ref(null);

const checkState = async () => {
    console.log('Checking job state for position:', positionId.value);
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId || !positionId.value) {
        jobState.value = 'initial';
        return;
    }

    // ① 已投递过 → 直接显示已投递
    const appliedKey = `candidate_applied_${positionId.value}`;
    if (uni.getStorageSync(appliedKey)) {
        jobState.value = 'added';
        return;
    }

    try {
        // ② 查询该岗位关联的测评列表
        const evalRes = await getAssessmentList({ positionId: positionId.value, pageNum: 1, pageSize: 100 });
        // 检查该岗位下是否有测评已支付（按evaluationId区分）
        const isAnyEvalPaid = evalRes.code === 200 && evalRes.rows
            ? evalRes.rows.some(e => uni.getStorageSync(`audit_paid_${e.id}`))
            : uni.getStorageSync(`audit_paid_${positionId.value}`);

        if (evalRes.code !== 200 || !evalRes.rows || evalRes.rows.length === 0) {
            // 无关联测评，检查是否已支付
            jobState.value = isAnyEvalPaid ? 'paid' : 'initial';
            return;
        }

        // ③ 获取用户的测评记录
        const recordRes = await getAssessmentRecordList(userInfo.studentId);
        if (recordRes.code !== 200 || !recordRes.data) {
            jobState.value = isAnyEvalPaid ? 'paid' : 'initial';
            return;
        }

        // ④ 检查用户是否通过了该岗位关联的任一测评
        const evaluationIds = evalRes.rows.map(e => e.id);
        const passedRecord = recordRes.data.find(r =>
            r.finalResult === '1' && evaluationIds.includes(r.evaluationId)
        );

        if (passedRecord) {
            // 测评通过 → 显示"投递简历"
            jobState.value = 'assessed';
        } else if (isAnyEvalPaid) {
            // 已付款但未通过测评 → 显示"开始测评"
            jobState.value = 'paid';
        } else {
            // 未支付测评费用，只显示咨询按钮
            jobState.value = 'initial';
        }
    } catch (err) {
        console.error('检查状态失败:', err);
        jobState.value = 'initial';
    }
};

const latitude = ref(31.22863);
const longitude = ref(121.45039);
const markers = ref([]);

const fetchDetail = async (id) => {
    console.log('fetchDetail called with id:', id); // 调试日志
    uni.showLoading({ title: '加载中...' });
    try {
        const res = await getPositionDetail(id);
        console.log('getPositionDetail响应:', res); // 调试日志
        if (res.code === 200 && res.data) {
            jobInfo.value = res.data;
            positionId.value = res.data.id;
            const data = res.data;
            
            // 地图坐标赋值
            if (data.latitude && data.longitude) {
                latitude.value = parseFloat(data.latitude);
                longitude.value = parseFloat(data.longitude);
                markers.value = [{
                    id: 1,
                    latitude: latitude.value,
                    longitude: longitude.value,
                    title: data.postName || '办公地点',
                    iconPath: '/static/icons/location.svg',
                    width: 32,
                    height: 32,
                    callout: {
                        content: data.workAddress || (data.workProvince + data.workCity + data.workDistrict),
                        color: '#333333',
                        fontSize: 12,
                        borderRadius: 8,
                        padding: 8,
                        bgColor: '#ffffff',
                        display: 'ALWAYS',
                        boxShadow: '0 4rpx 12rpx rgba(0,0,0,0.1)'
                    }
                }];
            } else {
                // 如果没有经纬度，显示一个默认位置或清空标记
                markers.value = [];
            }
            
            let t = [];
            if(data.postTypeLabel) t.push(data.postTypeLabel);
            if(data.schoolRequirementLabel) t.push(data.schoolRequirementLabel);
            if(data.gradeRequirementLabel) t.push(data.gradeRequirementLabel);
            if(data.welfareTags) {
                t.push(...data.welfareTags.split(',').filter(Boolean));
            }
            tags.value = t;

            // 检查是否已收藏
            console.log('准备检查收藏状态, id:', id);
            checkCollectionStatus(id);
        }
    } catch(err) {
        console.error('获取岗位详情失败:', err);
    } finally {
        uni.hideLoading();
    }
};

// 检查收藏状态
const checkCollectionStatus = async (id) => {
    console.log('checkCollectionStatus called with id:', id); // 调试日志
    const userInfo = uni.getStorageSync('userInfo');
    console.log('checkCollectionStatus userInfo:', userInfo); // 调试日志
    if (!userInfo || !userInfo.studentId) {
        console.log('checkCollectionStatus: 用户未登录');
        return;
    }
    
    try {
        console.log('调用checkCollection API, studentId:', userInfo.studentId, 'targetId:', id, 'type: job'); // 调试日志
        const res = await checkCollection(userInfo.studentId, id, 'job');
        console.log('checkCollection API响应:', res); // 调试日志
        if (res.code === 200 && res.data) {
            isCollected.value = true;
            collectionId.value = res.data.id; // 保存收藏记录ID
            console.log('设置为已收藏, collectionId:', res.data.id);
        } else {
            isCollected.value = false;
            collectionId.value = null;
            console.log('设置为未收藏');
        }
    } catch (err) {
        console.error('检查收藏状态失败', err);
    }
};

// 切换收藏状态
const toggleCollect = async () => {
    console.log('toggleCollect clicked'); // 调试日志
    const userInfo = uni.getStorageSync('userInfo');
    console.log('userInfo:', userInfo); // 调试日志
    
    if (!userInfo || !userInfo.studentId) {
        console.log('用户未登录'); // 调试日志
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' });
        }, 1000);
        return;
    }
    
    if (!jobInfo.value.id) {
        console.log('jobInfo.value.id 为空:', jobInfo.value); // 调试日志
        return;
    }
    
    console.log('准备发送收藏请求, jobInfo.value.id:', jobInfo.value.id); // 调试日志
    uni.showLoading({ title: isCollected.value ? '取消收藏中...' : '收藏中...' });
    
    try {
        if (isCollected.value) {
            // 取消收藏
            console.log('取消收藏, collectionId:', collectionId.value); // 调试日志
            if (collectionId.value) {
                const res = await delCollection(collectionId.value);
                console.log('取消收藏响应:', res); // 调试日志
                if (res.code === 200) {
                    isCollected.value = false;
                    collectionId.value = null;
                    uni.showToast({ title: '已取消收藏', icon: 'none' });
                }
            }
        } else {
            // 添加收藏
            const requestData = {
                studentId: userInfo.studentId,
                targetId: jobInfo.value.id,
                type: 'job'
            };
            console.log('添加收藏请求数据:', requestData); // 调试日志
            const res = await addCollection(requestData);
            console.log('添加收藏响应:', res); // 调试日志
            if (res.code === 200) {
                isCollected.value = true;
                // 添加成功后重新检查获取完整的收藏记录ID
                checkCollectionStatus(jobInfo.value.id);
                uni.showToast({ title: '收藏成功', icon: 'success' });
            } else {
                uni.showToast({ title: res.msg || '收藏失败', icon: 'none' });
            }
        }
    } catch (err) {
        console.error('操作收藏失败', err);
        uni.showToast({ title: '操作失败', icon: 'none' });
    } finally {
        uni.hideLoading();
    }
};

onLoad((options) => {
    if (options.id) {
        positionId.value = options.id;
        fetchDetail(options.id);
    }
    // 监听支付完成事件（chat.vue 支付成功后会 emit）
    uni.$on('payment_done', (data) => {
        console.log('收到 payment_done 事件:', data);
        checkState();
    });
    // 监听简历投递完成事件（select-resume.vue 投递成功后会 emit）
    uni.$on('resume_delivered', (data) => {
        console.log('收到 resume_delivered 事件:', data);
        if (data && data.postId == positionId.value) {
            jobState.value = 'added';
        }
    });
});

onShow(() => {
    if (positionId.value) {
        checkState();
    }
});

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

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.svg';
      
      const res = await createOrGetSession({
        sessionType: 1,
        fromUserId: userId,
        fromUserName: userName,
        fromUserAvatar: userAvatar,
        sourceId: 'job_' + positionId.value
      });
      
      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)}&jobName=${encodeURIComponent(jobInfo.value.postName || '')}&type=job&positionId=${positionId.value}&salaryRange=${encodeURIComponent(jobInfo.value.salaryRange || '')}&companyName=${encodeURIComponent(jobInfo.value.companyName || '')}&workCity=${encodeURIComponent(jobInfo.value.workCity || '')}`
        });
      } else {
        uni.showToast({ title: '创建会话失败', icon: 'none' });
      }
    } catch (err) {
      uni.hideLoading();
      console.error('创建会话失败:', err);
      uni.showToast({ title: '连接失败，请重试', icon: 'none' });
    }
  } else if (jobState.value === 'paid') {
    uni.navigateTo({
      url: '/pages/assessment/remind?family=audit'
    });
  } else if (jobState.value === 'assessed') {
    // 投递简历：跳转到选择简历页面
    const userInfo = uni.getStorageSync('userInfo') || {};
    if (!userInfo.studentId) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' });
      }, 1000);
      return;
    }
    
    uni.navigateTo({
      url: `/pages/my/select-resume?postId=${positionId.value}`
    });
  }
};

const updateState = (state) => {
  jobState.value = state;
};

// 状态逻辑已移至 checkState 内部
</script>

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

.scroll-wrapper {
  flex: 1;
}

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

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #1A1A1A;
  margin-bottom: 30rpx;
}

/* 头部样式 */
.header-section {
  padding-top: 20rpx;
  .title-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .left-box {
      display: flex;
      align-items: center;
      .job-name {
        font-size: 44rpx;
        font-weight: bold;
        color: #1A1A1A;
        margin-right: 16rpx;
      }
      .urgent-tag {
        font-size: 20rpx;
        color: #FF4D4F;
        border: 1rpx solid #FF4D4F;
        padding: 2rpx 10rpx;
        border-radius: 6rpx;
      }
    }
    .salary {
      font-size: 38rpx;
      font-weight: bold;
      color: #1F6CFF;
    }
  }

  .meta-list {
    .meta-item {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      font-size: 26rpx;
      color: #777777;
      
      .icon {
        width: 30rpx;
        height: 30rpx;
        margin-right: 12rpx;
        opacity: 0.7;
      }
      
      .warning-text {
        color: #FF4D4F;
        margin-left: 16rpx;
      }
    }
  }
}

/* HR 区域 */
.hr-section {
  border-top: 1rpx solid #F8F9FB;
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  
  .hr-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin-right: 24rpx;
    background-color: #F0F0F0;
  }
  
  .hr-content {
    .hr-name {
      display: block;
      font-size: 30rpx;
      font-weight: bold;
      color: #1A1A1A;
      margin-bottom: 4rpx;
    }
    .hr-desc {
      font-size: 24rpx;
      color: #888888;
    }
  }
}

/* 岗位详情描述 */
.detail-content {
  border-top: 10rpx solid #F8F9FB;
  .tag-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 40rpx;
    
    .tag-label {
      background-color: #F5F7FA;
      color: #888888;
      font-size: 24rpx;
      padding: 10rpx 24rpx;
      border-radius: 6rpx;
    }
  }
  
  .rich-text-wrapper {
    font-size: 28rpx;
    color: #555555;
    line-height: 1.8;
  }
  
  .info-block {
    margin-bottom: 24rpx;
    
    .block-label {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      color: #1A1A1A;
      margin-bottom: 8rpx;
    }
    
    .block-text {
      font-size: 28rpx;
      color: #555555;
      line-height: 1.6;
    }
    
    .list-item {
      display: flex;
      margin-bottom: 8rpx;
      .dot {
        font-weight: bold;
        margin-right: 12rpx;
        color: #1A1A1A;
      }
      .list-text {
        font-size: 28rpx;
        color: #555555;
        line-height: 1.6;
      }
    }
  }
}

/* 办公地址区 - 动态地图 */
.address-section {
  border-top: 10rpx solid #F8F9FB;
  .map-wrapper {
    position: relative;
    width: 100%;
    height: 360rpx;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.06);
    
    .map-view {
      width: 100%;
      height: 100%;
    }
  }
}

/* 公司概况区 */
.company-section {
  border-top: 10rpx solid #F8F9FB;
  .company-header {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    .company-logo {
      width: 80rpx;
      height: 80rpx;
      border-radius: 12rpx;
      background: #f0f0f0;
      margin-right: 20rpx;
    }
    .company-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #1A1A1A;
    }
  }
  .company-desc {
    font-size: 28rpx;
    color: #666666;
    line-height: 1.6;
  }
}

.end-tip {
  padding: 60rpx 0;
  text-align: center;
  text {
    font-size: 24rpx;
    color: #CCCCCC;
  }
}

.safe-bottom-holder {
  height: 140rpx;
}

/* 底部栏 */
.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #FFFFFF;
  display: flex;
  align-items: center;
  padding: 0 40rpx;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);
  z-index: 999;

  .collect-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 80rpx;
    margin-right: 40rpx;
    background: transparent; /* 强制背景透明 */
    
    .star-icon {
      width: 44rpx;
      height: 44rpx;
      margin-bottom: 4rpx;
      background: transparent;
      display: block;
    }
    .collect-text {
      font-size: 20rpx;
      color: #999999;
    }
  }
  
  .consult-btn {
    flex: 1;
    background-color: #FFB700;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    
    text {
      color: #FFFFFF;
      font-size: 32rpx;
      font-weight: bold;
    }

    &.initial, &.paid {
        background-color: #FFB700;
        box-shadow: 0 8rpx 16rpx rgba(255, 183, 0, 0.2);
    }

    &.assessed {
        background-color: #1F6CFF; // 测评通过后变为蓝色，投递简历
        box-shadow: 0 8rpx 16rpx rgba(31, 108, 255, 0.2);
    }

    &.added {
        background-color: #E0E0E0 !important; // 已投递后禁用灰色
        box-shadow: none !important;
        pointer-events: none;
        text {
            color: #999 !important;
        }
    }

    &:active {
      opacity: 0.9;
    }
  }
}
</style>
