<template>
  <div class="min-h-screen bg-gray-50 rounded-lg relative">
    <BackButton backHomePage />
    <!-- 顶部背景区域 -->
    <div class="box relative h-200px bg-gradient-to-r from-purple-400 via-pink-300 to-blue-300">
      <!-- 顶部操作按钮 -->
      <div class="absolute top-4 right-4 flex gap-2">
        <el-button
          v-if="!userInfo.isOfficialAccount"
          type="info"
          plain
          size="small"
          @click="handleClearCache"
          >清除缓存</el-button
        >
        <el-button type="info" plain size="small" @click="showOnlineTime = !showOnlineTime"
          >展示/隐藏在线时长</el-button
        >
        <el-button
          v-if="officialAccountList.length"
          type="info"
          plain
          size="small"
          @click="handleSwitchAccount"
          >切换账号</el-button
        >
        <el-button
          v-if="userInfo.isOfficialAccount"
          type="info"
          plain
          size="small"
          @click="handleBackUser"
          >返回个人账号</el-button
        >

        <el-button
          v-if="userInfo.isAdmin || userInfo.isOfficialAccount"
          type="primary"
          plain
          size="small"
          @click="handleAdmin"
          >后台管理</el-button
        >
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="relative -mt-20 p-6">
      <div class="flex gap-6 w-100% flex-nowrap">
        <!-- 左侧个人信息卡片 -->
        <div class="w-300px">
          <!-- 个人信息卡片 -->
          <transition name="slide-fade" mode="out-in">
            <div
              :key="isReal"
              class="bg-white rounded-lg shadow-sm p-6 mb-4 relative overflow-hidden"
            >
              <div
                class="absolute -left-10 top-3 bg-blue-500 text-white text-xs px-10 py-1 -rotate-45 cursor-pointer shadow-md hover:from-blue-600 hover:to-blue-700 transition-all"
                @click="isReal = isReal ? 0 : 1"
              >
                切换{{ isReal ? '匿名' : '实名' }}
              </div>

              <!-- 内容区域 -->
              <div class="flex items-start gap-4">
                <el-avatar
                  :size="80"
                  :src="currentUserInfo.avatar"
                  class="border-4 border-white shadow-lg flex-shrink-0"
                />

                <div class="flex-1 min-w-0">
                  <el-tooltip :content="currentUserInfo.name" placement="top">
                    <!-- 省略号 一行 -->
                    <span
                      class="text-xl font-semibold text-gray-800 mb-1 truncate line-clamp-1 break-all"
                    >
                      {{ currentUserInfo.name }}
                    </span>
                  </el-tooltip>

                  <el-tooltip :content="currentUserInfo.signature" placement="right">
                    <span class="text-gray-500 text-sm mb-1 line-clamp-2 break-all">
                      {{ currentUserInfo.signature }}
                    </span>
                  </el-tooltip>

                  <el-button v-if="!isReal" type="warning" size="small" plain @click="handleEdit">
                    <el-icon><IEpEdit /></el-icon>
                    修改资料
                  </el-button>
                </div>
              </div>
            </div>
          </transition>

          <!-- 左侧菜单 ——个人菜单 -->
          <div class="bg-white rounded-lg shadow-sm mb-4">
            <div
              v-for="item in menuUserItems"
              :key="item.path"
              @click="changeMenu(item.path)"
              :class="[
                'flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors border-b border-gray-100 last:border-b-0',
                activeMenu === item.path
                  ? 'bg-blue-50 text-blue-600 border-r-3 border-r-blue-600'
                  : 'text-gray-700 hover:bg-gray-50',
              ]"
            >
              <el-icon :size="16">
                <component :is="item.icon" />
              </el-icon>
              <span class="text-sm">{{ item.label }}</span>
            </div>
          </div>
          <!-- 左侧菜单 —— 官方账号菜单 审核操作等 -->
          <div
            v-if="userInfo.isOfficialAccount || userInfo.isAdmin"
            class="bg-white rounded-lg shadow-sm"
          >
            <div
              v-for="item in menuOfficialItems"
              :key="item.path"
              @click="changeMenu(item.path)"
              :class="[
                'flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors border-b border-gray-100 last:border-b-0',
                activeMenu === item.path
                  ? 'bg-blue-50 text-blue-600 border-r-3 border-r-blue-600'
                  : 'text-gray-700 hover:bg-gray-50',
              ]"
            >
              <el-icon :size="16">
                <component :is="item.icon" />
              </el-icon>
              <span class="text-sm">{{ item.label }}</span>
            </div>
          </div>
          <!-- 左侧菜单 -->
        </div>
        <!-- 右侧内容区域 -->
        <div class="flex-1 min-w-0">
          <div class="bg-white rounded-lg shadow-sm min-h-500px">
            <router-view v-slot="{ Component, route }">
              <transition name="fade-user" mode="out-in">
                <keep-alive>
                  <component
                    :is="Component"
                    :key="getThirdLevelKey(route)"
                    ref="componentRef"
                    @toggleReal="(flag: BooleanFlag) => (isReal = flag)"
                  />
                </keep-alive>
              </transition>
            </router-view>
          </div>
        </div>
      </div>
    </div>
    <EditUserInfo ref="editUserInfoRef" />
  </div>
