<template>
  <view class="container">
    <scroll-view class="scroll-body" scroll-y :show-scrollbar="false" :enhanced="true">
      <!-- 视频/直播封面区域 -->
      <view v-if="pageType === 'video' || pageType === 'live'" class="media-banner">
        <!-- 视频播放器 -->
        <video 
          v-if="isPlaying && mediaInfo.videoUrl"
          id="myVideo"
          class="video-player"
          :src="mediaInfo.videoUrl"
          autoplay
          controls
          @fullscreenchange="onFullscreenChange"
        ></video>
        
        <!-- 封面展示 -->
        <template v-else>
          <image :src="trainingInfo.cover || '/static/images/assess_cover.svg'" class="banner-img" mode="aspectFill"></image>
          <!-- 中央播放按钮 -->
          <view v-if="pageType === 'video'" class="play-btn-wrap" @click="playVideo">
            <view class="play-circle">
              <view class="play-triangle"></view>
            </view>
          </view>
          
          <!-- 底部信息栏 -->
          <view class="banner-info-bar">
            <view class="b-left">
               <view class="play-mini-triangle"></view>
               <text>{{ mediaInfo.views || '95万' }}</text>
            </view>
            <view class="b-right">
               <template v-if="pageType === 'video'">
                 <image src="/static/icons/time.svg" class="b-icon" style="filter: brightness(0) invert(1);"></image>
                 <text>{{ mediaInfo.duration || '10:28' }}</text>
               </template>
               <template v-else>
                 <image src="/static/icons/user.svg" class="b-icon" style="filter: brightness(0) invert(1);"></image>
                 <text>{{ mediaInfo.spectators || '1234567890' }}</text>
               </template>
            </view>
          </view>
        </template>
      </view>

      <view class="content">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 标题区域 -->
        <view v-if="!loading" class="header-section">
          <text :class="['title', (pageType === 'video' || pageType === 'live') ? 'video-title' : '']">{{ trainingInfo.title || '培训详情' }}</text>
          
          <view v-if="pageType === 'offline'" class="info-list">
            <view class="info-item" v-if="trainingInfo.location">
              <image src="/static/icons/location.svg" class="i-icon"></image>
              <text class="i-text">{{ trainingInfo.location }}</text>
            </view>
            <view class="info-item" v-if="trainingInfo.organizer">
              <image src="/static/icons/user.svg" class="i-icon"></image>
              <text class="i-text">主办单位：{{ trainingInfo.organizer }}</text>
            </view>
            <view class="info-item" v-if="trainingInfo.trainingTime">
              <image src="/static/icons/time.svg" class="i-icon"></image>
              <text class="i-text">培训时间：{{ trainingInfo.trainingTime }}</text>
            </view>
            <view class="info-item" v-if="trainingInfo.deadline">
              <image src="/static/icons/time.svg" class="i-icon"></image>
              <text class="i-text">截止时间：{{ trainingInfo.deadline }}</text>
              <text class="ending-tag" v-if="trainingInfo.isEnding">即将截止</text>
            </view>
          </view>

          <view v-else class="lecturer-info">
             <text class="l-name">讲师：{{ trainingInfo.lecturer || '待定' }}</text>
          </view>
        </view>

        <view class="divider"></view>

        <!-- 详情区域 -->
        <view v-if="!loading" class="detail-section">
          <text class="section-title">培训详情</text>
          <view class="tag-row" v-if="trainingInfo.tags && trainingInfo.tags.length > 0">
            <text class="t-tag" v-for="(tag, idx) in trainingInfo.tags" :key="idx">{{ tag }}</text>
          </view>

          <view class="rich-content">
            <view class="para-item" v-if="trainingInfo.description">
              <text class="p-label">培训描述：</text>
              <text class="p-text">{{ trainingInfo.description }}</text>
            </view>
            <view class="para-item" v-if="trainingInfo.requirements">
              <text class="p-label">参与要求：</text>
              <text class="p-text">{{ trainingInfo.requirements }}</text>
            </view>
            <view class="para-item" v-if="trainingInfo.benefits">
              <text class="p-label">培训收益：</text>
              <text class="p-text">{{ trainingInfo.benefits }}</text>
            </view>
          </view>
        </view>

        <view v-if="pageType === 'offline'" class="divider"></view>

        <!-- 地址区域 (仅线下) -->
        <view v-if="pageType === 'offline'" class="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="end-of-page">
          <view class="line"></view>
          <text class="end-text">已到底啦~</text>
          <view class="line"></view>
        </view>

        <view class="bottom-placeholder"></view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 (视频类型不展示) -->
    <view v-if="pageType !== 'video'" class="bottom-bar">
      <!-- 线下培训状态 -->
      <template v-if="pageType === 'offline'">
        <button v-if="regStatus === 'consult'" class="action-btn primary" @click="handleConsult">咨询</button>
        <button v-if="regStatus === 'enrolled'" class="action-btn disabled">已报名</button>
        <button v-if="regStatus === 'finished'" class="action-btn disabled">培训结束</button>
      </template>

      <!-- 直播培训状态 -->
      <template v-else-if="pageType === 'live'">
        <button v-if="liveStatus === 'streaming' || liveStatus === 'upcoming'" class="action-btn primary" @click="watchLive">进入直播间</button>
        <button v-else-if="liveStatus === 'not-started'" class="action-btn disabled">直播还未开始</button>
        <button v-else-if="liveStatus === 'finished'" class="action-btn primary" @click="watchReplay">观看回放</button>
        <button v-else class="action-btn primary" @click="watchLive">进入直播间</button>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { createOrGetSession } from '../../api/message.js';
