<template>
  <el-container class="app-wrapper">
    <el-aside
      :width="sidebarOpened ? '210px' : '64px'"
      :class="sidebarOpened ? 'sidebar-container' : 'sidebar-container collapsed'"
    >
      <div class="logo">
        <img src="@/assets/logo.svg" alt="logo" />
        <h1 v-show="sidebarOpened">摄像头管理</h1>
      </div>
      <el-menu
        :default-active="activeMenu"
        :collapse="!sidebarOpened"
        :collapse-transition="false"
        :background-color="isDark ? '#18181b' : '#1e293b'"
        :text-color="isDark ? '#a1a1aa' : '#94a3b8'"
        active-text-color="var(--color-primary)"
        router
      >
        <el-menu-item index="/machine">
          <el-icon><Monitor /></el-icon>
          <template #title>{{ t('机器管理') }}</template>
        </el-menu-item>

        <el-menu-item index="/camera">
          <el-icon><VideoCamera /></el-icon>
          <template #title>{{ t('摄像头管理') }}</template>
        </el-menu-item>

        <el-menu-item index="/user">
          <el-icon><UserFilled /></el-icon>
          <template #title>{{ t('用户管理') }}</template>
        </el-menu-item>

        <el-menu-item index="/cc">
          <el-icon><VideoCamera /></el-icon>
          <template #title>{{ t('Cloudflare Stream') }}</template>
        </el-menu-item>

        <el-menu-item index="/webrtc">
          <el-icon><Connection /></el-icon>
          <template #title>{{ t('WebRTC 流') }}</template>
        </el-menu-item>

        <el-sub-menu index="/demo">
          <template #title>
            <el-icon><VideoPlay /></el-icon>
            <span>{{ t('视频测试') }}</span>
          </template>
          <el-menu-item index="/demo/directurl">
            <el-icon><Link /></el-icon>
            <template #title>{{ t('直接 URL') }}</template>
          </el-menu-item>
          <el-menu-item index="/demo/rtsp">
            <el-icon><Connection /></el-icon>
            <template #title>{{ t('RTSP 流') }}</template>
          </el-menu-item>
          <el-menu-item index="/demo/samples">
            <el-icon><Film /></el-icon>
            <template #title>{{ t('测试视频') }}</template>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="/stream">
          <template #title>
            <el-icon><Film /></el-icon>
            <span>{{ t('Cloudflare Stream') }}</span>
          </template>
          <el-menu-item index="/stream/videos">
            <el-icon><Film /></el-icon>
            <template #title>{{ t('视频管理') }}</template>
          </el-menu-item>
          <el-menu-item index="/stream/live">
            <el-icon><VideoCameraFilled /></el-icon>
            <template #title>{{ t('直播管理') }}</template>
          </el-menu-item>
          <el-menu-item index="/stream/config">
            <el-icon><Setting /></el-icon>
            <template #title>{{ t('Stream 配置') }}</template>
          </el-menu-item>
          <el-menu-item index="/streamtest">
            <el-icon><Monitor /></el-icon>
            <template #title>{{ t('快速测试') }}</template>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container class="main-container">
      <el-header class="app-header">
        <div class="header-left">
          <el-icon class="collapse-btn" @click="toggleSidebar">
            <Fold v-if="sidebarOpened" />
            <Expand v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path">
              {{ t(item.meta?.title as string) }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <ThemeSwitch @open-settings="themeSettingsVisible = true" />
          <LangDropdown />

          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="'https://cube.elemecdn.com/0/88/03b0d39583f4b3a790e9d12d41f23e23jps.jpg'" />
              <span class="username">{{ userInfo?.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="changePassword">{{ t('修改密码') }}</el-dropdown-item>
                <el-dropdown-item command="logout">{{ t('退出登录') }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="passwordDialogVisible" :title="t('修改密码')" width="400px" :close-on-click-modal="false">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item :label="t('原密码')" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item :label="t('新密码')" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item :label="t('确认密码')" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            :placeholder="t('请再次输入新密码')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">{{ t('取消') }}</el-button>
        <el-button type="primary" :loading="passwordLoading" @click="handleChangePassword">{{ t('确定') }}</el-button>
      </template>
    </el-dialog>

    <!-- 主题设置抽屉 -->
    <ThemeSettings v-model="themeSettingsVisible" />
  </el-container>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  VideoCamera,
  Fold,
  Expand,
  ArrowDown,
  Monitor,
  Film,
  VideoCameraFilled,
  Setting,
  UserFilled,
  VideoPlay,
  Link,
  Connection
} from '@element-plus/icons-vue'
import LangDropdown from '@/components/LangDropdown.vue'
import ThemeSwitch from '@/components/ThemeSwitch.vue'
import ThemeSettings from '@/components/ThemeSettings.vue'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { useThemeStore } from '@/store/theme'
import { changePassword } from '@/api/login'
import { useI18n } from 'vue-i18n'
const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()
const themeStore = useThemeStore()
const { t } = useI18n()
const sidebarOpened = computed(() => appStore.sidebarOpened)
const themeSettingsVisible = ref(false)
const isDark = computed(() => themeStore.isDark)
const userInfo = computed(() => userStore.userInfo)

const activeMenu = computed(() => {
  const { path } = route
  return path
})

const breadcrumbs = computed(() => {
  return route.matched.filter((item) => item.meta && item.meta.title && !item.meta.hidden)
})

function toggleSidebar() {
  appStore.toggleSidebar()
}

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (_rule: any, value: string, callback: any) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error(t('两次输入的密码不一致')))
  } else {
    callback()
  }
}

