import axios from './instance'
import {
  GET_USER,
  POST_LOGIN,
  GET_USER_META,
  POST_LOGOUT,
  UPLOAD_FILE
} from './constant'
import { jsonToForm } from '@/shared'
import type { Role } from './'
import { RoutesName } from '@/router'

export interface User {
  nickname: string
  phone: string
  avatar: string
  email: string
}

type SUser = {
  head: string
  nickName: string
  userName: string
  email: string
}

const toLocal = (data: SUser): User => ({
  nickname: data.nickName,
  avatar: data.head,
  phone: data.userName,
  email: data.email
})

export const fetchUser = async (): Promise<User> => {
  const data = await axios.post<SUser>(GET_USER)
  return toLocal(data)
}

export type LoginState = {
  phone: string
  password: string
}
export const postLogin = async (state: LoginState) => {
  const data = await axios.post<{ token: string; user: SUser }>(POST_LOGIN, {
    phoneNum: state.phone,
    password: state.password
  })
  return {
    token: data.token,
    user: toLocal(data.user)
  }
}

export const postLogout = async () => axios.post(POST_LOGOUT)

export type UserMeta = {
  projectCount: number
  projectFileCount: number
  projectSceneCount: number
  projectOverCount: number
}
export const fetchUserMeta = () => axios.get<UserMeta>(GET_USER_META)

export const uploadFile = async (file: File | Blob) =>
  await axios<string>({
    url: UPLOAD_FILE,
    method: 'POST',
    data: jsonToForm({ file }),
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
