<template>
  <div class="kechengmulu">
    <div class="gap10">
      <div class="line_vertical"></div>
      <div class="font_size18 bold">{{$t('common.kechengmulu')}} (1/{{list.length}})</div>
    </div>
    <div class="flex-center-between font_size16 gray list_item" 
    @click="handleCheck(item)"
    :class="{'active': selectedItem.chapterId === item.chapterId}"
    v-for="(item, index) in list" :key="index">
      <div class="gap10">
        <div>{{item.chapterOrderName}}</div>
        <div class="gap5">
          <img :src="muluIcon" alt="" style="width:20px;height:20px" v-show="selectedItem.chapterId === item.chapterId">
          <span>{{item.chapterName}}</span>
        </div>
      </div>
      <div>{{item.chapterTimeConvert}}</div>
    </div>
    <div v-if="list.length === 0" >
      <el-empty :image-size="200" />
    </div>
  </div>
</template>
<script setup>
import muluIcon from '@/assets/imgs/mulu.png'
import { getChaptersList } from '@/api/course.js'
import { ref, onMounted, watch, onActivated } from 'vue'
import { useRouter } from 'vue-router'
const emit = defineEmits(['purchaseFn']);
const router = useRouter();
const props = defineProps({
  info: {
    type: Object,
    default: () => ({})
  },
  formPage: {
    type: String,
    default: ''
  },
  chapterId: {
    type: String,
    default: ''
  }
})
const selectedItem = ref({});//选中的章节


//监听props.info.courseId变化
watch(() => props.info.courseId, (newVal, oldVal) => {
  if(newVal !== oldVal){
    getChaptersListFn();
  }
})

onActivated(() => {
 if(props.info.courseId){
    getChaptersListFn();
  }
})

const list = ref([]);

const getChaptersListFn = () => {
   getChaptersList({id: props.info.courseId}).then(res => {
    if(res.code === 200){
      list.value = res.rows || [];
      if(list.value.length > 0){
        if(props.chapterId){
          selectedItem.value = list.value.find(item => item.chapterId == props.chapterId) || {};
        }else{
          selectedItem.value = list.value[0];
        }
        purchaseFn(selectedItem.value.chapterId, selectedItem.value);
      }
    }
  })
};


const handleCheck = (item) => {
  selectedItem.value = item;
  if(props.formPage === 'LearningSystemDetail'){
    //增加参数名称
    router.push({
      path: `/learning-system/detail/${item.courseId}/course/${item.courseId}`,
      query: {
        courseId: item.courseId,
        chapterId: item.chapterId,
        metaTitle: '课程详情'
      }
    })
  }else{
    purchaseFn(selectedItem.value.chapterId, selectedItem.value);
  }
}

const purchaseFn = (chapterId, chapterInfo={}) => {
  emit('purchaseFn', chapterId, chapterInfo);
}



</script>
<style scoped lang="scss">
  .kechengmulu{
    .list_item{
      cursor: pointer;
      padding: 15px 0;
      border-bottom: 1px solid #DCDFE6;
      &.active{
        color: $primary-color;
        font-weight: 600;
      }
    }

  }

</style>