</template>

<script lang="tsx" setup>
import { storeToRefs } from 'pinia'
import EditUserInfo from './components/editUserInfo.vue'
import { generateLoginKey, hasOfficialAccount } from '@/api'
import type { OfficialAccountItemDto } from '@/api/user/types'
import { wxLogin } from '@/utils/wxUtil'
import type { RouteLocationNormalizedLoadedGeneric } from 'vue-router'
import type { TabPaneName } from 'element-plus'
import { IS_REAL_KEY } from '@/constants/symbolKey'
import { useOnlineTimeStore, useUserStore } from '@/stores'
import BackButton from '@/components/common/BackButton/index.vue'
import { push } from 'notivue'
import { BooleanFlag } from '@/constants/enums'
const { showOnlineTime } = storeToRefs(useOnlineTimeStore())

const router = useRouter()
const route = useRoute()

// 当前激活的菜单 用计算属性 好办法！
const activeMenu = computed(() => {
  const path = route.path
  if (path.includes('userPage')) {
    return path.split('/').at(-1) || 'selfPublish'
  }
  return 'selfPublish'
})

const getThirdLevelKey = (route: RouteLocationNormalizedLoadedGeneric) => {
  console.log(route.fullPath, '三级路由用户信息页面')
  return route.path
}
const componentRef = useTemplateRef<{
  refresh: () => void
}>('componentRef')
const editUserInfoRef = useTemplateRef<InstanceType<typeof EditUserInfo>>('editUserInfoRef')
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 左侧普通用户菜单
const menuUserItems = [
  {
    path: 'selfPublish',
    label: '我的帖子',
    icon: () => <IEpUser />,
    tab: '发布',
  },
  {
    path: 'selfDraft',
    label: '我的草稿',
    icon: () => <IEpDocument />,
    tab: '草稿',
  },
  {
    path: 'selfCollect',
    label: '我的收藏',
    icon: () => <IEpStar />,
    tab: '收藏',
  },
  {
    path: 'selfPraise',
    label: '我的点赞',
    icon: () => <IEpPointer />,
    tab: '点赞',
  },
  {
    path: 'selfCase',
    label: '我的案例库',
    icon: () => <IEpCollection />,
    tab: '案例库',
  },
  {
    path: 'selfTask',
    label: '我的任务',
    icon: () => <IEpFinished />,
    tab: '任务',
  },
  {
    path: 'selfActivity',
    label: '参与活动',
    icon: () => <IEpTrophy />,
    tab: '活动',
  },
  {
    path: 'selfComment',
    label: '评论回复',
    icon: () => <IEpChatDotRound />,
    tab: '评论回复',
  },
  {
    path: 'selfAnswer',
    label: '回答问题(问吧)',
    icon: () => <IEpChatLineSquare />,
    tab: '回答问题',
  },
]

// 左侧官方账号菜单
const menuOfficialItems = [
  {
    path: 'selfAudit',
    label: '审核列表',
    icon: () => <IEpUser />,
    tab: '审核列表',
  },
  {
    path: 'selfComplaint',
    label: '举报列表',
    icon: () => <IEpWarning />,
    tab: '举报列表',
  },
]

const isReal = ref<BooleanFlag>(BooleanFlag.NO)

provide(IS_REAL_KEY, isReal)

watch(isReal, () => {
  // 重新刷新一次
  componentRef.value?.refresh?.()
})

const currentUserInfo = computed(() =>
  isReal.value
    ? {
        avatar: userInfo.value.avatar,
        name: userInfo.value.name,
        signature: '',
      }
    : {
        avatar: userInfo.value.hiddenAvatar,
        name: userInfo.value.hiddenName,
        signature: userInfo.value.signature,
      },
)

const changeMenu = (key: TabPaneName) => {
  router.push(`/userPage/${key}`)
}

const handleEdit = () => {
  console.log('修改资料')
  editUserInfoRef.value?.open({
    hiddenAvatar: userInfo.value.hiddenAvatar,
    hiddenName: userInfo.value.hiddenName,
    signature: userInfo.value.signature,
  })
}

