<!-- DevTools.vue -->
<template>
    <div
      v-if="!isClosed"
      ref="widgetRef"
      class="dev-tools-widget"
      :style="widgetStyle"
      @mouseenter="hovering = true"
      @mouseleave="hovering = false"
    >
      <div class="dev-tools-header">
        <n-icon size="16" class="close-icon" @click="closeWidget">
          <Close />
        </n-icon>
      </div>
      <div class="dev-tools-content">
        <div class="dev-tools-row">
          <span class="label">用户名：</span>
          <span class="value" @click="showLoginModal">
            <template v-if="userStore.username">
                {{userStore.username}}
            </template>
            <span v-else class="login-placeholder">登录</span>
          </span>
        </div>
        <div class="dev-tools-row">
          <span class="label">环境：</span>
          <span class="value" @click="showEnvModal">{{ envStore.currentEnv?.name || '未设置' }}</span>
        </div>
      </div>
    </div>
  
    <!-- 登录弹窗 -->
    <n-modal v-model:show="showLogin" preset="dialog" title="用户登录">
      <template #header>
        <div>用户登录</div>
      </template>
      <n-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
        <n-form-item label="用户名" path="username">
          <n-input-group>
            <n-input v-model:value="loginForm.username" placeholder="请输入用户名" />
            <n-button type="primary" @click="showUserList = true">选择用户</n-button>
          </n-input-group>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input
            v-model:value="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :show-password-on="'click'"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button type="primary" @click="handleLogin">登录</n-button>
      </template>
    </n-modal>
  
    <!-- 用户列表弹窗 -->
    <n-modal v-model:show="showUserList" title="选择用户">
      <n-card title="选择用户" style="width: 480px;">
        <n-list>
          <n-list-item
            v-for="user in userList"
            :key="user.username"
            clickable
            @click="selectUser(user)"
          >
            <n-thing :title="user.username" :description="user.role" />
          </n-list-item>
        </n-list>
      </n-card>
    </n-modal>
  
    <!-- 环境切换弹窗 -->
    <n-modal v-model:show="showEnv" title="切换环境">
      <n-card title="切换环境" style="width: 480px;">
        <n-list>
          <n-list-item
            v-for="env in envStore.envList"
            :key="env.name"
            :class="{ 'active-env': env.name === envStore.currentEnv?.name }"
            clickable
            @click="switchEnv(env)"
          >
            <n-thing :title="env.name" :description="env.url" />
          </n-list-item>
        </n-list>
      </n-card>
    </n-modal>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useDraggable } from '@vueuse/core'
  import { NModal, NForm, NFormItem, NInput, NButton, NInputGroup, NList, NListItem, NThing, NIcon,NCard } from 'naive-ui'
  import { Close } from '@vicons/ionicons5'
  import axios from 'axios'
  import { useUserStore } from './stores/user'
  import { useEnvStore } from './stores/env'
  
  // 存储相关
  const userStore = useUserStore()
  const envStore = useEnvStore()
  
  // 组件状态
  const isClosed = ref(false)
  const hovering = ref(false)
  const showLogin = ref(false)
  const showUserList = ref(false)
  const showEnv = ref(false)
  
  // 登录表单
  const loginForm = ref({
    username: '',
    password: ''
  })
  
  const loginFormRef = ref(null)
  const loginRules = {
    username: { required: true, message: '请输入用户名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' }
  }
  
  // 用户列表
  const userList = [
    { username: 'sysadmin', role: '系统管理员', password: 'admin123' },
    { username: 'tschen', role: '开发人员', password: 'dev123' },
    { username: 'tester1', role: '测试人员', password: 'test123' },
    { username: 'product1', role: '产品经理', password: 'pm123' },
    { username: 'designer1', role: '设计师', password: 'design123' },
    { username: 'guest', role: '访客', password: 'guest123' }
  ]
  
  // 拖拽相关
  const widgetRef = ref(null)
  const { x, y } = useDraggable(widgetRef, {
    initialValue: { x: window.innerWidth - 220, y: window.innerHeight - 120 },
    onEnd: throttle(savePosition, 200)
  })
  
  // 计算样式
  const widgetStyle = computed(() => ({
    left: `${x.value}px`,
    top: `${y.value}px`,
    opacity: hovering.value ? 1 : 0.7
  }))
  
  // 初始化位置
  onMounted(() => {
    loadPosition()
    loadClosedState()
  })
  
  // 加载位置
  function loadPosition() {
    const savedPos = sessionStorage.getItem('devToolsPosition')
    if (savedPos) {
      const { x: savedX, y: savedY } = JSON.parse(savedPos)
      // 检查是否在视窗内
      const inViewportX = savedX > 0 && savedX < window.innerWidth - 200
      const inViewportY = savedY > 0 && savedY < window.innerHeight - 100
      
      if (inViewportX && inViewportY) {
        x.value = savedX
        y.value = savedY
      }
    }
  }
  
  // 保存位置
  function savePosition() {
    const position = { x: x.value, y: y.value }
    sessionStorage.setItem('devToolsPosition', JSON.stringify(position))
  }
  
  // 节流函数
  function throttle(fn, delay) {
    let timer = null
    return function(...args) {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(this, args)
          timer = null
        }, delay)
      }
    }
  }
  
  // 关闭组件
  function closeWidget() {
    isClosed.value = true
  }
  
  // 加载关闭状态
  function loadClosedState() {
    // const closed = sessionStorage.getItem('devToolsClosed')
    // isClosed.value = closed === 'true'
    isClosed.value = false
  }
  
  // 显示登录弹窗
  function showLoginModal() {
    if (userStore.isLoggedIn) {
      showLogin.value = true
    } else {
      showLogin.value = true
    }
  }
  
  // 显示环境弹窗
  function showEnvModal() {
    showEnv.value = true
  }
  
  // 选择用户
  function selectUser(user) {
    loginForm.value.username = user.username
    loginForm.value.password = user.password
    showUserList.value = false
  }
  
  // 处理登录
  async function handleLogin() {
    try {
      loginFormRef.value?.validate(async (errors) => {
        if (!errors) {
          const response = await axios.post('/api/login', loginForm.value)
          if (response.data.success) {
            userStore.login({
              username: loginForm.value.username,
              role: response.data.role,
              permissions: response.data.permissions
            })
            showLogin.value = false
          }
        }
      })
    } catch (error) {
      console.error('登录失败:', error)
    }
  }
  
  // 切换环境
  function switchEnv(env) {
    envStore.setCurrentEnv(env)
    userStore.logout() // 切换环境后清空登录态
    showEnv.value = false
  }
  </script>
  
  <style scoped>
  .dev-tools-widget {
    position: fixed;
    width: 200px;
    padding: 10px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 9999;
    cursor: move;
    transition: opacity 0.3s;
  }
  
  .dev-tools-header {
    display: flex;
    justify-content: flex-end;
  }
  
  .close-icon {
    cursor: pointer;
    opacity: 0.5;
    transition: opacity 0.2s;
  }
  
  .close-icon:hover {
    opacity: 1;
  }
  
  .dev-tools-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .dev-tools-row {
    display: flex;
    justify-content: space-between;
  }
  
  .label {
    color: #666;
  }
  
  .value {
    cursor: pointer;
    color: #1890ff;
  }
  
  .value:hover {
    text-decoration: underline;
  }
  
  .login-placeholder {
    color: #1890ff;
    font-weight: bold;
  }
  
  .active-env {
    background-color: #f0f7ff;
  }
  </style>