<template>
  <div class="main-container">
    <!-- aspect-[16/6] -->
    <div class="banner mb-3 w-full aspect-[4/1] overflow-hidden">
      <el-carousel class="h-full w-full shadow-lg rounded-lg">
        <el-carousel-item
          v-for="(item, index) in carouselList"
          :key="index"
          class="h-full w-full"
          @click="handleClickCarousel(item)"
        >
          <el-image :src="item.assetUrl" class="w-full h-full object-cover" />
        </el-carousel-item>
      </el-carousel>
    </div>

    <div class="flex gap-3">
      <div class="left basis-3/4 transition-all duration-500">
        <div
          id="tabsRef"
          ref="tabsRef"
          class="tabs-container h-75px flex relative rounded-lg mb-3 shadow-md"
        >
          <div
            v-for="tab in tabs"
            :key="tab.path"
            class="flex-1 flex items-center justify-center cursor-pointer relative transition-all duration-300 group"
            @click="toggleTab(tab)"
          >
            <div
              class="flex items-center gap-2 px-12 py-2.5 rounded-lg transition-all duration-300"
              :class="{
                'bg-#fffdfd shadow-[inset_0_2px_4px_0_rgb(0,0,0,0.1)]': activeTab === tab.name,
                'hover:bg-white/60': activeTab !== tab.name,
              }"
            >
              <svg-icon :name="tab.svg" class="h-60px w-auto md:h-50px sm:h-40px" size="40" />
              <div class="text-18px font-500 text-gray-800 md:text-16px sm:text-14px">
                {{ tab.name }}
              </div>
            </div>
          </div>
        </div>

        <div
          class="content-container w-100% rounded-lg bg-#F5F8FD border-1px border-solid border-#EAEAEF shadow-[0_1px_4px_0_rgba(33,33,52,0.1)]"
        >
          <div class="content-wrapper p-6">
            <router-view v-slot="{ Component, route }">
              <transition name="fade-home" mode="out-in">
                <keep-alive>
                  <component :is="Component" :key="getThirdLevelKey(route)" />
                </keep-alive>
              </transition>
            </router-view>
          </div>
        </div>
      </div>
      <!-- 屏幕变小直接隐藏 -->
      <div class="right flex-col gap-3 flex basis-1/4">
        <!-- 等级等相关信息 -->
        <div
          ref="levelContainerRef"
          id="levelContainerRef"
          class="level-container common-box flex flex-col justify-center items-center gap-4 rounded-lg bg-#E4F5FE"
        >
          <div class="top flex items-center justify-center gap-3">
            <img class="h-20" :src="currentLevelData?.iconUrl" alt="" />
            <div class="text-base flex-3/4 flex flex-col gap-1">
              <div class="flex items-center gap-1 justify-start">
                <div class="font-semibold">等级：{{ currentLevelData?.label }}</div>
                <el-tooltip
                  :content="`当前经验：${userAccountData.expTotal}/${currentLevelData.expScope[1]} (${currentLevelData.percentage}%)`"
                  placement="top"
                >
                  <div class="relative w-20 cursor-pointer">
                    <div
                      class="relative w-full h-4 bg-#A5E4FF rounded-full border-1 border-#30C4FF border-solid"
                    >
                      <div class="absolute left-0 top-0 h-full bg-#30C4FF rounded-full"></div>
                      <div
                        class="absolute left-0 top-0 h-full bg-gradient-to-r from-blue-500 via-blue-400 to-cyan-400 rounded-full transition-all duration-500 ease-out"
                        :style="{ width: `${currentLevelData.percentage}%` }"
                      >
                        <div
                          class="absolute top-0 left-0 w-full h-1/2 bg-gradient-to-b from-white/40 to-transparent rounded-t-full"
                        ></div>
                      </div>
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="text-amber-600 font-medium">
                YA币：{{ userAccountData.ayabiAvailable }}
              </div>
            </div>
          </div>
          <div class="flex flex-col sm:flex-row gap-2">
            <div ref="dailySignBtnRef">
              <el-button
                class="bg-[linear-gradient(to_right,#FFD06A_0%,#FFB143_100%)] shadow-[0px_1px_8px_0_rgba(255,173,91,0.25)] border-none hover:-translate-y-1 hover:shadow-[0px_4px_10px_0_rgba(255,173,91,0.4)] hover:scale-105 active:scale-95 active:translate-y-0 transition-all duration-200 flex-1 text-xs sm:text-sm"
                type="primary"
                @click="onDailySign"
                v-if="!userRecordData.isSign"
              >
                <!-- v-if="!userRecordData.isSign" -->

                <svg-icon name="sign_in" size="24" class="mr-2 mb-1" />
                <span class="text-black text-xs sm:text-sm">立即签到</span>
              </el-button>
            </div>
            <el-button
              class="bg-[linear-gradient(to_right,#ABB0FF_0%,#7495FF_100%)] shadow-[0_1px_8px_0_rgba(0,36,237,0.25)] border-none hover:-translate-y-1 transition-all duration-200 flex-1 text-xs sm:text-sm w-116px"
              type="primary"
              @click="router.push('/pointsStore')"
            >
              <svg-icon name="points_store" size="24" class="mr-2 mb-1" />
              <span class="text-black text-xs sm:text-sm">积分商城</span>
            </el-button>
          </div>
        </div>

        <!-- 案例库 -->
        <div class="case-container common-box rounded-lg bg-#E2FDF5">
          <div class="flex items-center gap-2 mb-2">
            <div class="w-1 h-4 bg-gradient-to-b from-blue-500 to-purple-500 rounded-full"></div>
            <h1 class="text-sm sm:text-base font-bold">YAYA案例库</h1>
          </div>
          <p class="text-xs sm:text-sm mb-4 line-clamp-3 leading-relaxed">
            分享您在工作或文化践行中的优秀案例，公开有奖，有机会收录至内部经验库，沉淀经验，赋能组织成长。
          </p>
          <div class="flex justify-center items-center">
            <el-button
              class="bg-[linear-gradient(to_right,#A3EADC_0%,#7BE0BD_100%)] shadow-[0_1px_4px_0_rgba(168,225,210,1)] border-none hover:-translate-y-1 transition-all duration-200 text-xs sm:text-sm w-116px"
              type="primary"
              @click="router.push('/publishCase')"
            >
              <svg-icon name="submit" size="20" class="mr-2" />
              <span class="text-black text-xs sm:text-sm">去投稿</span>
            </el-button>
          </div>
        </div>

        <div class="submit-container common-box rounded-lg bg-#EDEAFE">
          <div class="grid grid-cols-3 mb-4 gap-0 2xl:gap-2">
            <div
              class="flex flex-col items-center justify-center text-center cursor-pointer hover:-translate-y-1 transition-transform duration-200 p-2 rounded-lg hover:bg-white/10"
              @click="publishTopic"
            >
              <svg-icon name="topic_release" size="80" />
              <div class="text-xs 2xl:text-sm">话题发布</div>
            </div>
            <div
              class="flex flex-col items-center justify-center text-center cursor-pointer hover:-translate-y-1 transition-transform duration-200 p-2 rounded-lg hover:bg-white/10"
              @click="router.push('/userPage/selfAnswer')"
            >
              <el-badge :value="userQestionNum" :offset="[-5, 20]" :hidden="!userQestionNum">
                <svg-icon name="answer" size="80" />
              </el-badge>

              <div class="text-xs 2xl:text-sm">回答问题</div>
            </div>

            <div
              @click="router.push('/publishVideo')"
              class="flex flex-col items-center justify-center text-center cursor-pointer hover:-translate-y-1 transition-transform duration-200 p-2 rounded-lg hover:bg-white/10"
            >
              <svg-icon name="video_release" size="80" />
              <div class="text-xs 2xl:text-sm">视频发布</div>
            </div>
          </div>
          <div class="flex justify-center items-center">
            <el-button
              @click="router.push(`/userPage/selfComment?type=${ArticleTypeEnum.QUESTION}`)"
              class="bg-[linear-gradient(to_right,#D6C9FF_0%,#C5B1FF_100%)] shadow-[0_1px_4px_0_rgba(95,0,237,0.25)] border-none hover:-translate-y-1 transition-all duration-200 text-xs sm:text-sm w-116px"
              type="primary"
            >
              <svg-icon name="my_answer" size="20" class="mr-2" />
              <span class="text-black text-xs sm:text-sm">我的回答</span>
            </el-button>
          </div>
        </div>

        <!-- 任务中心 -->
        <div class="task-container common-box rounded-lg bg-#FFF0E5">
          <div class="flex items-start justify-start mb-2">
            <div class="w-full">
              <div class="flex items-center gap-2">
                <div class="w-1 h-4 bg-gradient-to-b from-pink-500 to-rose-500 rounded-full"></div>
                <h1 class="text-sm sm:text-base">任务中心</h1>
              </div>
              <div
                class="w-full text-xs sm:text-sm mt-1 text-gray-600 flex items-center justify-between"
              >
                <div>
                  <span
                    v-for="item in taskTypeList"
                    :key="item.value"
                    class="text-#333 cursor-pointer after:content-['|'] after:mx-2 after:text-#999 last:after:content-none"
                    :class="{ 'text-#999': currentTask !== item.value }"
                    @click="currentTask = item.value"
                    >{{ item.label }}
                  </span>
                </div>
                <span class="text-#999 cursor-pointer" @click="router.push(`/userPage/selfTask`)">
                  查看更多
                </span>
              </div>
            </div>
          </div>

          <div class="flex flex-col gap-2 sm:gap-3">
            <div v-show="currentTaskList.length">
              <div v-for="item in currentTaskList" :key="item.id">
                <div
                  class="flex items-center justify-between hover:bg-white/10 rounded-lg transition-colors duration-200 group"
                >
                  <div class="flex items-center min-w-0 flex-1">
                    <div class="h-16 2xl:h-19 flex items-center justify-center">
                      <svg-icon :name="item.svgName" size="46" />
                    </div>
                    <div
                      class="flex flex-col items-start justify-center mx-2 sm:ml-3 min-w-0 flex-1"
                    >
                      <el-tooltip :content="item.description" placement="top">
                        <div class="text-14px truncate w-full font-medium mb-1 cursor-pointer">
                          {{ item.title }}({{ item.currentCount }}/{{ item.limitCount }})
                        </div>
                      </el-tooltip>

                      <div class="color-#333 text-xs w-full flex items-center flex-nowrap">
                        <svg-icon name="small_coin" size="16" class="mr-1" />
                        <el-tooltip :content="getTaskRewardDescription(item)" placement="bottom">
                          <div class="truncate w-130px">
                            {{ getTaskRewardDescription(item) }}
                          </div>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                  <button
                    class="w-16 h-8 2xl:w-18 2xl:h-9 shadow-[0_1px_8px_0_rgba(255,141,54,0.25)] border-none text-xs sm:text-sm rounded-full"
                    :class="[
                      item.currentCount === item.limitCount
                        ? 'bg-#FFC5A1 cursor-not-allowed'
                        : 'bg-[linear-gradient(to_right,#FFC5A1_0%,#FFB77F_100%)] hover:-translate-y-1 transition-all duration-200 cursor-pointer',
                    ]"
                    @click="handleTask(item)"
                  >
                    <span
                      class="text-black text-sm"
                      :style="{
                        color: item.currentCount === item.limitCount ? '#999' : '#000',
                      }"
                      >{{ item.currentCount === item.limitCount ? '已完成' : '去完成' }}</span
                    >
                  </button>
                </div>
                <el-divider style="margin: 0" />
              </div>
            </div>
            <div v-show="currentTaskList.length === 0">
              <div class="flex items-center justify-center">
                <el-empty :image-size="100" description="暂无任务" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-tour v-model="open">
      <el-tour-step :target="dailySignBtnRef">
        <div>签到成功后，可以获得亚币奖励</div>
      </el-tour-step>
      <template #indicators></template>
    </el-tour>
  </div>
