<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <t-navbar class="custom-navbar">
      <!-- 左侧区域 -->
      <template #left>
        <t-button variant="text"
                  shape="square"
                  @click="handleLeftClick('home')">
          <template #icon>
            <t-icon size="23px" name="home" />
          </template>
        </t-button>
        <!-- 控制页面路由菜单 -->
        <t-dropdown-menu ref="parentRef" style="height:32px;border:none">
          <t-dropdown-item :value="currentTitle.routes" :label="currentTitle.label">
            <div v-for="(group,i) in menuValue" :key="i" >
              <div class="demo-dropdown-item_label" v-if="group.label != '管理' || (username == 'MomoWen' || username == 'Admin')">
                {{ group.label }}
              </div>
              <t-radio-group @change="menuChange" :key="i" v-if="group.label != '管理' || (username == 'MomoWen' || username == 'Admin')">
                <view v-for="(item, index) in group.options" :key="item.value" :class="`card ${currentTitle.routes == item.value ? 'card--active' : ''}`">
                  <icon v-if="currentTitle.routes == item.value" name="check" class="card__icon" />
                  <t-radio :value="item" :label="item.label" icon="none" borderless />
                </view>
              </t-radio-group>
            </div>
          </t-dropdown-item>
        </t-dropdown-menu>
        <!-- 数据库控制菜单 -->
        <t-dropdown-menu style="height:32px;border:none">
          <t-dropdown-item :options="product.options" :value="product.value" @change="databaseChanges" :disabled="disDbDrop" />
        </t-dropdown-menu>
      </template>

      <!-- 右侧区域 -->
      <template #right>
        <t-popover v-model="showPopover"
                   trigger="click"
                   placement="bottom-right"
                   :overlay-style="{ width: '120px' }">
          <t-avatar class="avatar-example--small external-class-content" shape="circle" size="33px">{{ username[0] }}</t-avatar>

          <template #content>
            <t-button size="large" theme="primary" variant="text" @click="handleAction('profile')">个人中心</t-button>
            <t-button size="large" theme="danger" variant="text" @click="handleAction('logout')">退出登录</t-button>

          </template>
        </t-popover>
        <t-button class="theme-toggle" @click="toggleTheme" size="33px">
          {{ isDarkMode ? '🌞' : '🌙' }}
        </t-button>
      </template>
    </t-navbar>

    <!-- 导航栏 -->
    <!-- 页面内容 -->
    <!--<router-view></router-view>-->
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, reactive, inject } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { Toast } from 'tdesign-mobile-vue'
  import { useDark, useToggle } from '@vueuse/core'

  const isDark = useDark()
  const toggleDark = useToggle(isDark)

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

  const $http = inject('$http')
  const username = localStorage.getItem('username')


  const product = reactive({
    value: '',
    options: [],
  })

  // 菜单值
  const menuValue = reactive([
    {
      label: "控制台",
      options: [
        {
          label: '主页',
          value: '/home',
          disabled: true,
        },
      ],
    },
    {
      label: "数据",
      options: [
        {
          label: '测试数据',
          value: '/testlog',
          disabled: true,
        },
      ],
    },
    {
      label: "管理",
      options: [
        {
          label: '导入数据',
          value: '/inputcolorbox',
          disabled: true,
        },
        {
          label: '用户管理',
          value: '/usermanage',
          disabled: true,
        },
        {
          label: '数据库管理',
          value: '/dbmanage',
          disabled: true,
        },
        {
          label: '用户日志',
          value: '/loginlog',
          disabled: true,
        }
      ],
    },
  ])
  const currentTitle = reactive({
    label: '主页',
    routes: '/home',
  }) // 当前页面标题

  const showPopover = ref(false) // 气泡菜单显示状态


  // 左侧按钮点击处理
  const handleLeftClick = (type) => {
    // type 可能的值: 'home' 按钮
    switch (type) {
      case 'home':
        let hm = {
          "label": "主页",
          "value": "/home",
          "disabled": true
        }
        menuChange(hm)
        router.push('/home')
        break;
      default:
        console.log('跳转错误！');
        break;
    }
  }

  // 菜单操作处理
  const handleAction = (action) => {
    // action 可能的值: 'profile' 个人中心 / 'logout' 退出登录
    showPopover.value = false
    switch (action) {
      case 'profile':
        disDbDrop.value = true
        router.push('/user')
        break;
      case 'logout':
        router.push('/login')
        break;
      default:
        console.log('跳转错误！');
        break;
    }


  }

  const disDbDrop = ref(false)


  // 数据库变更处理
  const databaseChanges = (type) => {
    if (type != localStorage.getItem('selectdb')) {
      Toast({
        className: 'toast-root--success',
        theme: 'success',
        direction: 'column',
        message: '数据库切换为：' + type,
      });
      localStorage.setItem('selectdb', type)
      setTimeout(() => {
        location.reload(true);
      }, 666);
    }
  }
  const parentRef = ref(null)
  // 菜单处理
  const menuChange = (val) => {
    currentTitle.label = val.label;
    currentTitle.routes = val.value;
    //console.log(val)
    if (val.value != '/home') {
      disDbDrop.value = true
    } else {
      disDbDrop.value = false
    }
    parentRef.value.collapseMenu();
    router.push(val.value)
  }

  // 判断是否管理员
  const isAdmin = (page) => {
    return (page.label == "管理" && (username == 'MomoWen' || username == 'Admin'))

  }
  // 控制深色模式
  const isDarkMode = ref(false)
  const webToDark = (dark) => {
    // 获取 <html> 元素的类名
    let ishtmldark = null;
    if (document.documentElement.className.indexOf('dark') !== -1) {
      ishtmldark = false
    } else {
      ishtmldark = true
    }
    if (dark) {
      document.documentElement.setAttribute('theme-mode', 'dark')
      isDarkMode.value = true
      if (ishtmldark) {
        toggleDark()
      }
    } else {
      document.documentElement.removeAttribute('theme-mode')
      isDarkMode.value = false
      if (!ishtmldark) {
        toggleDark()
      }

    }
  }
  const toggleTheme = () => {

    isDarkMode.value = !isDarkMode.value
    let root = document.documentElement;
    if (!isDarkMode.value) {
      // 如果当前是暗色主题，切换到亮色主题
      root.style.setProperty('--color-background', '#ffffff');
      root.style.setProperty('--color-background-soft', '#f8f8f8');
      root.style.setProperty('--color-background-mute', '#f2f2f2');
      root.style.setProperty('--color-border', 'rgba(60, 60, 60, 0.12)');
      root.style.setProperty('--color-border-hover', 'rgba(60, 60, 60, 0.29)');
      root.style.setProperty('--color-heading', '#2c3e50');
      root.style.setProperty('--color-text', '#2c3e50');
      root.setAttribute('data-theme', 'light');
      if (root.className.indexOf('dark') !== -1) {
        toggleDark()
      }
      setTimeout(() => {
        root.removeAttribute('theme-mode');
      }, 20);
    } else {
      // 如果当前是亮色主题，切换到暗色主题
      root.style.setProperty('--color-background', '#242424');
      root.style.setProperty('--color-background-soft', '#222222');
      root.style.setProperty('--color-background-mute', '#282828');
      root.style.setProperty('--color-border', 'rgba(84, 84, 84, 0.48)');
      root.style.setProperty('--color-border-hover', 'rgba(84, 84, 84, 0.65)');
      root.style.setProperty('--color-heading', '#ffffff');
      root.style.setProperty('--color-text', 'rgba(235, 235, 235, 0.64)');
      root.setAttribute('data-theme', 'dark');
      if (!(root.className.indexOf('dark') !== -1)) {
        toggleDark()
      }
      setTimeout(() => {
        root.setAttribute('theme-mode', 'dark');
      }, 20);
    }
  }
  var alreadyLogin = ref(false)
  const checkLoginStatus = () => {
    alreadyLogin.value = localStorage.getItem('login') == 'true'

  }

  // 获取服务器信息
  const onDbLogout = () => {
    let requestBody = {
      key: "getDbName",
      CmdType: "sys",
      DBQueryData: []
    }
    $http.post('DataHandle/R_InfoCommon', requestBody)
      .then(rs => {
        console.log(rs)
        if (rs.data.isok) {
          product.options = []
          // 从localStorage获取auths权限列表
          const authsJson = localStorage.getItem('auths')
          const auths = authsJson ? JSON.parse(authsJson) : []
          console.log(auths)
          rs.data.response.forEach(item => {
            if (item.Database.slice(0, 3) == "uts" && item.Database != "uts_manage") {
              // 检查用户是否有该数据库的权限（大小写不敏感）
              const hasPermission = auths.some(auth => auth.databaseName.toLowerCase() === item.Database.toLowerCase())
              if (hasPermission) {
                let dbname = {
                  label: item.Database,
                  value: item.Database
                }
                product.options.push(dbname)
              }
            }
          })
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
  }


  // 初始化
  onMounted(() => {
    // 初始检查登录状态
    checkLoginStatus()

    // 初始化数据库列表
    onDbLogout()

    if (localStorage.getItem('selectdb')) {
      product.value = localStorage.getItem('selectdb')
    } else {
      product.value = ""
      localStorage.setItem('selectdb', product.value)
    }

    findLabelByValue();
    // 主题初始化
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleColorSchemeChange = (e) => {
      webToDark(e.matches)
    }

    const url = window.location.href;
    // 找到最后一个 '/' 的位置
    const lastSlashIndex = url.lastIndexOf('/');
    // 获取最后一个 '/' 后面的内容
    const lastSegment = url.substring(lastSlashIndex);
    if (lastSegment == '/home') {
      disDbDrop.value = false
    }

    // 初始设置
    webToDark(darkModeQuery.matches)

    // 监听系统主题变化
    darkModeQuery.addEventListener('change', handleColorSchemeChange)

    // 清理监听器
    return () => {
      darkModeQuery.removeEventListener('change', handleColorSchemeChange)
    }
  })


  // 确定当前地址
  const findLabelByValue = () => {
    const url = window.location.href;
    // 找到最后一个 '/' 的位置
    const lastSlashIndex = url.lastIndexOf('/');
    // 获取最后一个 '/' 后面的内容
    const lastSegment = url.substring(lastSlashIndex);
    for (const menu of menuValue) {
      for (const option of menu.options) {
        if (option.value == lastSegment) {
          currentTitle.routes = lastSegment
          currentTitle.label = option.label
        }
      }
    }
  }
</script>

<style scoped>
  /* 主题切换按钮 */
  .theme-toggle {
    margin-left: 8px;
    padding: 8px 12px;
    background: var(--toggle-bg);
    color: var(--toggle-text);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }


  /* 横向布局 */
  .t-radio--block {
    padding: 3px 10px 3px 10px;
  }

  .horizontal-box {
    width: calc(100% - 32px);
    display: flex;
    align-items: center;
    margin: 16px;
  }

    .horizontal-box .card {
      flex: 1;
      margin: 0;
    }

      .horizontal-box .card + .card {
        margin-left: 12px;
      }

  .demo-desc {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.6);
    margin-bottom: 16px;
  }

  .card {
    display: block;
    position: relative;
    margin: 8px;
    border-radius: 6px;
    overflow: hidden;
    box-sizing: border-box;
    border: 1.5px solid #fff;
    height: 35px;
  }

  .card--active {
    border-color: #0052d9;
  }

    .card--active::after {
      content: '';
      display: block;
      position: absolute;
      left: 0;
      top: 0;
      width: 0;
      border: 8px solid #0052d9;
      border-bottom-color: transparent;
      border-right-color: transparent;
    }

  .card__icon {
    display: block;
    color: #fff;
    position: absolute;
    left: 1.5px;
    top: 1.5px;
    z-index: 10;
    font-size: 14px;
  }
</style>
