<script setup lang="ts">
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import BookSelect from '@/components/book-select/index.vue'
import { subjectStore, userStore } from '@/stores'
import { isNotStudyMachine } from '@/utils'
import hud from '@/utils/hud'
import { book_select_practice, book_select_video } from '@/components/book-select'
import { cleanBooks } from '@/api/subject/config'
import subjectApi from '@/api/subject/subject'
import type { TextBook } from '@/api/subject/subject'
import { storeToRefs } from 'pinia'

const OSS_URL = import.meta.env.VITE_OSS_URL

const { userInfo } = storeToRefs(userStore())
const isWebOrSchool = computed(() => isNotStudyMachine || userInfo.value.isTaskStudent)
const route = useRoute()
const router = useRouter()

const subjectId = computed(() => route.query.id)
if (!route.query.id) {
  router.replace('/subject')
}

const { subject } = subjectStore()
const showArtifact = computed(() => {
  // 英语，直接显示
  if (subject.name === '英语') return true
  // 如果是浏览器 || 学校的学员，直接隐藏
  if (isWebOrSchool.value) return false
  // 显示
  return true
})
const nav = computed(() => [
  {
    title: '自由学',
    desc: '想学啥就学啥',
    path: `/subject/freeStudy/${subjectId.value}`,
    icon: `${OSS_URL}/urm/textbook_tool_ziyouxue.png`,
  },
  // 英语/语文 隐藏AI精准学
  // ['2', '4'].includes(subjectId.value as string)
  //   ? undefined
  //   : {
  //       title: 'AI精准学',
  //       desc: 'AI个性化精准出题',
  //       path: `/subject/aiStudy/${subjectId.value}`,
  //       icon: `${OSS_URL}/urm/textbook_tool_aijingzhunxue.png`,
  //     },
  {
    title: '错题本',
    desc: '失败是成功的爸爸',
    path: '/system/homeWork/wrongQuestion',
    isCheck: false,
    icon: `${OSS_URL}/urm/textbook_tool_cuotiben.png`,
  },
  // {
  //   title: '自由组卷',
  //   desc: '自由组合知识点出题',
  //   path: `/subject/groupPaper`,
  //   icon: `${OSS_URL}/urm/textbook_tool_ziyouzujuan.png`,
  // },
])

const textbookList = ref([] as TextBook[])

function go(path: string, isCheck = true) {
  if (isCheck && !textbookList.value.length) {
    showType.value = 0
    showTextbookDia.value = true
    return
  }
  if (path) {
    router.push(path)
    return
  }
}

const showType = ref(book_select_practice) // 0选择教材 1选择学习进度 2修改学习进度 3学习视频选择教材
const showTextbookDia = ref(false)
const textbookData = ref<anyObj>({})
function addTextbook() {
  showType.value = book_select_practice
  showTextbookDia.value = true
  textbookData.value = {}
}

const loading = ref(true)
async function init() {
  loading.value = true
  try {
    const res = await subjectApi.getUserTextBookList({
      size: -1,
      subjectId: subjectId.value as string,
    })
    cleanBooks(res.rows)
    textbookList.value = res.rows
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }
}

async function onRemove(data: anyObj) {
  await subjectApi.delUserTextBookToId(data.id)
  init()
}

// 查看详情
// function onSelect(data: anyObj) {
//   showType.value = 2
//   showTextbookDia.value = true
//   textbookData.value = data
// }

// 选择学习视频教材
function handleVideo() {
  showType.value = book_select_video
  showTextbookDia.value = true
  textbookData.value = {}
}

// 选择了教材
async function selectBook(book: TextBook) {
  if (showType.value === book_select_practice) {
    // 保存进度
    hud.load({
      option: '保存',
      task: async () => {
        await subjectApi.saveUserTextBook({
          subjectId: subjectId.value as string,
          textBookId: book.id,
          textBookName: book.displayName || book.shortName,
          gradeId: userInfo.value.learnGradeId,
        })
        showTextbookDia.value = false
        init()
      },
    })
  } else if (showType.value === book_select_video) {
    const { id, shortName } = book
    router.push(`/subject/studyVideo/${id}?textbookName=${shortName}`)
    showTextbookDia.value = false
  }
}

// onMounted(() => {
//     init();
// });

onActivated(() => {
  if (!route.query.id) {
    router.replace('/subject')
    return
  }
  init()
})