</template>
<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import front from '@/assets/img/culture/front_page.png'
import ya from '@/assets/img/culture/ya_culture.png'
import ask from '@/assets/img/culture/ask.png'
import type { RouteLocationNormalizedLoadedGeneric } from 'vue-router'
import { getTaskList, dailySign, getCarouselList, getUserAccountData, getRecordData } from '@/api'
import { TaskTypeEnum, TaskDateLimitTypeText, ArticleTypeEnum } from '@/constants'
import type { CarouselItemDto, TaskItemDto, UserAccountDataDto, UserRecordDataDto } from '@/api'
import { TABS_REF_KEY, levelListOptions } from '@/constants'
import { useScrollTop } from '@/hooks'
import { useQuestionStore } from '@/stores/question'
import { storeToRefs } from 'pinia'

const route = useRoute()
const router = useRouter()
const open = ref(false)

const levelContainerRef = useTemplateRef<HTMLElement>('levelContainerRef')
const dailySignBtnRef = useTemplateRef<HTMLElement>('dailySignBtnRef')
const { handleBackTop } = useScrollTop(levelContainerRef)

const questionStore = useQuestionStore()
const { userQestionNum } = storeToRefs(questionStore)

const getThirdLevelKey = (route: RouteLocationNormalizedLoadedGeneric) => {
  // console.log(route.fullPath, '三级路由首页')
  // console.log(route.path, 11111111111111)
  // return route.fullPath // fullpath带有query参数
  return route.path
}

