import {
  BaseResParams,
  ImageVodeResParams,
  LoginResParams,
  PermissonListResParams,
  SelfInfoResParams
} from '@/types/client'
import { Client } from '@/enums/api'
import { request } from '@/utils/request'
import { UploadFileParams } from '@/types/axios'

/**
 * 网页客户端登录
 * @param username 用户ID
 * @param password 用户密码，必须为md5加密后
 */
export const doLogin = (
  username: string,
  password: string,
  session?: string,
  vcode?: string
) => {
  return request.post<LoginResParams>({
    url: Client.LOGIN,
    data: {
      username,
      password,
      session,
      vcode
    }
  })
}

/**
 * 获取当前登录用户权限集
 */
export const getPermissions = () => {
  return request.post<PermissonListResParams>({
    url: Client.GET_PERMISSIONS,
    data: {}
  })
}

/**
 * 获取当前登录用户个人信息
 */
export const getSelfInfo = () => {
  return request.post<SelfInfoResParams>({
    url: Client.GET_SELF_INFO,
    data: {}
  })
}

/**
 * 设置当前登录用户个人信息
 * @param params
 */
export const setSelfInfo = (params: {
  name?: string
  mobile?: string
  email?: string
  old_pass?: string
  new_pass?: string
}) => {
  return request.post<BaseResParams>({
    url: Client.SET_SELF_INFO,
    data: params
  })
}

/**
 * 获取图片验证码
 */
export const getImageVcode = () => {
  return request.post<ImageVodeResParams>({
    url: Client.GET_IMAGE_VODE,
    data: {}
  })
}

/**
 * 上传
 * @param url
 * @param params
 * @returns
 */
export const uploadFile = (
  url: string,
  params: UploadFileParams,
  uploadProgress?: (progressEvent: ProgressEvent) => void,
  timeout?: number | 36000
) => {
  return request.uploadFile<any>(
    {
      url,
      timeout
    },
    params,
    uploadProgress
  )
}

/**
 * 使用axios下载文件，显示进度条
 * @param url
 * @param downloadProgress
 * @returns
 */
export const downloadFile = async (
  name: string,
  url: string,
  downloadProgress?: any,
  otherParams?: object
) => {
  const response = await request.get<any>(
    {
      url,
      timeout: 1000 * 60 * 60,
      responseType: 'blob',
      onDownloadProgress: (e: ProgressEvent) => downloadProgress(e, otherParams)
    },
    {
      isReturnNativeResponse: true
    }
  )
  const blob = response.data
  const a = document.createElement('a')
  document.body.appendChild(a)
  a.style.display = 'none'
  const downloadUrl = window.URL.createObjectURL(blob)
  a.href = downloadUrl
  a.download = name
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(downloadUrl)
}

/**
 * 获取区域树
 */
export const getGroupTree = () => {
  return request.post<GroupTreeResParams>({
    url: Client.INFO_DOMAIN_TREE,
    data: {}
  })
}

// 获取分组详情返回参数
export interface GroupTreeResParams extends BaseResParams {
  tree: Array<GroupTree>
}

// 功能模块具体参数
export interface GroupTree {
  id: number // 域id
  memo?: string
  key: string
  name: string
  title: string // 域名
  children: Array<GroupTree>
  showMore?: boolean
}
