<template>
  <view class="course-home-page">
    <!-- 头部区域 -->
    <view class="home-bg" :style="{ paddingTop: notchHeight + 'px' }">
      <wd-search
        hide-cancel
        light
        clearable
        class="search-bar"
        :placeholder="$t('course.searchPlaceholder')"
        @search="handleSearch"
      />
      <view class="icon-hua">
        <image
          src="../../static/course/homeLogo.png"
          mode="aspectFit"
          class="icon-hua-img"
        />
      </view>
    </view>

    <!-- 课程分类标签区域 -->
    <!-- <view class="newLeve2">
      <view class="home_nar nomargin" style="padding: 0; background-color: #fff">
        <view class="flexbox">
          <view
            :class="['hn_cl_tit', currentIndex == index ? 'active' : '']"
            @click="curseClick(item, index)"
            v-for="(item, index) in curseTagList"
            :key="item.id"
          >
            <image :src="item.icon" mode="aspectFit"></image>
            <text>{{ item.title }}</text>
          </view>
        </view>
      </view>
      <view
        class="fourBox"
        style="padding: 0; padding-bottom: 8rpx"
        v-if="sbuMedicalTagsList && sbuMedicalTagsList.length > 0"
      >
        <view
          class="childrenBox fourIcon flexbox"
          style="justify-content: space-around"
        >
          <view
            class="item flexbox"
            @click="curseClickJump(item)"
            v-for="(item, index) in sbuMedicalTagsList"
            :key="item.id"
          >
            <image
              :src="item.icon"
              mode="aspectFit"
              v-if="item.icon != '' && item.icon != null"
            ></image>
            <text>{{ item.title }}</text>
          </view>
        </view>
      </view>
    </view> -->

    <!-- 观看记录区域 -->
    <view class="learnBox" v-if="learnList.length > 0">
      <view class="titleBox flexbox">
        <image src="../../static/course/learing.png" mode="aspectFit"></image>
        <text>{{ $t('course.watchHistory') }}</text>
      </view>
      <view class="learn flexbox">
        <view
          class="item"
          v-for="(item, index) in learnList"
          :key="item.id"
          @click="onPageJump('/pages/course/courseDetail', item.id)"
        >
          <view class="img" style="overflow: hidden">
            <image
              v-if="item.image && item.image != ''"
              :src="item.image"
              mode="aspectFit"
            ></image>
            <image v-else src="../../static/course/nobg.jpg" mode="widthFix"></image>
          </view>
          <view class="txt555">
            {{ item.title }}
          </view>
        </view>
      </view>
    </view>

    <!-- 新闻播报区域 -->
    <view style="padding: 0 5px;" v-if="newsList.length > 0">
      <view class="newsBox flexbox">
        <view class="icon">
          <wd-icon name="sound" size="22px"></wd-icon>
        </view>
        <view class="newscoll">
          <swiper
            class="swiper"
            interval="5000"
            circular
            autoplay
            vertical
            :indicator-dots="false"
          >
            <swiper-item
              class="item"
              v-for="(item, index) in newsList"
              :key="item.id"
              @click="newsClick(item)"
            >
              <view class="swiper-item">{{ item.title }}</view>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </view>

    <!-- 精彩试听区域 -->
    <view class="learnBox" v-if="tryListenList.length > 0">
      <view class="titleBox flexbox">
        <image src="../../static/course/try_listen.png" mode="aspectFit"></image>
        <text>{{ $t('course.tryListen') }}</text>
      </view>
      <view class="learn flexbox shiting">
        <view
          class="item"
          v-for="(item, index) in tryListenList"
          :key="item.id"
          @click="onPageJump('/pages/course/courseDetail', item.id, item.title)"
        >
          <view class="imgcontainer">
            <image
              v-if="item.image == '' || !item.image"
              src="../../static/course/nobg.jpg"
              mode="aspectFit"
            >
            </image>
            <image v-else :src="item.image"></image>
          </view>
          <view class="buyItems flexbox">
            <view class="txt555">
              {{ item.title }}
            </view>
            <view class="buybtn">
              <span>{{ $t('course.buy') }}</span>
            </view>
          </view>
        </view>
      </view>
      <view class="moreBox shiting">
        <text @click="onPageJump('/pages/course/tryListen', 1, $t('course.tryListen'))"
          >{{ $t('course.moreTryListen') }}</text
        >
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow, onHide, onPullDownRefresh, onPageScroll, onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { courseApi } from '@/api/modules/course'
import { commonApi } from '@/api/modules/common'
import type { IMedicalTag, ICourse, INews } from '@/types/course'