const carouselList = ref<CarouselItemDto[]>([])
const tabsRef = useTemplateRef('tabsRef')

const tabs = [
  { name: '首页', path: 'homeTab', img: front, svg: 'home' },
  { name: 'YA文化', path: 'yaTab', img: ya, svg: 'ya_culture' },
  { name: '问吧', path: 'askTab', img: ask, svg: 'ask' },
]

const activeTab = ref(
  tabs.find((item) => item.path === route.path.split('/').at(-1))?.name || '首页',
)
watch(
  () => route.path,
  (newPath) => {
    activeTab.value = tabs.find((item) => item.path === newPath.split('/').at(-1))?.name || '首页'
  },
)

const toggleTab = (tab: { name: string; path: string }) => {
  activeTab.value = tab.name
  router.push(`/homePage/${tab.path}`)
}

const taskTypeList = [
  {
    label: '常规任务',
    value: TaskTypeEnum.REGULAR_TASK,
  },
  {
    label: '特殊任务',
    value: TaskTypeEnum.SPECIAL_TASK,
  },
]

const currentTask = ref(TaskTypeEnum.REGULAR_TASK)

const regularTaskList = ref<TaskItemDto[]>([])
const specialTaskList = ref<TaskItemDto[]>([])

const currentTaskList = computed(() =>
  currentTask.value === TaskTypeEnum.REGULAR_TASK ? regularTaskList.value : specialTaskList.value,
)