import { getTrainingDetail } from '../../api/assessment.js';

const pageType = ref('offline'); // offline, video, live
const regStatus = ref('consult'); 
const liveStatus = ref(''); 
const mediaInfo = ref({});
const isPlaying = ref(false);
const loading = ref(true);
const trainingId = ref(null);

const trainingInfo = ref({
  title: '',
  location: '',
  organizer: '',
  trainingTime: '',
  deadline: '',
  isEnding: false,
  tags: [],
  description: '',
  requirements: '',
  benefits: ''
});

// 地图相关数据
const latitude = ref(31.22863);
const longitude = ref(121.45039);
const markers = ref([{
  id: 1,
  latitude: 31.22863,
  longitude: 121.45039,
  title: 'SOHO东海广场',
  iconPath: '/static/icons/location.svg',
  width: 32,
  height: 32,
  callout: {
    content: '上海静安区SOHO东海广场1209',
    color: '#333333', fontSize: 12, borderRadius: 8, padding: 8, bgColor: '#ffffff', display: 'ALWAYS'
  }
}]);

onLoad((options) => {
  if (options.id) {
    trainingId.value = options.id;
    loadTrainingDetail(options.id);
  }
  
  if (options.type) pageType.value = options.type;
  if (options.status) liveStatus.value = options.status;
  
  // 设置页面标题
  if (pageType.value === 'video') {
    uni.setNavigationBarTitle({ title: '视频培训详情' });
  } else if (pageType.value === 'live') {
    uni.setNavigationBarTitle({ title: '直播培训详情' });
  } else {
    uni.setNavigationBarTitle({ title: '培训详情' });
  }
  
  mediaInfo.value = {
    views: options.views,
    duration: options.duration,
    spectators: options.spectators
  };

  if (options.regSuccess) regStatus.value = 'enrolled';
  if (options.isFinished) regStatus.value = 'finished';
});