const { t } = useI18n()

// 系统信息
const notchHeight = ref<number>(0)          // 刘海屏高度
const scrollTop = ref<number>(0)            // 滚动位置

// 分类相关
const curseTagList = ref<IMedicalTag[]>([])           // 一级分类标签列表
const sbuMedicalTagsList = ref<IMedicalTag[]>([])     // 二级分类标签列表
const currentIndex = ref<number>(0)                    // 当前选中的一级分类索引
const currentItem = ref<IMedicalTag | null>(null)     // 当前选中的一级分类项

// 观看记录
const learnList = ref<ICourse[]>([])                  // 观看记录列表

// 新闻播报
const newsList = ref<INews[]>([])                     // 新闻列表

// 精彩试听
const tryListenList = ref<ICourse[]>([])              // 试听课程列表

/**
 * 处理搜索点击
 */
const handleSearch = ({ value }: { value: string }) => {
  uni.navigateTo({
    url: `/pages/book/search?keyword=${value}`
  })
}

/**
 * 获取课程分类数据
 */
const getMedicalTags = async () => {
  try {
    const res = await courseApi.getCourseMedicalTree()
    if (res && res.code === 0) {
      if (res.labels && res.labels.length > 0) {
        curseTagList.value = res.labels
        // 根据 currentIndex 设置初始选中的分类
        if (res.labels[currentIndex.value]) {
          const selectedTag = res.labels[currentIndex.value]
          if (selectedTag.isLast === 0) {
            // 非终极分类，显示子分类
            if (selectedTag.children && selectedTag.children.length > 0) {
              sbuMedicalTagsList.value = selectedTag.children
            } else {
              sbuMedicalTagsList.value = []
            }
          }
        }
      } else {
        curseTagList.value = []
      }
    }
  } catch (error) {
    console.error('获取课程分类失败:', error)
  }
}

/**
 * 获取观看记录
 */
const getLearnCourse = async () => {
  try {
    const res = await courseApi.getUserLateCourseList()
    if (res && res.code === 0) {
      if (res.page && res.page.length > 0) {
        learnList.value = res.page
      } else {
        learnList.value = []
      }
    }
  } catch (error) {
    console.error('获取观看记录失败:', error)
  }
}

/**
 * 获取试听课程列表
 */
const getTryListenList = async () => {
  try {
    const res = await courseApi.getMarketCourseList(1, 6, 1)
    if (res && res.code === 0) {
      if (res.courseList && res.courseList.records && res.courseList.records.length > 0) {
        tryListenList.value = res.courseList.records
      } else {
        tryListenList.value = []
      }
    }
  } catch (error) {
    console.error('获取试听课程失败:', error)
  }
}

/**
 * 获取新闻列表
 */