const getTaskRewardDescription = (item: TaskItemDto) => {
  return `+${item.rewardValue}亚币${
    TaskDateLimitTypeText[item.limitType] && `(${TaskDateLimitTypeText[item.limitType] + '刷新'})`
  }`
}

// 用户账号信息
const userAccountData = ref<UserAccountDataDto>({} as UserAccountDataDto)
const currentLevelData = computed<{
  label: string
  iconUrl: string
  percentage: number
  expScope: [number, number]
}>(() => {
  const levelData = levelListOptions.find((item) => item.value === userAccountData.value.level)!

  if (!levelData) return { label: '', iconUrl: '', percentage: 0, expScope: [0, 0] }

  const currExp = userAccountData.value.expTotal
  const percentage = Number(
    (
      ((currExp - levelData.expScope[0]) / (levelData.expScope[1] - levelData.expScope[0])) *
      100
    ).toFixed(2),
  )
  console.log(percentage)
  return {
    label: levelData.label,
    iconUrl: levelData.iconUrl,
    percentage,
    expScope: levelData.expScope,
  }
})

const userRecordData = ref({} as UserRecordDataDto)

const onDailySign = async () => {
  await dailySign()
  await refreshTaskData(true)
  const { data } = await getUserAccountData()
  userAccountData.value = data
  ElMessage.success('签到成功')
  open.value = false
}

