import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, UserRole } from '../types'
import { login, logout } from '../api/auth'
import type { LoginMenu } from '../api/auth'
import { getTeamSimpleList } from '../api/team'
import { useNotificationStore } from './notification'

export const useAuthStore = defineStore('auth', () => {
  const notificationStore = useNotificationStore()
  // State
  const token = ref<string>('')
  const user = ref<User | null>(null)
  const roleInfo = ref<{
    roleId?: number
    roleName?: string
    roleKey?: string
    homePath?: string
    menus?: LoginMenu[]
    permissions?: string[]
    mpEndpoint?: 'mp-sales' | 'mp-dispatch' | 'mp-construction'
  } | null>(null)

  // Getters
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => user.value?.name || '')
  const userRole = computed(() => user.value?.role || '')
  const userInfo = computed(() => user.value)
  const homePath = computed(() => roleInfo.value?.homePath || '')
  const userMpEndpoint = computed(() => roleInfo.value?.mpEndpoint || null)

  // 由账号绑定的移动端登录端推导所属业务端
  const endpointToRole = (mpEndpoint?: string): UserRole | null => {
    const map: Record<string, UserRole> = {
      'mp-sales': 'sales',
      'mp-dispatch': 'dispatch',
      'mp-construction': 'construction',
    }
    return mpEndpoint ? map[mpEndpoint] || null : null
  }

  // Actions
  async function doLogin(
    account: string,
    password: string,
    selectedRole?: 'mp-sales' | 'mp-dispatch' | 'mp-construction'
  ) {
    const res = await login({ account, password, roleType: selectedRole })

    let teamName = ''
    try {
      const teams = await getTeamSimpleList()
      const team = teams.find((t) => t.value === res.teamId)
      teamName = team?.label || ''
    } catch {
      teamName = ''
    }

    const finalRole = endpointToRole(res.mpEndpoint)
    if (!finalRole) {
      uni.showToast({ title: '当前账号未配置移动端登录端，无法登录', icon: 'none' })
      throw new Error('当前账号未配置移动端登录端')
    }

    const userData: User = {
      id: String(res.userId),
      name: res.nickName || res.userName,
      phone: res.phonenumber || res.phone || '',
      avatar: res.avatar,
      role: finalRole,
      department: res.deptName || res.dept?.deptName || '',
      deptId: res.deptId || res.dept?.deptId,
      employeeNo: res.staffCode || res.employeeNo || '',
      email: res.email || '',
      hireDate: res.entryDate || res.hireDate || '',
      team: teamName || res.teamName || res.team || '',
      teamId: res.teamId,
      postNames: res.postNames || '',
      dutyStatus: res.dutyStatus || '',
      skillLevel: res.skillLevel || '',
      certifications: res.certifications || '',
      tags: res.tags || '',
      skillTags: res.skillTags || '',
      currentTaskId: res.currentTaskId,
      status: 'active',
    }

    const roleData = {
      roleId: res.roleId,
      roleName: res.roleName,
      roleKey: res.roleKey,
      homePath: res.homePath,
      menus: res.menus,
      permissions: res.permissions,
      mpEndpoint: res.mpEndpoint,
    }

    user.value = userData
    roleInfo.value = roleData
    token.value = res.token

    // 保存到本地存储
    uni.setStorageSync('token', res.token)
    uni.setStorageSync('user', JSON.stringify(userData))
    uni.setStorageSync('roleInfo', JSON.stringify(roleData))

    // 连接 WebSocket 实时通知
    notificationStore.connectSocket(res.token)

    return finalRole
  }

  async function doLogout() {
    try {
      await logout()
    } catch {
      // 忽略登出失败
    }
    token.value = ''
    user.value = null
    roleInfo.value = null
    uni.removeStorageSync('token')
    uni.removeStorageSync('user')
    uni.removeStorageSync('roleInfo')

    // 断开 WebSocket 并清空通知
    notificationStore.disconnectSocket()
    notificationStore.messages = []
    notificationStore.unreadCount = 0
  }

  // 兼容旧代码的别名
  const logout = doLogout

  function checkLogin() {
    const savedToken = uni.getStorageSync('token')
    const savedUser = uni.getStorageSync('user')
    const savedRoleInfo = uni.getStorageSync('roleInfo')
    if (savedToken && savedUser) {
      token.value = savedToken
      try {
        user.value = JSON.parse(savedUser)
      } catch {
        user.value = null
      }
    }
    if (savedRoleInfo) {
      try {
        roleInfo.value = JSON.parse(savedRoleInfo)
      } catch {
        roleInfo.value = null
      }
    }
  }

  return {
    token,
    user,
    roleInfo,
    isLoggedIn,
    userName,
    userRole,
    userInfo,
    homePath,
    userMpEndpoint,
    doLogin,
    doLogout,
    logout,
    checkLogin,
  }
})
