<template>
  <div class="home-container">
    <div class="box-1">
      <div class="inner-box left-box">
        <div class="box-icon" @click="goToManagementInterface">
          <div class="app-header">
            <img :src="LogoImage" alt="Logo" class="app-logo" />
            <el-icon class="left-icon"><HomeFilled /></el-icon>
            <span>{{ platformTitle }}</span>
          </div>
        </div>
        <div class="dropdown-box">
          <el-dropdown v-model="selectedGrade" @command="handleGradeSelect" @visible-change="handleVisibleChange" popper-class="no-arrow-dropdown">
            <el-button type="primary">
              {{ selectedGrade }}
              <el-icon class="el-icon--right" v-if="!dropdownVisible"><ArrowDownBold /></el-icon>
              <el-icon class="el-icon--right" v-else><ArrowUpBold /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu class="dropdown-menu">
                <el-dropdown-item
                  v-for="item in classData"
                  :key="item.id"
                  :command="item.ctType"
                  >{{ item.ctType }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="inner-box right-box">
        <div class="top-right-box">
          <el-button
            v-for="button in buttonConfigs"
            :key="button.name"
            round
            class="top-right-btn"
            :class="{ 'is-active': selectedButton === button.name }"
            @click="handleButtonClick(button)"
            >{{ button.name }}</el-button
          >
          <UserInfoPopover />
        </div>
      </div>
    </div>
    <div class="box-2">
      <div
        class="left-box-in-box2"
        @click="goToAIPoetryCourse"
        :style="{ backgroundImage: `url(${indexImages[0]})` }"
      >
        <span style="background-color: #77b7db78;
              margin: 20px;
              padding: 10px;
              border-radius: 27px;">
          AI诗词课
        </span>
      </div>
      <div
        class="center-box-in-box2"
        @click="goToAILab()"
        :style="{ backgroundImage: `url(${indexImages[1]})` }"
      >
        <span>AI实验室</span>
      </div>
      <div class="right-box-in-box2">
        <div
          class="top-sub-box"
          :style="{ backgroundImage: `url(${indexImages[2]})` }"
           @click="goToEvaluation"
        >
          <span>能力测评</span>
        </div>
        <div
          class="bottom-sub-box"
          :style="{ backgroundImage: `url(${indexImages[3]})` }"
          @click="goToPersonalized"
        >
          <span>评估报告</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ClassList } from '@/api/class.js'
import {ArrowUpBold, ArrowDownBold, HomeFilled} from '@element-plus/icons-vue'
import UserInfoPopover from '@/components/user/UserInfoPopover.vue'
import LogoImage from '@/assets/images/logo.png'

import poetryImg from '@/assets/aiPoetry/poetry.png'
import roomImg from '@/assets/images/room.png'
import testImg from '@/assets/images/test.png'
import studyImg from '@/assets/images/study.png'

import {logoutLogic, removeLocalStorageKey} from '@/utils/loginUtils.js'
import {aiCourseRoutes, blocklyRoutes, homeRoutes, aiPoetryRoutes} from "@/router/index.js";

const platformTitle = ref(import.meta.env.VITE_APP_TITLE)

const updatePlatformTitle = () => {
  platformTitle.value = localStorage.getItem('tenantName') || import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT
}

const router = useRouter()

const handleButtonClick = (button) => {
  selectedButton.value = button.name
  router.push(button.route)
}

const buttonConfigs = ref([
  // { name: 'AI编程课', route: blocklyRoutes.home },
])

const selectedButton = ref('')

const indexImages = ref([poetryImg, roomImg, testImg, studyImg])

const goToAIPoetryCourse = () => {
  router.push('/ai-poetry-course')
}

const goToManagementInterface = () => {
  router.push('/management-interface')
}

const goToAILab = () => {
  router.push({
    path: '/ai-laboratory',
    state: { grade: selectedGrade.value }
  })
}

const goToEvaluation = () =>{
  router.push({
   path:'/evaluation'
 })
}

const goToPersonalized = () =>{
  router.push({
    path:'/personalized'
  })
}

const selectedGrade = ref(localStorage.getItem('selectedGrade') || '')
const selectedGradeId = ref(localStorage.getItem('selectedGradeId') || '')
const dropdownVisible = ref(false)
const classData = ref([])

const handleVisibleChange = (visible) => {
  dropdownVisible.value = visible
}

const fetchCtTypes = async () => {
  try {
    const response = await ClassList()
    if (response.code === 0) {
      classData.value = response.data
     if (classData.value.length > 0 && !selectedGrade.value) {
        selectedGrade.value = classData.value[0].ctType
        selectedGradeId.value = classData.value[0].id
        localStorage.setItem('selectedGrade', selectedGrade.value)
        localStorage.setItem('selectedGradeId', selectedGradeId.value)
      }
    }
  } catch (error) {
    console.error('获取 ctType 数据失败:', error)
  }
}

watch(selectedGrade, (newValue) => {
  if (newValue) {
    localStorage.setItem('selectedGrade', newValue)
    const selectedItem = classData.value.find(item => item.ctType === newValue)
    if (selectedItem) {
      selectedGradeId.value = selectedItem.id
      localStorage.setItem('selectedGradeId', selectedGradeId.value)
    }
  }
})

watch(selectedGradeId, (newValue) => {
  if (newValue) {
    localStorage.setItem('selectedGradeId', newValue)
  }
})

const handleGradeSelect = (command) => {
  selectedGrade.value = command
  const selectedItem = classData.value.find(item => item.ctType === command)
  if (selectedItem) {
    selectedGradeId.value = selectedItem.id
  }
}