const handleTask = async (item: TaskItemDto) => {
  console.log(item)
  if (item.currentCount === item.limitCount) return
  // 先暂时写死
  if (item.svgName === 'daily_sign') {
    //每日签到
    await handleBackTop()
    open.value = true
  } else if (item.svgName === 'valid_comments') {
    // 发布评论
    ElMessage.info('快去文章评论区去发表评论吧~')
  } else if (item.svgName === 'topic_publish') {
    if (route.path.includes('/homePage/askTab')) {
      // 同一个页面 需要加事件触发 watch
      router.push(`/homePage/askTab#tabsRef?t=${Date.now()}`)
    } else {
      router.push(`/homePage/askTab#tabsRef`)
    }
  } else if (item.svgName === 'answer_ask') {
    // 回答问题
    router.push('/userPage/selfAnswer')
  } else if (item.svgName === 'video_publish') {
    // 视频发布
    router.push('/publishVideo')
  } else if (item.svgName === 'practice_publish') {
    // 个人实践/投稿
    router.push('/publishCase')
  }
}

const publishTopic = () => {
  if (route.path.includes('/homePage/askTab')) {
    // 同一个页面 需要加事件触发 watch
    router.push(`/homePage/askTab#tabsRef?t=${Date.now()}`)
  } else {
    router.push(`/homePage/askTab#tabsRef`)
  }
}

const handleClickCarousel = (item: CarouselItemDto) => {
  if (item.url) {
    window.open(item.url)
  }
}

const initPage = () => {
  Promise.allSettled([getCarouselList(), getUserAccountData(), getRecordData()]).then(
    ([r1, r2, r3]) => {
      if (r1.status === 'fulfilled') {
        carouselList.value = r1.value.data
      }

      if (r2.status === 'fulfilled') {
        userAccountData.value = r2.value.data
      }
      if (r3.status === 'fulfilled') {
        userRecordData.value = r3.value.data
      }
    },
  )
}
const refreshTaskData = async (refreshRecordData = false) => {
  if (refreshRecordData) {
    const { data } = await getRecordData()
    userRecordData.value = data
  }
  const { data } = await getTaskList()
  regularTaskList.value = data.filter((item) => item.taskType === TaskTypeEnum.REGULAR_TASK)
  specialTaskList.value = data.filter((item) => item.taskType === TaskTypeEnum.SPECIAL_TASK)
}

// 刷新任务进度 以及是否打开漫游
onActivated(async () => {
  questionStore.fetchUserQestionNum()
  refreshTaskData(false)
  if (route.fullPath.includes('#levelContainerRef')) {
    await handleBackTop()
    open.value = true
  }
})

onMounted(() => {
  initPage()
})

provide(TABS_REF_KEY, tabsRef)
</script>
<style lang="scss" scoped>
.main-container {
  .banner {
    :deep(.el-carousel__container) {
      height: 100% !important;
    }
  }

  padding-bottom: 100px;

  .tabs-container {
    background: linear-gradient(to right, #d1f3ff 0%, #bebeff 100%);
  }

  .right {
    .common-box {
      padding: 15px;
      border: 1px solid #eaeaef;
      box-shadow: 0 1px 4px 0 rgba(33, 33, 52, 0.1);
    }

    .common-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(to right, #efe7dc 0%, #efe7dc 100%);
      border: 1px solid #767676;
      color: #000;
      cursor: pointer;
      transition: all 0.3s;
    }
  }
}

.fade-home-enter-from,
.fade-home-leave-to {
  opacity: 0;
  transform: translateX(30px);
  filter: blur(4px);
}

.fade-home-enter-to,
.fade-home-leave-from {
  opacity: 1;
  transform: translateX(0);
  filter: blur(0);
}

.fade-home-enter-active,
.fade-home-leave-active {
  transition: all 0.3s ease;
}
</style>
