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

    <!-- 课程分类标签区域 -->
    <view class="classify-first-level">
      <view 
        class="item" 
        v-for="(item, index) in firstLevelCategories" 
        :class="{ active: selectedFirstLevel === item }"
        :key="index" 
        @click="handleFirstLevelClick(item)"
      >{{ item }}</view>
    </view>
    <!-- 医学 -->
    <Skeleton
      v-if="selectedFirstLevel === '医学'"
      ref="medicineMenuSkeletonRef"
      theme="menu"
      :request="getMedicineMenus"
      @success="getMedicineMenusSuccess"
    >
      <template #content>
        <view v-if="selectedFirstLevel === '医学'" 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?.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>
      </template>
    </Skeleton>
    <!-- 心理学和国学 -->
    <Skeleton
      v-if="selectedFirstLevel === '心理学' || selectedFirstLevel === '国学'"
      ref="menuSkeletonRef"
      theme="menu"
      :request="getMenus"
    >
      <template #content="{ data }">
        <view
          v-if="data.labels.length > 0"
          :class="[
            {'sociology_cate_box': selectedFirstLevel === '国学'},
            {'soul_cate_box': selectedFirstLevel === '心理学'}
          ]"
        >
          <view
            class="cate_item_box"
            v-for="item in data.labels"
            @click="curseClickJump(item)"
          >
            <view class="cate_item_border">
              <image
                :src="item.icon"
                mode="aspectFill"
                style="width: 49rpx; height: 49rpx"
              ></image>
            </view>
            <view class="cate_item_name">{{ item.title }}</view>
          </view>
        </view>
      </template>
    </Skeleton>

    <!-- 观看记录区域 -->
    <view class="learnBox" v-if="learnList.length > 0">
      <view class="titleBox flexbox">
        <image src="../../static/course/learing.png" mode="aspectFit"></image>
        <text>{{ $t('courseHome.watchHistory') }}</text>
      </view>
      <view class="learn flexbox">
        <view
          class="item"
          v-for="(item, index) in learnList"
          :key="item.id"
          @click="onPageJump('/pages/course/details/course', item.id, item.title)"
        >
          <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">
      <view class="titleBox flexbox">
        <image src="../../static/course/try_listen.png" mode="aspectFit"></image>
        <text>{{ $t('courseHome.tryListen') }}</text>
      </view>
      <Skeleton
        theme="image-card"
        class=""
        :size="Array(2).fill({ width: '48%', height: '260rpx' })"
        :count="3"
        :request="getTryListenList"
      >
        <template #content="{ data }">
          <view v-if="data.courseList.records.length > 0" class="learn flexbox shiting">
            <view
              class="item"
              v-for="(item, index) in data.courseList.records"
              :key="item.id"
              @click="onPageJump('/pages/course/details/course', 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('courseHome.buy') }}</span>
                </view>
              </view>
            </view>
          </view>
          <view class="moreBox shiting">
            <text @click="onPageJump('/pages/course/list/tryListen', 1, $t('courseHome.tryListen'))">{{ $t('courseHome.moreTryListen') }}</text>
          </view>
        </template>
      </Skeleton>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow, onHide, onPullDownRefresh, onPageScroll } from '@dcloudio/uni-app'
import { courseApi } from '@/api/modules/course'
import { courseSubjectClassificationApi } from '@/api/modules/cousre_subject_classification'
import { commonApi } from '@/api/modules/common'
import { getNotchHeight } from '@/utils/system'
// import { onPageJump } from '@/utils'
import type { ICategory, ICourse, INews } from '@/types/course'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 系统信息
const scrollTop = ref<number>(0)            // 滚动位置

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

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

// 学科数据
const firstLevelCategories = ref<string[]>(['医学', '心理学', '国学'])
const selectedFirstLevel = ref('医学') // 当前选中的一级分类索引

/**
 * 医学
 * 获取课程分类数据
 */
const medicineMenuSkeletonRef = ref()
const getMedicineMenus = () => {
  sbuMedicalTagsList.value = []
  return courseSubjectClassificationApi.getCourseMedicalTree()
}
const getMedicineMenusSuccess = (res: any) => {
  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 {
      curseTagList.value = []
    }
  }
}
/**
 * 医学
 * 一级分类点击处理
 */
