<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import Button from 'primevue/button'
import Menu from 'primevue/menu'
import NavMenu from '@/components/NavMenu.vue'
import Drawer from 'primevue/drawer'
import Dialog from 'primevue/dialog'
import Password from 'primevue/password'
import Message from 'primevue/message'
import { Form } from '@primevue/forms'
import FloatLabel from 'primevue/floatlabel'
import IconField from 'primevue/iconfield'
import InputIcon from 'primevue/inputicon'
import { useToast } from 'primevue/usetoast'
import { useUserStore } from '@/stores/user'
import { resetPasswordApi } from '@/services/api'
import { zodResolver } from '@primevue/forms/resolvers/zod'
import { z } from 'zod'

const router = useRouter()
const sidebarVisible = ref(false)
const userMenuRef = ref()
const toast = useToast()
const userStore = useUserStore()

const showUserMenu = (event) => {
  userMenuRef.value.toggle(event)
}

const allNavItems = [
  {
    label: '首页',
    icon: 'pi pi-fw pi-home',
    name: 'dashboard',
    roles: ['admin', 'team', 'promoter']
  },
  {
    label: '团队管理',
    icon: 'pi pi-fw pi-building',
    roles: ['admin', 'team'],
    items: [
      {
        label: '团队信息',
        icon: 'pi pi-fw pi-info-circle',
        name: 'team-info',
        roles: ['admin', 'team']
      },
      {
        label: '成员信息',
        icon: 'pi pi-fw pi-users',
        name: 'team-members',
        roles: ['admin', 'team']
      }
    ]
  },
  {
    label: '推广链接',
    icon: 'pi pi-fw pi-link',
    name: 'link',
    roles: ['admin', 'team', 'promoter']
  },
  {
    label: '财务记录',
    icon: 'pi pi-fw pi-credit-card',
    name: 'finance',
    roles: ['admin', 'team']
  },
  {
    label: '收入记录',
    icon: 'pi pi-fw pi-wallet',
    name: 'income',
    roles: ['admin', 'team', 'promoter']
  },
  {
    label: '用户管理',
    icon: 'pi pi-fw pi-user',
    name: 'user',
    roles: ['admin']
  },
  {
    label: '参数配置',
    icon: 'pi pi-fw pi-cog',
    name: 'sys-config',
    roles: ['admin']
  }
]

const navItems = computed(() => {
  const { userInfo } = userStore
  if (!userInfo?.id || !userInfo?.role) return []

  const filterItemsByRole = (items, role) =>
    items
      .filter((item) => !item.roles || item.roles.includes(role))
      .map((item) => {
        if (item.items) {
          const subItems = filterItemsByRole(item.items, role)
          if (subItems.length > 0) {
            return { ...item, items: subItems }
          }
          return null
        }
        return item
      })
      .filter(Boolean)

  return filterItemsByRole(allNavItems, userInfo.role)
})

const userMenuItems = [
  {
    label: '修改密码',
    icon: 'pi pi-fw pi-lock',
    command: () => resetPassword()
  },
  {
    separator: true
  },
  {
    label: '退出登录',
    icon: 'pi pi-fw pi-sign-out',
    command: () => logout()
  }
]

const logout = () => {
  userStore.logout()
  router.push('/login')
}

const resetingPasswordData = ref({
  visible: false,
  password: '',
  confirmPassword: '',
  loading: false
})

const resetPassword = () => {
  resetingPasswordData.value = {
    visible: true,
    password: '',
    confirmPassword: '',
    loading: false
  }
}

const resolver = zodResolver(
  z.object({
    password: z.string().min(8, { message: '密码至少8位' }),
    confirmPassword: z.string().refine((val) => val === resetingPasswordData.value.password, {
      message: '密码不一致'
    })
  })
)
const handleResetPassword = async ({ valid, values }) => {
  console.log(valid, values)
  if (!valid) {
    return
  }
  resetingPasswordData.value.loading = true
  try {
    await resetPasswordApi(values.password)
    resetingPasswordData.value.loading = false
    resetingPasswordData.value.visible = false
    toast.add({
      severity: 'success',
      summary: '成功',
      detail: '密码修改成功',
      life: 2000
    })
    logout()
  } catch (error) {
    resetingPasswordData.value.loading = false
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: error.message || '密码修改失败',
      life: 2000
    })
  }
}
</script>