const getNewsList = async () => {
  try {
    const res = await commonApi.getMessageList(0, 1, 0)
    if (res && res.code === 0) {
      if (res.messages && res.messages.length > 0) {
        newsList.value = res.messages
      } else {
        newsList.value = []
      }
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
  }
}

/**
 * 统一请求所有数据
 */
const requestAll = async () => {
  await getLearnCourse()
  await getMedicalTags()
  await getTryListenList()
  await getNewsList()
}

/**
 * 一级分类点击处理
 */
const curseClick = (item: IMedicalTag, index: number) => {
  currentItem.value = item
  currentIndex.value = index
  
  if (item.isLast === 0) {
    // 非终极分类，显示子分类
    if (item.children && item.children.length > 0) {
      sbuMedicalTagsList.value = item.children
    } else {
      sbuMedicalTagsList.value = []
    }
  } else {
    // 终极分类，直接跳转
    uni.navigateTo({
      url: `/pages/course/index?id=${item.id}&title=${item.title}&pid=${item.id}`
    })
  }
}

/**
 * 二级分类点击处理
 */
const curseClickJump = (item: IMedicalTag) => {
  uni.navigateTo({
    url: `/pages/course/index?id=${item.id}&title=${item.title}&pid=${item.pid}`
  })
}

/**
 * 新闻点击处理
 */
const newsClick = (item: INews) => {
  if (item.type === 1 && item.url) {
    uni.navigateTo({
      url: `/pages/news/newsForwebview?newsId=${item.id}&url=${item.url}&type=${item.type}`
    })
  } else {
    uni.navigateTo({
      url: `/pages/news/news?newsId=${item.id}&url=${item.url}&type=${item.type}`
    })
  }
}

/**
 * 页面跳转统一处理
 */
const onPageJump = (url: string, id?: number, title?: string) => {
  let targetUrl = url
  if (id !== undefined) {
    targetUrl += `?id=${id}`
    if (title) {
      targetUrl += `&title=${encodeURIComponent(title)}`
    }
  }
  uni.navigateTo({ url: targetUrl })
}

/**
 * 页面挂载
 */
onMounted(() => {
  // 获取系统信息，设置刘海屏高度
  const systemInfo = uni.getSystemInfoSync()
  notchHeight.value = systemInfo.safeArea?.top || 0
  
  // 重置分类索引
  currentIndex.value = 0
  
  // 请求所有数据
  requestAll()
})

/**
 * 页面显示
 */
onShow(() => {  
  // 检查是否有固定的分类选择状态
  const fixed = uni.getStorageSync('fixed')
  if (fixed && currentItem.value) {
    curseClick(currentItem.value, currentIndex.value)
  } else {
    currentIndex.value = 0
    currentItem.value = null
  }
  
  // 刷新数据
  requestAll()
})

/**
 * 页面隐藏
 */
onHide(() => {
  // 清除固定状态
  uni.removeStorageSync('fixed')
})

/**
 * 下拉刷新
 */
onPullDownRefresh(() => {
  requestAll().then(() => {
    uni.stopPullDownRefresh()
  })
})

/**
 * 页面滚动
 */
onPageScroll((e) => {
  scrollTop.value = e.scrollTop
})
</script>

<style lang="scss" scoped>
// SCSS 变量定义
$theme-color: #55aa7f;
$theme-color-light: #e4eefa;
$bg-color: #f7f7f7;
$card-bg: #ffffff;
$text-primary: #333333;
$text-secondary: #666666;
$text-placeholder: #999999;
$border-color: #eeeeee;

.course-home-page {
  min-height: 100vh;
  background-color: $bg-color;
  font-size: 28upx;
}

// 头部区域样式
.home-bg {
  background-image: url('@/static/course/home_bg.jpg');
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  padding: 30rpx;
  position: relative;

  .icon-hua {
    width: 100%;
    text-align: center;
    display: block;
    padding-top: 20rpx;

    .icon-hua-img {
      width: 100%;
      height: 160rpx;
    }
  }
}

.search-bar {
  background-color: transparent !important;
}

// 公共样式
.flexbox {
  display: flex;
}

.nomargin {
  margin: 0 !important;
}

// 分类标签样式
.newLeve2 {
  background-color: #fff;
  padding: 0 10rpx;
  border-top: 1px solid #eee;
  padding-top: 4rpx;
}

.home_nar {
  margin: 10px 0;
  justify-content: space-between;
  color: #333;
  margin-bottom: 0;
  padding: 0 5px;

  .hn_cl_tit {
    display: block;
    width: 100%;
    background-color: #fff;
    text-align: center;
    align-content: center;
    justify-content: center;
    margin-right: 8rpx;
    border-bottom: 1px solid #fff;

    image {
      width: 100rpx;
      height: 90rpx;
      display: block;
      margin: 0 auto;
      padding: 20rpx;
    }

    text {
      display: block;
      padding-bottom: 20rpx;
      text-align: center;
      margin-top: 4rpx;
      font-size: 28rpx;
      color: #00337f;
      font-weight: bold;
    }
  }

  .hn_cl_tit:last-child {
    margin-right: 0;
  }

  .hn_cl_tit.active {
    background-color: $theme-color-light;

    text {
      color: #3361a5;
    }
  }
}

.childrenBox {
  background-color: $theme-color-light !important;
  border-radius: 6rpx !important;
  box-shadow: 0px 0px 10px 0px rgba(167, 187, 228, 0.3);
  justify-content: center;
  box-shadow: none !important;

  .item {
    text {
      color: #3361a5;
    }
  }

  image {
    width: 80rpx;
    height: 80rpx;
  }
}

.fourIcon {
  justify-content: space-between;
  box-shadow: 0px 0px 10px 0px rgba(167, 187, 228, 1);
  text-align: center;
  height: 60px;
  background-color: #fff;
  border-radius: 10px;
  line-height: 60px;

  .item {
    align-items: center;
  }

  text {
    font-size: 28rpx;
    color: #76664d;
    padding-left: 6rpx;
  }

  image {
    width: 48rpx;
    height: 48rpx;
    margin: 0 auto;
  }
}

// 观看记录和试听样式
.learnBox {
  background-color: #fff;
  margin: 10px 5px 20px;
  border-radius: 20rpx;
  padding: 10px;
  box-shadow: 0px 0px 10px 0px rgba(167, 187, 228, 0.3);

  .img {
    width: 100%;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
  }

  .learn {
    justify-content: space-between;
    margin-top: 20rpx;
    flex-wrap: wrap;

    .item {
      width: 326rpx;
      overflow: hidden;
      margin-bottom: 20rpx;

      image {
        width: 100%;
        height: 220rpx;
      }

      .txt555 {
        height: 40rpx;
        line-height: 40rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 24rpx;
      }
    }
  }
}

.titleBox {
  align-items: center;

  image {
    width: 50rpx;
    height: 50rpx;
  }

  text {
    font-size: 30rpx;
    padding-left: 10rpx;
    align-items: center;
  }
}

.shiting {
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 40rpx;

  .buyItems {
    padding-top: 10rpx;
    align-items: center;

    .buybtn {
      display: block;
      width: 28%;
      padding: 0 4px;
      font-size: 24rpx;
      line-height: 40rpx;
      text-align: center;
      background-color: $theme-color;
      color: #fff;
      border-radius: 20rpx;
      height: 40rpx;
    }

    .txt555 {
      width: 70%;
      overflow: hidden;
    }
  }
}

.moreBox {
  margin-top: 10px;
  text-align: center;

  text {
    display: inline-block;
    border: 1px solid $theme-color;
    padding: 14rpx 0;
    width: 80%;
    border-radius: 60rpx;
    color: $theme-color;
  }
}

.imgcontainer {
  background-color: #f7f7f7;
}

// 新闻播报样式
.newsBox {
  justify-content: space-between;
  background-color: #fff;
  box-shadow: 0px 0px 10px 0px rgba(167, 187, 228, 0.3);
  margin-top: 10px;
  overflow: hidden;
  border-radius: 20rpx;
  padding: 10rpx;
  line-height: 40rpx;
  height: 60rpx;

  .icon {
    color: #00337f;
    margin-left: 10rpx;
  }

  .newscoll {
    overflow: hidden;
    width: calc(100% - 70rpx);
    height: 40rpx;
    .item {
      .swiper-item {
        font-size: 28rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