const curseClick = (item: ICategory, 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 {
    // 终极分类，直接跳转
    curseClickJump(item)
  }
}

/**
 * 菜单
 * 获取课程分类数据
 */
const menuSkeletonRef = ref()
const getMenus = () => {
  switch (selectedFirstLevel.value) {
    // case '医学':
    //   return getMedicalTags()
    case '心理学':
      return courseSubjectClassificationApi.getCourseSoulTree()
    case '国学':
      return courseSubjectClassificationApi.getCourseSociologyTree()
  }
}

/**
 * 学科点击处理
 */
const handleFirstLevelClick = (item: string) => {
	getPrompt()
	if(!uni.getStorageSync('token')) return
	selectedFirstLevel.value = item
  if (item === '医学') {
    medicineMenuSkeletonRef.value.reload()
  } else {
    menuSkeletonRef.value?.reload()
  }
  
	// switch (item) {
	//   case '医学':
	//     getMedicalTags()
	//     break
	//   case '心理学':
	//     getSoulCateList()
	//     break
	//   case '国学':
	//     getSociologyCateList()
	//     break
	// }
  
}

/**
 * 终极分类点击处理
 */
const curseClickJump = (item: ICategory) => {
	getPrompt()
	if(!uni.getStorageSync('token')) return
	uni.navigateTo({
		url: `/pages/course/list/category?id=${item.id}&title=${item.title}&pid=${item.pid}&subject=${selectedFirstLevel.value}`
	})
}

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


// 观看记录
const learnList = ref<ICourse[]>([]) // 观看记录列表
/**
 * 获取观看记录
 */
const getLearnCourse = async () => {
  const res = await courseApi.getUserLateCourseList()
  if (res && res.code === 0) {
    if (res.page && res.page.length > 0) {
      learnList.value = res.page
    } else {
      learnList.value = []
    }
  }
}

// 新闻播报
const newsList = ref<INews[]>([]) // 新闻列表
/**
 * 获取新闻列表
 */
const getNewsList = async () => {
  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 = []
    }
  }
}
/**
 * 新闻点击处理
 */
const newsClick = (item: INews) => {
	getPrompt()
	if(!uni.getStorageSync('token')) return
	uni.navigateTo({
	  url: `/pages/news/details?newsId=${item.id}&url=${item.url}&type=${item.type}`
	})
  
}

// 精彩试听
/**
 * 获取试听课程列表
 */
const getTryListenList = () => courseApi.getMarketCourseList({ page: 1, limit: 6, id: 1 })

/**
 * 登录提示语
 */
 const getPrompt = () => {
	 console.log(userStore.token);
	 if(!uni.getStorageSync('token')) {
		 uni.showModal({
		 	title: '提示',
		 	content: '请先登录后访问该页面',
		 	confirmText: '去登录',
		 	success: (res) => {
		 		console.log(res, 'res');
		 		if (res.confirm) uni.navigateTo({
		 			url: '/pages/login/login'
		 		});
		 	}
		 });
	 }
 }

/**
 * 统一请求所有数据
 */
const requestAll = async () => {
  if(uni.getStorageSync('token')){
		getLearnCourse()
	}
	getTryListenList()
	getNewsList()
}

/**
 * 页面挂载
 */
onMounted(() => {  
  // 重置分类索引
  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()
  if(uni.getStorageSync('token')){
		getLearnCourse()
	} 
})

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

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

/**
 * 页面滚动
 */
