/**
 * 用户状态管理（唯一的用户信息来源）
 *
 * 所有用户信息统一由本 store 管理，localStorage 只存以下 key：
 *   token, userId, userName, officeId, officeName, deptId, deptName,
 *   areaId, areaName, roleIds
 *
 * 禁止在其他地方直接读写 localStorage 中的用户相关 key。
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// ── localStorage key 常量 ────────────────────────────────────────────
const LS = {
  TOKEN: 'token',
  USER_ID: 'userId',
  USER_NAME: 'userName',
  OFFICE_ID: 'officeId',
  OFFICE_NAME: 'officeName',
  DEPT_ID: 'deptId',
  DEPT_NAME: 'deptName',
  AREA_ID: 'areaId',
  AREA_NAME: 'areaName',
  ROLE_IDS: 'roleIds',
} as const

/** 解析 JWT payload（不验证签名，仅用于前端展示） */
function decodeJwtPayload(token: string): Record<string, unknown> | null {
  try {
    const parts = token.split('.')
    if (parts.length !== 3) return null
    const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/')
    const padded = payload + '='.repeat((4 - payload.length % 4) % 4)
    return JSON.parse(atob(padded))
  } catch {
    return null
  }
}

export const useUserStore = defineStore('user', () => {
  // ── Reactive state ────────────────────────────────────────────────
  const token = ref(localStorage.getItem(LS.TOKEN) || '')
  const userId = ref(localStorage.getItem(LS.USER_ID) || '')
  const userName = ref(localStorage.getItem(LS.USER_NAME) || '')
  const officeId = ref(localStorage.getItem(LS.OFFICE_ID) || '')
  const officeName = ref(localStorage.getItem(LS.OFFICE_NAME) || '')
  const deptId = ref(localStorage.getItem(LS.DEPT_ID) || '')
  const deptName = ref(localStorage.getItem(LS.DEPT_NAME) || '')
  const areaId = ref(localStorage.getItem(LS.AREA_ID) || '')
  const areaName = ref(localStorage.getItem(LS.AREA_NAME) || '')
  const roleIds = ref<string[]>(JSON.parse(localStorage.getItem(LS.ROLE_IDS) || '[]'))

  const isLoggedIn = computed(() => !!token.value)

  // ── 持久化辅助 ────────────────────────────────────────────────────
  function persist() {
    localStorage.setItem(LS.TOKEN, token.value)
    localStorage.setItem(LS.USER_ID, userId.value)
    localStorage.setItem(LS.USER_NAME, userName.value)
    localStorage.setItem(LS.OFFICE_ID, officeId.value)
    localStorage.setItem(LS.OFFICE_NAME, officeName.value)
    localStorage.setItem(LS.DEPT_ID, deptId.value)
    localStorage.setItem(LS.DEPT_NAME, deptName.value)
    localStorage.setItem(LS.AREA_ID, areaId.value)
    localStorage.setItem(LS.AREA_NAME, areaName.value)
    localStorage.setItem(LS.ROLE_IDS, JSON.stringify(roleIds.value))
  }

  /** 从 JWT payload 填充用户字段 */
  function parseToken(t: string) {
    const payload = decodeJwtPayload(t)
    if (!payload) return
    userId.value = (payload.sub as string) || ''
    userName.value = (payload.user_name as string) || userName.value || userId.value
    officeId.value = (payload.office_id as string) || ''
    officeName.value = (payload.office_name as string) || ''
    deptId.value = (payload.dept_id as string) || ''
    deptName.value = (payload.dept_name as string) || ''
    areaId.value = (payload.area_id as string) || ''
    areaName.value = (payload.area_name as string) || ''
    roleIds.value = Array.isArray(payload.role_ids) ? payload.role_ids : []
    persist()
  }

  /** 设置 token 并自动解析用户信息 */
  function setToken(newToken: string) {
    token.value = newToken
    parseToken(newToken)
  }

  /** 手动补充/覆盖用户信息（如 Mock 登录返回的 user_name） */
  function setUserInfo(info: {
    userName?: string
    userId?: string
    officeId?: string
    officeName?: string
    deptId?: string
    deptName?: string
    areaId?: string
    areaName?: string
    roleIds?: string[]
  }) {
    if (info.userName !== undefined) userName.value = info.userName
    if (info.userId !== undefined) userId.value = info.userId
    if (info.officeId !== undefined) officeId.value = info.officeId
    if (info.officeName !== undefined) officeName.value = info.officeName
    if (info.deptId !== undefined) deptId.value = info.deptId
    if (info.deptName !== undefined) deptName.value = info.deptName
    if (info.areaId !== undefined) areaId.value = info.areaId
    if (info.areaName !== undefined) areaName.value = info.areaName
    if (info.roleIds !== undefined) roleIds.value = info.roleIds
    persist()
  }

  /** 退出登录，清空全部状态和 localStorage */
  function logout() {
    token.value = ''
    userId.value = ''
    userName.value = ''
    officeId.value = ''
    officeName.value = ''
    deptId.value = ''
    deptName.value = ''
    areaId.value = ''
    areaName.value = ''
    roleIds.value = []
    Object.values(LS).forEach((key) => localStorage.removeItem(key))
  }

  // 初始化：从已有 token 解析用户信息
  if (token.value) {
    parseToken(token.value)
  }

  return {
    token,
    userId,
    userName,
    officeId,
    officeName,
    deptId,
    deptName,
    areaId,
    areaName,
    roleIds,
    isLoggedIn,
    setToken,
    setUserInfo,
    logout,
  }
})
