import router from '@/router'
import Axios from 'axios'
import { showError } from '@/utils/ui.ts'
import { v4 as uuidv4 } from 'uuid'
import dayjs from 'dayjs'
import {
  findRequestItemByUUID,
  deleteRequestByUUID,
  addRequestItem,
  getTimeDifferenceInMilliseconds,
  UserJson,
} from './requestLog.ts'
const axios = Axios.create({
  baseURL: import.meta.env.VITE_API_BASE,
  timeout: 60 * 60 * 1000, //半小时
})

const TOKEN_KEY = 'token'

export function setToken(token: string) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

axios.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers['jwt-token'] = token
    }
    config.headers.timestamp = new Date().getTime()
    config.headers.uuid = uuidv4().replace(/-/g, '')
    addRequestItem({
      url: config.url || '',
      method: config.method || '',
      startTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss.SSS'),
      uuid: config.headers.uuid,
    })
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)
axios.interceptors.response.use(
  (response) => {
    // 1. 判断响应码
    const data = response.data
    const uuid = response.config?.headers?.uuid
    const item = findRequestItemByUUID(uuid)
    if (response.config.url) {
      if (response.config.url.startsWith('/')) {
        item.url = `${import.meta.env.VITE_API_BASE}${response.config.url}`
      } else {
        item.url = `${
          import.meta.env.VITE_API_BASE
        }${`/${response.config.url}`}`
      }
    }

    const fm = new FormData()
    const processTime = response.headers['processtime']
    const endTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss.SSS')
    const clientResponseTime = getTimeDifferenceInMilliseconds(
      item.startTime,
      endTime,
    )
    console.log(item)
    if ((clientResponseTime as number) >= 3000) {
      const user = localStorage.getItem('user')
      if (user) {
        const userJson: UserJson = JSON.parse(user)
        fm.append('factoryCode', userJson?.factoryCode)
      }
      fm.append('processTime', processTime)
      fm.append('url', item.url)
      fm.append('method', item.method)
      fm.append('requestId', response.data.requestId)
      fm.append('clientResponseTime', String(clientResponseTime) + 'ms')
      navigator.sendBeacon(
        `${import.meta.env.VITE_API_BASE}/factory/ops/report-data`,
        fm,
      )
    }
    deleteRequestByUUID(uuid)
    if (data && typeof data === 'object' && typeof data.code === 'number') {
      // token 过期
      if (data.code === 403) {
        router.replace({ path: '/user/login' })
        return Promise.reject(data)
      }
      if (data.code !== 200) {
        if (!response.config.skipGlobalError) {
          showError(data.message)
        }
        return Promise.reject(data)
      }
    }
    return data
  },
  (error) => {
    if (!error.config?.skipGlobalError) {
      showError(error.message)
    }
    return Promise.reject(error)
  },
)
export function getFilePath() {
  if (!/(http|https):\/\/([^/]+)/i.test(import.meta.env.BASE_URL)) {
    return location.origin + import.meta.env.VITE_API_BASE_UPLOAD_URL
  }
  return (
    import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_API_BASE_UPLOAD_URL
  )
}
export function getFileCnPath() {
  if (!/(http|https):\/\/([^/]+)/i.test(import.meta.env.BASE_URL)) {
    return location.origin
  }
  return import.meta.env.VITE_API_BASE_URL
}
export function getWsUrl() {
  if (location.protocol === 'https:') {
    return 'wss://' + location.host
  } else {
    return 'ws://' + location.host
  }
}
export const filePath = getFilePath()
export const FileCnPath = getFileCnPath()

export default axios