onPageScroll((e: any) => {
  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;

  :deep(.wd-search__block) {
    background-color: transparent !important;
    .wd-search__cover{
      background: rgba(255, 255, 255, 0.5) !important;
    }
    .wd-search__placeholder-txt, .wd-search__search-icon{
      color: #fff !important;
    }
  } 
}

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

.nomargin {
  margin: 0 !important;
}

// 分类标签样式
.newLeve2 {
  padding: 0 10rpx;
  border-top: 1px solid #eee;
  padding-top: 4rpx;
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(51, 97, 165, 0.08);
  margin-bottom: 10rpx;
}

// 一级分类标签样式
.classify-first-level {
  background: #FAFCFF;
  display: flex;
  justify-content: space-around;
  padding: 16rpx 20rpx;
  position: relative;
  
  .item {
    position: relative;
    padding: 20rpx 40rpx;
    font-size: 32rpx;
    color: #333;
    background-color: rgba(255, 255, 255, 0.6);
    border: 1px solid rgba(51, 97, 165, 0.2);
    border-radius: 50rpx;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4rpx 15rpx rgba(51, 97, 165, 0.1);
    backdrop-filter: blur(8px);
    font-weight: 500;
    overflow: hidden;
    z-index: 1;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.4), transparent);
      opacity: 0;
      transition: opacity 0.3s ease;
      z-index: -1;
    }
    
    /* 选中状态样式 */
    &.active {
      background: linear-gradient(135deg, #3361a5, #2952a3);
      border-color: #2952a3;
      box-shadow: 0 6rpx 20rpx rgba(41, 82, 163, 0.35);
      color: #ffffff;
      font-weight: 600;
      
      &::before {
        opacity: 0.3;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.6), rgba(255, 255, 255, 0.1));
      }
    }
    
    /* 点击效果 */
    &:active {
      transform: scale(0.95);
      box-shadow: 0 2rpx 10rpx rgba(51, 97, 165, 0.2);
      
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 10rpx;
        height: 10rpx;
        background-color: rgba(51, 97, 165, 0.6);
        border-radius: 50%;
        transform: translate(-50%, -50%) scale(20);
        opacity: 0;
        animation: ripple 0.6s ease-out;
      }
    }
    
    /* 悬停效果（在支持的设备上） */
    @media (hover: hover) {
      &:hover:not(.active) {
        background-color: rgba(227, 242, 253, 0.8);
        border-color: rgba(51, 97, 165, 0.4);
        transform: translateY(-4rpx);
        box-shadow: 0 8rpx 20rpx rgba(51, 97, 165, 0.15);
        
        &::before {
          opacity: 0.7;
        }
      }
    }
  }
}

.soul_cate_box {
  background: #7dc1f0;
  box-shadow: 0rpx 0rpx 6rpx 0rpx #f9f6ea;
  border-radius: 10rpx;
  margin: 0 10rpx;
  
  display: flex;
  align-items: center;
  justify-content: space-around;
  .cate_item_box {
    width: 20%;
    padding: 40rpx 0 30rpx;
    text-align: center;

    .cate_item_border {
      width: 60rpx;
      height: 60rpx;
      background-size: 100% 100%;
      background-image: url("@/static/icon/cate_bg.png");
      border-radius: 4rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto;

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

    .cate_item_name {
      margin-top: 15rpx;
      font-size: 24rpx;
      line-height: 34rpx;
      text-align: center;
      color: #fff;
      font-weight: bold;
    }

    .child-menu {
      display: none;
      background-color: #000;
      box-shadow: 0 4rpx 12rpx rgba(51, 97, 165, 0.08);
      border-radius: 0 0 20rpx 20rpx;
      padding: 10rpx 0;
    }
  }
}

.sociology_cate_box {
  width: 100%;
  height: auto;
  background: #3ab3ae;
  background-repeat: no-repeat;
  display: flex;
  flex-wrap: wrap;

  background-size: 100% 100%;
  box-shadow: 0rpx 0rpx 6rpx 0rpx #f9f6ea;
  border-radius: 7rpx;
  padding: 10rpx 10rpx 0;
  box-sizing: border-box;

  .cate_item_box {
    width: 25%;
    height: 100%;
    padding: 10rpx 0 10rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;

    flex-direction: column;

    .cate_item_border {
      width: 65rpx;
      height: 78rpx;
      background-size: 100% 100%;
      background-image: url("@/static/icon/cate_bg.png");
      border-radius: 4rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        // height: 56rpx;
      }
    }

    .cate_item_name {
      margin-top: 10rpx;
      font-family: PangMenZhengDaoBiaoTiTiMianFeiBan;

      font-weight: normal;
      font-size: 36rpx;
      color: #000000;
      // line-height: 46rpx;
      text-align: center;
      color: #fff;
    }
  }
}

/* 点击涟漪动画 */
@keyframes ripple {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 0.6;
  }
  100% {
    transform: translate(-50%, -50%) scale(20);
    opacity: 0;
  }
}

.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;
  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;
    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;
  margin-bottom: 20rpx;

  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>
