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

export const useAuthStore = defineStore('auth', () => {
  // 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[]
    endpoints?: string[]
  } | 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 userEndpoints = computed(() => roleInfo.value?.endpoints || [])

  // 后端角色标识映射到前端业务端
  const backendRoleToFrontend = (roleKey?: string): UserRole => {
    const map: Record<string, UserRole> = {
      front: 'sales',
      dispatch: 'dispatch',
      construction: 'construction',
    }
    return map[roleKey || ''] || 'sales'
  }

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

    const finalRole = backendRoleToFrontend(res.roleKey)

    const userData: User = {
      id: String(res.userId),
      name: res.nickName || res.userName,
      phone: res.phonenumber || '',
      avatar: res.avatar,
      role: finalRole,
      department: res.dept?.deptName || '',
      position: '',
      employeeNo: '',
      email: res.email || '',
      hireDate: '',
      team: '',
      status: 'active',
    }

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

    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))

    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')
  }

  // 兼容旧代码的别名
  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,
    userEndpoints,
    doLogin,
    doLogout,
    logout,
    checkLogin,
  }
})