const officialAccountList = ref<OfficialAccountItemDto[]>([])
const getIsOfficial = async () => {
  const { data } = await hasOfficialAccount()
  console.log(data)
  officialAccountList.value = data
}

const handleSwitchAccount = async () => {
  const selectedEmail = ref('')
  ElMessageBox({
    title: '切换官方账号',
    message: () => (
      <div class="flex flex-wrap gap-3 p-4">
        {officialAccountList.value.map((item) => {
          return (
            <el-card
              key={item.email}
              shadow="hover"
              class={[
                'flex items-center justify-center cursor-pointer transition-all relative',
                'hover:shadow-lg border-2 rounded-lg',
                selectedEmail.value === item.email
                  ? 'border-blue-500! bg-blue-50!'
                  : 'border-gray-200!',
              ]}
              style="width: 160px; padding: 16px"
              onClick={() => {
                selectedEmail.value = item.email
              }}
            >
              {/* 右上角单选框 */}
              <div class="absolute top-2 right-2">
                <el-checkbox
                  modelValue={selectedEmail.value}
                  true-value={item.email}
                  size="large"
                />
              </div>

              {/* 内容区域 */}
              <div class="flex flex-col items-center gap-3 w-full">
                <el-avatar size={80} src={item.avatar} />
                <div class="flex flex-col items-center gap-1 w-full">
                  <span class="text-sm font-medium text-gray-800 truncate w-full text-center">
                    {item.officialTag}
                  </span>
                </div>
              </div>
            </el-card>
          )
        })}
      </div>
    ),
    showCancelButton: true,
    confirmButtonText: '确认切换',
    cancelButtonText: '取消',
    customClass: 'min-w-740px',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        if (!selectedEmail.value) return push.warning('请选择要切换的账号')
        instance.confirmButtonLoading = true
        try {
          const { data } = await generateLoginKey({
            timestamp: Date.now(),
            type: 2,
            userId: userInfo.value.userId,
            cutEmail: selectedEmail.value,
          })
          console.log(data)
          localStorage.clear()
          await userStore.getUserInfoByCode({
            code: data,
            isCodeLogin: 1,
            cutEmail: selectedEmail.value,
          })
          done()
          window.location.reload()
        } catch (error) {
          console.log(error)
        } finally {
          instance.confirmButtonLoading = false
        }
      } else {
        done()
      }
    },
  })
}

const handleBackUser = () => {
  wxLogin(route.fullPath)
}

const handleAdmin = () => {
  router.push('/backend')
}

const handleClearCache = async () => {
  // 获取登陆的key
  const { data } = await generateLoginKey({
    timestamp: Date.now(),
    type: 1,
    userId: userInfo.value.userId,
  })
  // 清理sessionStorage
  localStorage.clear()
  await userStore.getUserInfoByCode({
    code: data,
    isCodeLogin: 1,
  })
  window.location.reload()
}

onMounted(() => {
  getIsOfficial()
})
</script>

<style scoped>
.box {
  background-image: url('http://soundasia.oss-cn-shenzhen.aliyuncs.com/OA/2022/10/13/1665643787806.jpg');
}
.slide-fade-enter-from {
  opacity: 0;
  transform: translateY(20px) rotateY(-10deg) translateZ(-300px) scale(0.95);
  filter: blur(6px);
}

.slide-fade-enter-active {
  transition:
    opacity 0.6s cubic-bezier(0.22, 1, 0.36, 1),
    transform 0.6s cubic-bezier(0.22, 1, 0.36, 1),
    filter 0.6s ease;
  transform-style: preserve-3d;
}

.slide-fade-enter-to {
  opacity: 1;
  transform: translateY(0) rotateY(0deg) translateZ(0) scale(1);
  filter: blur(0);
  /* box-shadow: 0 15px 40px rgba(0, 0, 0, 0.18); */
}

.slide-fade-leave-from {
  opacity: 1;
  transform: translateY(0) rotateY(0deg) translateZ(0) scale(1);
  filter: blur(0);
}

.slide-fade-leave-active {
  transition:
    opacity 0.5s cubic-bezier(0.55, 0, 0.55, 0.2),
    transform 0.5s cubic-bezier(0.55, 0, 0.55, 0.2),
    filter 0.4s;
  transform-style: preserve-3d;
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-20px) rotateY(10deg) translateZ(200px) scale(0.9);
  filter: blur(6px);
}
.fade-user-enter-from,
.fade-user-leave-to {
  opacity: 0;
  transform: translateX(10px);
  filter: blur(4px);
}
.fade-user-enter-to,
.fade-user-leave-from {
  opacity: 1;
  transform: translateX(0);
  filter: blur(0);
}
.fade-user-enter-active,
.fade-user-leave-active {
  transition: all 0.3s ease;
}
</style>