// 加载培训详情数据
const loadTrainingDetail = async (id) => {
  try {
    loading.value = true;
    const res = await getTrainingDetail(id);
    if (res.code === 200 && res.data) {
      const data = res.data;
      trainingInfo.value = {
        title: data.trainingName || data.title || '培训详情',
        location: data.location || '线上培训',
        organizer: data.organizer || data.organizerName || '平台推荐',
        trainingTime: formatTrainingTime(data.startTime, data.endTime),
        deadline: formatDeadline(data.deadline || data.registrationDeadline),
        isEnding: checkIsEnding(data.deadline || data.registrationDeadline),
        tags: data.tags ? data.tags.split(',').filter(tag => tag.trim()) : [],
        description: data.description || data.remark || '',
        requirements: data.requirements || '',
        benefits: data.benefits || '',
        price: data.price || '0.00',
        cover: data.coverImage || '/static/images/assess_cover.svg'
      };
      
      // 处理媒体信息
      if (data.videoUrl) {
        mediaInfo.value.videoUrl = data.videoUrl;
      }
      if (data.views) {
        mediaInfo.value.views = data.views;
      }
      if (data.duration) {
        mediaInfo.value.duration = data.duration;
      }
    } else {
      uni.showToast({ title: '获取培训详情失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取培训详情失败:', err);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 格式化培训时间
const formatTrainingTime = (startTime, endTime) => {
  if (!startTime) return '';
  
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  if (endTime && startTime !== endTime) {
    return `${formatDate(startTime)} 至 ${formatDate(endTime)}`;
  }
  return formatDate(startTime);
};

// 格式化截止时间
const formatDeadline = (deadline) => {
  if (!deadline) return '';
  
  const date = new Date(deadline);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 检查是否即将截止
const checkIsEnding = (deadline) => {
  if (!deadline) return false;
  
  const now = new Date();
  const deadlineDate = new Date(deadline);
  const timeDiff = deadlineDate.getTime() - now.getTime();
  const daysDiff = timeDiff / (1000 * 3600 * 24);
  
  return daysDiff > 0 && daysDiff <= 3; // 3天内即将截止
};

const playVideo = () => {
  isPlaying.value = true;
  // 延迟确保 DOM 渲染完成
  setTimeout(() => {
    const videoContext = uni.createVideoContext('myVideo');
    videoContext.play();
    // 显式触发全屏
    videoContext.requestFullScreen({
      direction: 90 // 横屏全屏
    });
  }, 300);
};

const onFullscreenChange = (e) => {
  // 全屏状态改变时的回调
  if (!e.detail.fullScreen) {
    // 退出全屏的处理
  }
};

const handleConsult = async () => {
    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: 'training_' + (trainingData.value?.id || trainingId.value)
        });
        uni.hideLoading();
        if (res.data) {
            const session = res.data;
            const title = encodeURIComponent(trainingInfo.value.title || '');
            const cover = encodeURIComponent(trainingInfo.value.cover || '');
            const price = trainingInfo.value.price || '0.00';
            uni.navigateTo({
                url: `/pages/chat/chat?sessionId=${session.sessionId}&sessionNo=${session.sessionNo || ''}&fromUserId=${userId || ''}&userName=${encodeURIComponent(userName)}&type=training&title=${title}&cover=${cover}&trainingId=${trainingId.value || ''}&price=${price}`
            });
        } else {
            uni.showToast({ title: '创建会话失败', icon: 'none' });
        }
    } catch (err) {
        uni.hideLoading();
        console.error('创建会话失败:', err);
        uni.showToast({ title: '连接失败，请重试', icon: 'none' });
    }
};

const watchLive = () => uni.showToast({ title: '正在进入直播间...', icon: 'loading' });
const subscribeLive = () => {
    uni.showToast({ title: '预约成功', icon: 'success' });
    liveStatus.value = 'subscribed'; 
};
const watchReplay = () => {
  pageType.value = 'video'; // 切换为视频模式播放回播
  playVideo();
};

</script>

<style lang="scss" scoped>
.container { width: 100%; height: 100vh; background: #FFF; display: flex; flex-direction: column; }
.scroll-body { flex: 1; height: 0; }

/* 视频/直播 Banner */
.media-banner {
  width: 100%; height: 420rpx; position: relative; background: #000;
  .banner-img { width: 100%; height: 100%; }
  .video-player { width: 100%; height: 100%; }
  
  .play-btn-wrap {
    position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
    .play-circle {
      width: 110rpx; height: 110rpx; background: rgba(0,0,0,0.4); border: 4rpx solid #FFF; border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      .play-triangle {
        width: 0; height: 0; 
        border-left: 36rpx solid #FFF; border-top: 24rpx solid transparent; border-bottom: 24rpx solid transparent;
        margin-left: 10rpx;
      }
    }
  }
  
  .banner-info-bar {
    position: absolute; left: 0; right: 0; bottom: 0; height: 80rpx;
    background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 100%);
    display: flex; justify-content: space-between; align-items: center; padding: 0 40rpx;
    color: #FFF; font-size: 26rpx;
    .b-left, .b-right { display: flex; align-items: center; gap: 12rpx; }
    .b-icon { width: 28rpx; height: 28rpx; }
    
    .play-mini-triangle {
      width: 0; height: 0; 
      border-left: 12rpx solid #FFF; border-top: 8rpx solid transparent; border-bottom: 8rpx solid transparent;
    }
  }
}

.content { padding: 30rpx 40rpx; }

.loading-state {
  display: flex; justify-content: center; align-items: center; 
  padding: 80rpx 0;
  .loading-text { font-size: 28rpx; color: #999; }
}

.header-section {
  .title { font-size: 48rpx; font-weight: bold; color: #1A1A1A; display: block; margin-bottom: 30rpx; }
  .video-title { font-size: 38rpx; } /* 视频标题调小 */
  
  .info-list {
    display: flex; flex-direction: column; gap: 20rpx;
    .info-item {
      display: flex; align-items: center;
      .i-icon { width: 32rpx; height: 32rpx; margin-right: 20rpx; opacity: 0.5; }
      .i-text { font-size: 28rpx; color: #666; flex: 1; }
      .ending-tag { font-size: 24rpx; color: #FF4D4F; margin-left: 20rpx; font-weight: bold; }
    }
  }
  .lecturer-info {
    display: flex; align-items: center; font-size: 30rpx; color: #888;
    .l-name { font-weight: 500; }
  }
}

.divider { height: 1rpx; background: #F0F0F0; margin: 40rpx 0; }
.section-title { font-size: 34rpx; font-weight: bold; color: #1A1A1A; margin-bottom: 30rpx; display: block; }

.detail-section {
  .tag-row {
    display: flex; flex-wrap: wrap; gap: 16rpx; margin-bottom: 40rpx;
    .t-tag { font-size: 24rpx; color: #666; background: #F5F7FA; padding: 10rpx 24rpx; border-radius: 10rpx; }
  }
  .rich-content {
    .para-item {
      margin-bottom: 30rpx;
      .p-label { font-size: 30rpx; font-weight: bold; color: #1A1A1A; display: block; margin-bottom: 12rpx; }
      .p-text { font-size: 28rpx; color: #666; line-height: 1.6; display: block; white-space: pre-wrap; }
    }
  }
}

.address-section {
  .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%; }
  }
}

.end-of-page {
  display: flex; align-items: center; justify-content: center; padding: 60rpx 0 20rpx;
  .line { width: 60rpx; height: 1rpx; background: #EEE; margin: 0 20rpx; }
  .end-text { font-size: 24rpx; color: #BBB; }
}

.bottom-placeholder { height: 160rpx; }

.bottom-bar {
  position: fixed; left: 0; right: 0; bottom: 0; background: #FFF; padding: 20rpx 40rpx; padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.05); z-index: 1000;
  .action-btn {
    width: 100%; height: 90rpx; line-height: 90rpx; border-radius: 45rpx; font-size: 32rpx; font-weight: bold;
    &::after { border: none; }
    &.primary { background: #1F6CFF; color: #FFF; box-shadow: 0 6rpx 20rpx rgba(31, 108, 255, 0.3); }
    &.disabled { background: #D6E8FF; color: #1F6CFF; }
  }
}
</style>
