<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/store/user'
import request from '@/api/request'
import {
  House,
  Briefcase,
  User,
  Tickets,
  Van,
  Box,
  Goods,
  Money,
  Wallet,
  Connection,
  Document,
  DataAnalysis,
  Setting,
  Fold,
  Expand,
  ArrowDown
} from '@element-plus/icons-vue'
import FloatingChat from '@/components/FloatingChat.vue'

const isCollapse = ref(false)
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// ---- 修改密码 ----
const pwdDialogVisible = ref(false)
const pwdSubmitting = ref(false)
const pwdFormRef = ref<FormInstance>()
const pwdForm = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' })

const pwdRules = reactive<FormRules>({
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== pwdForm.newPassword) callback(new Error('两次密码不一致'))
        else callback()
      },
      trigger: 'blur',
    },
  ],
})

const openPwdDialog = () => {
  pwdDialogVisible.value = true
  nextTick(() => pwdFormRef.value?.resetFields())
}

const submitChangePassword = async () => {
  const valid = await pwdFormRef.value?.validate().catch(() => false)
  if (!valid) return
  pwdSubmitting.value = true
  try {
    await request.put('/api/auth/password', {
      old_password: pwdForm.oldPassword,
      new_password: pwdForm.newPassword,
    })
    ElMessage.success('密码修改成功，请重新登录')
    pwdDialogVisible.value = false
    // 强制重新登录
    setTimeout(() => {
      userStore.logout()
      router.push('/login')
    }, 800)
  } catch {
    // 已统一拦截
  } finally {
    pwdSubmitting.value = false
  }
}

const handleCommand = (command: string) => {
  if (command === 'logout') {
    userStore.logout()
    ElMessage.success('已安全退出')
    router.push('/login')
  } else if (command === 'changePassword') {
    openPwdDialog()
  }
}
</script>

<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside :width="isCollapse ? '64px' : '240px'" class="aside">
      <div class="logo">
        <span v-show="!isCollapse" class="logo-text"><strong>SHBL-ERP</strong></span>
        <span v-show="isCollapse" class="logo-icon">S</span>
      </div>
      <el-menu
        :default-active="route.path"
        class="el-menu-vertical"
        :collapse="isCollapse"
        router
        unique-opened
        background-color="#001529"
        text-color="#a6adb4"
        active-text-color="#fff"
      >
        <el-menu-item index="/">
          <el-icon><House /></el-icon>
          <template #title>工作台</template>
        </el-menu-item>

        <el-sub-menu index="sales">
          <template #title>
            <el-icon><Briefcase /></el-icon>
            <span>业务线</span>
          </template>
          <el-menu-item index="/customers">
            <el-icon><User /></el-icon>
            <template #title>客户管理</template>
          </el-menu-item>
          <el-menu-item index="/orders">
            <el-icon><Tickets /></el-icon>
            <template #title>订单管理</template>
          </el-menu-item>
          <el-menu-item index="/shipping">
            <el-icon><Van /></el-icon>
            <template #title>发货记录</template>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="supply-chain">
          <template #title>
            <el-icon><Box /></el-icon>
            <span>供应链</span>
          </template>
          <el-menu-item index="/products">
            <el-icon><Goods /></el-icon>
            <template #title>产品与库存</template>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="finance-group">
          <template #title>
            <el-icon><Money /></el-icon>
            <span>财务管理</span>
          </template>
          <el-menu-item index="/finance/sales-invoices">销项发票</el-menu-item>
          <el-menu-item index="/finance">报销管理</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="oa">
          <template #title>
            <el-icon><Connection /></el-icon>
            <span>协同办公</span>
          </template>
          <el-menu-item index="/logs">
            <el-icon><Document /></el-icon>
            <template #title>销售日志</template>
          </el-menu-item>
          <el-menu-item index="/reports">
            <el-icon><DataAnalysis /></el-icon>
            <template #title>AI 智能复盘</template>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="sys-settings">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </template>
          <el-menu-item index="/settings">
            <el-icon><User /></el-icon>
            <template #title>权限与员工管理</template>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <!-- 右侧容器 -->
    <el-container>
      <!-- 顶栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-icon class="toggle-icon" @click="toggleSidebar">
            <component :is="isCollapse ? Expand : Fold" />
          </el-icon>
          <!-- 面包屑 -->
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ (route.meta?.title as string) || route.name }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              <el-avatar :size="30" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
              <span class="username">{{ userStore.realName || userStore.username || 'Admin' }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="'changePassword'">修改密码</el-dropdown-item>
                <el-dropdown-item divided :command="'logout'">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="main">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <component :is="Component" :key="$route.fullPath" />
          </transition>
        </router-view>
      </el-main>
    </el-container>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="pwdDialogVisible" title="修改密码" width="420px" destroy-on-close>
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="90px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="pwdForm.oldPassword" type="password" show-password placeholder="请输入当前密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" type="password" show-password placeholder="至少6位" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" type="password" show-password placeholder="再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pwdDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="pwdSubmitting" @click="submitChangePassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 全局 AI 悬浮球 -->
    <FloatingChat />
  </el-container>
</template>

<style scoped>
.layout-container {
  height: 100vh;
  width: 100vw;
}

.aside {
  background-color: #001529;
  transition: width 0.3s;
  display: flex;
  flex-direction: column;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  color: #fff;
  background-color: #002140;
  overflow: hidden;
  white-space: nowrap;
}

.logo-text {
  font-size: 18px;
  letter-spacing: 1px;
}

.logo-icon {
  font-size: 20px;
  font-weight: bold;
}

.el-menu-vertical {
  flex: 1;
  border-right: none;
}

/* Ensure sub-menu titles have a nice color change on hover */
:deep(.el-sub-menu__title:hover) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}
.el-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

.el-menu-item.is-active {
  background-color: var(--el-color-primary) !important;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
  background-color: #fff;
  height: 60px;
  padding: 0 20px;
}

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

.toggle-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
}

.header-right {
  display: flex;
  align-items: center;
}

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

.username {
  margin-left: 8px;
  font-size: 14px;
}

.main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

/* 页面过渡动画 */
.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