// 当学科只有1本教材时，点击自由学，直接进入教材章节视频/练习
onBeforeRouteLeave((to, _from, next) => {
  if (to.name === 'FreeHome' && textbookList.value.length === 1) {
    if (textbookList.value?.[0].id) {
      const book = textbookList.value[0]
      return next(
        `/subject/freeStudy/textbookDetail/${subjectId.value}/${book.textBookId}?id=${book.id}&textbookName=${book.clean.fullName}`,
      )
    } else {
      next()
    }
  }
  next()
})
</script>

<template>
  <div class="page">
    <!-- <div v-if="!textbookList.length && !loading" class="pop">
            <span>请选择学习目标范围内的所有学习教材吧~</span>
        </div> -->
    <BackBar :leftText="subject.name || '学科'"></BackBar>
    <div class="tool">
      <div class="tool-item" @click="handleVideo">
        <Icon name="textbook_learn_video" size="90" />
        <LineFont text="学习视频" borderColor="#3F31D9" size="24" border="4" />
      </div>

      <div v-if="showArtifact" class="tool-item" @click="go('/subject/learningArtifact', false)">
        <Icon name="textbook_learn_artifact" size="90" />
        <LineFont text="学习神器" borderColor="#3F31D9" size="24" border="4" />
      </div>
      <div
        class="tool-item"
        @click="go(`/studyAnalysis?subjectId=${subjectId}&subjectName=${subject.name}`, false)"
      >
        <Icon name="textbook_learn_analysis" size="90" />
        <LineFont text="学情分析" borderColor="#3F31D9" size="24" border="4" />
      </div>
    </div>
    <div class="main">
      <div class="left">
        <div v-if="loading" class="loading">
          <Empty type="loading" />
        </div>
        <book-shelf
          v-else
          :books="textbookList"
          add
          :onRemove="onRemove"
          :progress="false"
          remove
          :width="1100"
          @add="addTextbook"
        />
      </div>
      <div class="right">
        <div class="list">
          <template v-for="item in nav" :key="item?.title">
            <div v-if="item" class="item" @click="go(item.path, item.isCheck)">
              <div class="item-title">{{ item.title }}</div>
              <div class="item-desc">{{ item.desc }}</div>
              <img :src="item.icon" />
            </div>
          </template>
        </div>
      </div>
    </div>
    <book-select
      v-model="showTextbookDia"
      v-model:type="showType"
      :subjectId="subjectId"
      :locked-book-ids="textbookList.map((item: any) => item.textBookId)"
      @ok="selectBook"
    />
  </div>
</template>

<style lang="scss" scoped>
$book_shelf_h: 66.67vh;

.page {
  width: 100%;
  height: 100%;
  padding: $space-4_h $space-6;
  position: relative;
  @include main_bg;

  .tool {
    display: flex;
    gap: $space-6;
    position: absolute;
    top: $space-4_h;
    right: $space-8;
    &-item {
      width: 120px;
      height: 10vh;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      position: relative;
      cursor: pointer;
      .x-line-font {
        position: absolute;
        bottom: -0.67vh;
      }
    }
  }
  .main {
    height: calc(100% - 80px);
    display: flex;
    gap: $space-8;
    .loading {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .left {
      width: 1104px;
      margin-top: 0.67vh;

      .book-shelf {
        margin-top: 2.17vh;
        height: 84.67vh;
      }
    }
    .right {
      flex: 1;
      padding-top: 6.67vh;
      .list {
        .item {
          height: 18.67vh;
          border-radius: 3.33vh;
          border: 0.33vh solid #fff;
          margin-bottom: $space-3_h;
          padding: $space-4_h $space-5;
          background: $theme-color;
          position: relative;
          cursor: pointer;
          &-title {
            color: #fff;
            text-shadow: 0 0.33vh 0.17vh rgba(0, 0, 0, 0.25);
            font-family: $font-special;
            font-size: 4vh;
            line-height: 1.5em;
          }
          &-desc {
            color: #fff;
            text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
            font-size: $font-size-7;
            line-height: 1.5em;
          }
          img {
            position: absolute;
            top: 0;
            right: 16px;
            height: 16.67vh;
            width: 16.67vh;
          }

          &:nth-child(1) {
            background: linear-gradient(101.98deg, #bab3ff 16%, #9395f5 83.61%);
          }
          &:nth-child(2) {
            background: linear-gradient(101.98deg, #ffb3ff 16%, #db93f5 83.61%);
          }
          &:nth-child(3) {
            background: linear-gradient(101.98deg, #ffb3b4 16%, #f59395 83.61%);
          }
          &:nth-child(4) {
            background: linear-gradient(101.98deg, #ffd1b3 16%, #f5ad93 83.61%);
          }
        }
      }
    }
  }
}
</style>