const passwordRules: FormRules = {
  oldPassword: [{ required: true, message: t('请输入原密码'), trigger: 'blur' }],
  newPassword: [
    { required: true, message: t('请输入新密码'), trigger: 'blur' },
    { min: 6, message: t('密码长度不能少于6位'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('请再次输入新密码'), trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

function resetPasswordForm() {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

async function handleChangePassword() {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        const res = await changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        if (res.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          passwordDialogVisible.value = false
          resetPasswordForm()
          await userStore.logoutAction()
          router.push('/login')
        } else {
          ElMessage.error(res.message || '密码修改失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

async function handleCommand(command: string) {
  if (command === 'changePassword') {
    resetPasswordForm()
    passwordDialogVisible.value = true
  } else if (command === 'logout') {
    await userStore.logoutAction()
    router.push('/login')
  }
}

onMounted(() => {
  userStore.getUserInfo()
})
</script>

<style lang="scss" scoped>
.app-wrapper {
  height: 100%;
}

.sidebar-container {
  background-color: var(--bg-sidebar);
  transition: width var(--transition-base) var(--transition-timing),
    background-color var(--transition-base) var(--transition-timing);
  overflow: auto;

  .logo {
    height: var(--header-height);
    display: flex;
    align-items: center;
    padding: 0 15px;
    background-color: var(--bg-sidebar-logo);
    transition: background-color var(--transition-base) var(--transition-timing);

    img {
      width: 32px;
      height: 32px;
    }

    h1 {
      margin-left: 12px;
      font-size: var(--font-size-lg);
      font-weight: var(--font-weight-semibold);
      color: var(--text-inverse);
      white-space: nowrap;
    }
  }

  .el-menu {
    border-right: none;
  }
}

.sidebar-container.collapsed {
  overflow: hidden;
}

.main-container {
  flex-direction: column;
  min-height: 100%;
  overflow: hidden;
}

.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: var(--header-height);
  background-color: var(--bg-header);
  box-shadow: var(--shadow-header);
  transition: background-color var(--transition-base) var(--transition-timing),
    box-shadow var(--transition-base) var(--transition-timing);

  .header-left {
    display: flex;
    align-items: center;

    .collapse-btn {
      font-size: 20px;
      cursor: pointer;
      margin-right: 15px;
      color: var(--text-secondary);
      transition: color var(--transition-fast) var(--transition-timing);

      &:hover {
        color: var(--color-primary);
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;

      .username {
        margin: 0 8px;
        color: var(--text-secondary);
      }
    }
  }
}

.app-main {
  background-color: var(--bg-page);
  overflow: auto;
  transition: background-color var(--transition-base) var(--transition-timing);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity var(--transition-base) ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