<template>
  <div class="main-layout">
    <div class="layout-content">
      <div class="sidebar fixed overflow-auto">
        <NavMenu :model="navItems" />
        <!-- <Menu :model="navItems" /> -->
      </div>
      <div class="main-content flex-1">
        <router-view />
      </div>
    </div>

    <div class="layout-header fixed top-0 left-0 right-0 w-full z-1 flex items-center">
      <Button
        icon="pi pi-bars"
        severity="secondary"
        variant="text"
        @click="sidebarVisible = true"
        class="mr-4 lg:hidden!"
      />
      <img src="@/assets/logo.svg" alt="logo" class="logo" />
      <div class="title flex-1 font-bold ml-4 text-xl">Admin</div>
      <Button
        icon="pi pi-user"
        severity="secondary"
        @click="showUserMenu"
        aria-haspopup="true"
        aria-controls="overlay_menu"
        class="ml-2"
      />
      <Menu ref="userMenuRef" id="overlay_menu" :model="userMenuItems" :popup="true" />
    </div>

    <Drawer v-model:visible="sidebarVisible" position="left" :modal="true" :dismissable="false">
      <NavMenu :model="navItems" />
    </Drawer>

    <Dialog v-model:visible="resetingPasswordData.visible" modal header="修改密码" :style="{ width: '25rem' }">
      <Form
        v-slot="$form"
        :resolver="resolver"
        :initialValues="resetingPasswordData"
        @submit="handleResetPassword"
        class="p-fluid"
      >
        <FloatLabel variant="on" class="mt-2">
          <IconField>
            <InputIcon class="pi pi-lock" />
            <Password
              id="password"
              name="password"
              v-model="resetingPasswordData.password"
              fluid
              toggleMask
              :feedback="false"
              autocomplete="off"
            />
          </IconField>
          <label for="password">新密码</label>
        </FloatLabel>
        <Message v-if="$form.password?.invalid" severity="error" size="small" variant="simple">{{
          $form.password.error?.message
        }}</Message>
        <FloatLabel variant="on" class="mt-4">
          <IconField>
            <InputIcon class="pi pi-lock" />
            <Password
              id="confirmPassword"
              name="confirmPassword"
              v-model="resetingPasswordData.confirmPassword"
              fluid
              toggleMask
              :feedback="false"
              autocomplete="off"
            />
          </IconField>
          <label for="confirmPassword">重复新密码</label>
        </FloatLabel>
        <Message v-if="$form.confirmPassword?.invalid" severity="error" size="small" variant="simple">{{
          $form.confirmPassword.error?.message
        }}</Message>
        <div class="field mt-4 text-right">
          <Button label="取消" severity="secondary" @click="resetingPasswordData.visible = false" />
          <Button label="保存" type="submit" class="ml-4" />
        </div>
      </Form>
    </Dialog>
  </div>
</template>

<style lang="less" scoped>
.layout-header {
  height: 4rem;
  background-color: var(--p-surface-0);
  padding: 0 2rem;
  .logo {
    width: 1.5rem;
    height: 1.5rem;
  }
}

.layout-content {
  margin-top: 60px;
}

.sidebar {
  width: 250px;
  top: 0;
  left: 0;
  margin-top: 4rem;
  max-height: calc(100vh - 4rem);
}

.main-content {
  padding: 1rem 2rem;
  overflow-y: auto;
  width: calc(100% - 250px);
  margin-left: 250px;
}

@media (max-width: 1024px) {
  .layout-header {
    padding: 0 1rem;
  }
  .sidebar {
    display: none;
  }
  .main-content {
    margin-left: 0;
    width: 100%;
    padding: 1rem;
  }
}
</style>