onMounted(() => {
  fetchCtTypes()
  updatePlatformTitle()
  window.addEventListener('storage', (e) => {
    if (e.key === 'tenantName') {
      updatePlatformTitle()
    }
  })

  removeLocalStorageKey(localStorage.getItem("token") + "_ai_")
  removeLocalStorageKey(localStorage.getItem('token') + "_course_")
  removeLocalStorageKey(localStorage.getItem("token") + "_blockly_")
  removeLocalStorageKey(localStorage.getItem("token") + "_aiCourse_")
})

window.updateTenantName = (newName) => {
  localStorage.setItem('tenantName', newName)
  updatePlatformTitle()
}
</script>

<style scoped lang="scss">
@use 'sass:math';

@function rpx($px) {
  @return math.div($px, 750) * 100vw;
}

.home-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, #001169, #8a78d0);
  display: flex;
  flex-direction: column;
  gap: rpx(0);
}

.box-1 {
  width: 100%;
  min-height: rpx(50);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  box-sizing: border-box;
  font-size: rpx(16);
}

.box-2 {
  width: 90%;
  margin: auto;
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  cursor: pointer;
}

.box-2 span {
  padding: rpx(10) 0 0 rpx(10);
  font-size: rpx(12);
  color: white;
}

.left-box-in-box2,
.center-box-in-box2 {
  background-color: rgba(133, 135, 176, 0.5);
  border-radius: rpx(30);
  flex: 1;
  margin: 0 rpx(10);
  height: 85%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  background-origin: border-box;
  background-clip: padding-box;
}

.left-box-in-box2:hover,
.left-box-in-box2:active,
.center-box-in-box2:hover,
.center-box-in-box2:active {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
}

.left-box-in-box2,
.center-box-in-box2,
.top-sub-box,
.bottom-sub-box {
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

.right-box-in-box2 {
  flex: 1;
  margin: 0 rpx(10);
  height: 85%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  gap: rpx(10);
}

.top-sub-box,
.bottom-sub-box {
  background-color: rgba(133, 135, 176, 0.5);
  flex: 1;
  display: flex;
  border-radius: rpx(20);
  width: 100%;
}

.top-sub-box:hover,
.top-sub-box:active,
.bottom-sub-box:hover,
.bottom-sub-box:active {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
}

.inner-box {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: rpx(16);
}

.inner-box.left-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 rpx(20);
}

.left-icon{
  font-size: rpx(14);
  color: white;
  cursor: pointer;
}

.app-header {
  width: 100%;
  height: rpx(30);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: rpx(5);
}

.app-logo {
  width: rpx(20);
  height: rpx(20);
  object-fit: contain;
}

.app-header span {
  color: white;
  font-size: rpx(11);
  letter-spacing: rpx(1);
  display: flex;
  align-items: center;
  height: 100%;
}

.left-box span {
  position: static;
  margin-top: 0;
  margin-left: 0;
  margin-right: rpx(10);
  font-size: rpx(11);
  color: white;
  max-width: rpx(200);
  white-space: normal;
  line-height: rpx(16);
  text-align: left;
}

.box-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: rpx(5);
  padding: rpx(3) rpx(5);
  margin-right: rpx(5);
  border-radius: rpx(30);
  backdrop-filter: blur(10px);
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: rpx(14);
  color: white;
}

.right-box {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-right: rpx(60);
}

.top-right-box {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: wrap;
  cursor: pointer;
}

.top-right-btn {
  width: rpx(50);
  height: rpx(15);
  margin: rpx(10) rpx(5) 0 0;
  background-color: transparent;
  color: white;
  border: none;
  font-size: rpx(8);
  outline: none;
}

.top-right-btn:hover {
  background-color: rgba(255, 255, 255, 0.7);
  border: 1px white solid;
  color: #8B4513;
  outline: none;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
}

.dropdown-box {
  align-items: center;
  margin-top: 0;
  display: flex;
}

.dropdown-box .el-button {
  width: rpx(60);
  height: rpx(15);
  background-color: rgba(255, 255, 255, 0.7);
  border: 1px white solid;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  color: #8B4513;
  border-radius: rpx(12);
  font-size: rpx(8);
}

.dropdown-box .el-button:hover,
.dropdown-box .el-button:focus,
.dropdown-box .el-button:active {
  border: none;
  outline: none;
}

.dropdown-menu {
  width: rpx(100);
  border-radius: rpx(5);
  border: 1px white solid;
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(rpx(5));
  box-shadow: 0 4px 8px rgba(139, 69, 19, 0.1);
  margin-left: rpx(40);
}

.el-scrollbar__view .el-dropdown__list{
  background-color: transparent;
}

.dropdown-menu ::v-deep(.el-dropdown-menu__item) {
  font-size: rpx(8);
  color: #8B4513;
  border-radius: rpx(5);
  width: rpx(78);
  height: rpx(20);
  margin-left: rpx(4);
  margin-bottom: rpx(8);
}

.dropdown-menu ::v-deep(.el-dropdown-menu__item:hover),
.dropdown-menu ::v-deep(.el-dropdown-menu__item:focus),
.dropdown-menu ::v-deep(.el-dropdown-menu__item:active) {
  background: linear-gradient(
    to bottom,
    #ffd700,
    #ffa500
  );
  box-shadow: 0 4px 8px rgba(139, 69, 19, 0.1);
}
</style>

<style lang="scss">
.no-arrow-dropdown .el-popper__arrow{
  display: none;
}

.el-popper.is-light,
.el-dropdown__popper.el-popper{
  background: transparent;
  border: none;
  box-shadow: none;
}

.el-dropdown__popper{
  --el-dropdown-menuItem-hover-color: none;
}

.user-name-box:focus,
.user-name-box:focus-within,
.user-name-box:hover{
  outline: none;
  box-shadow: none;
}

.el-dropdown .el-dropdown__trigger:focus{
  outline: none;
  box-shadow: none;
}
</style>
