import type { IUserInfo } from '@/api/types/appointment'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
  getUserInfo as _getUserInfo,
  updateUserInfo as _updateUserInfo,
} from '@/api/appointment'

// 初始化状态
const userInfoState: IUserInfo = {
  id: 0,
  openid: '',
  nickname: '',
  real_name: '',
  phone: '',
  phone_verified: false,
  avatar_url: '',
  face_image_url: '',
  status: 1,
  created_at: '',
  updated_at: '',
  role: '',
  role_name: '',
  is_formal_employee: false,
  department_name: '',
  position: '',
  certification: undefined,
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...userInfoState })

    const roleCode = computed(() => userInfo.value.role || '')

    // 通用角色检查函数
    const hasRole = (code: string): boolean => roleCode.value === code

    // 动态角色 getters
    const isEmployee = computed(() => hasRole('employee'))
    const isGuard = computed(() => hasRole('guard'))
    const isVisitor = computed(() => hasRole('visitor') || !roleCode.value)
    const isLeader = computed(() => hasRole('employee'))

    // 是否为正式员工（来自后端 userinfo 返回）
    const isFormalEmployee = computed(() => !!userInfo.value.is_formal_employee)

    const setUserInfo = (val: IUserInfo) => {
      console.log('设置用户信息', val)
      userInfo.value = { ...userInfoState, ...val }
    }

    const clearUserInfo = () => {
      userInfo.value = { ...userInfoState }
    }

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
      const res = await _getUserInfo()
      setUserInfo(res)
      return res
    }

    /**
     * 更新用户信息（封装 API 调用 + store 同步）
     */
    const updateUserInfo = async (data: Record<string, any>) => {
      await _updateUserInfo(data)
      await fetchUserInfo()
    }

    return {
      userInfo,
      roleCode,
      hasRole,
      isEmployee,
      isFormalEmployee,
      isGuard,
      isVisitor,
      isLeader,
      clearUserInfo,
      fetchUserInfo,
      setUserInfo,
      updateUserInfo,
    }
  },
  {
    persist: true,
  },
)