import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const api = axios.create({
    baseURL: '/api',
    timeout: 15000
})

// Request interceptor — attach token
api.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
})

// Response interceptor — handle errors
api.interceptors.response.use(
    response => response.data,
    error => {
        const msg = error.response?.data?.message || '请求失败'
        if (error.response?.status === 401) {
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
        } else {
            ElMessage.error(msg)
        }
        return Promise.reject(error)
    }
)

export default api

// Auth API
export const authApi = {
    login: (data) => api.post('/auth/login', data),
    me: () => api.get('/auth/me')
}

// Admin API
export const adminApi = {
    getUsers: () => api.get('/admin/users'),
    createUser: (data) => api.post('/admin/users', data),
    updateUser: (id, data) => api.put(`/admin/users/${id}`, data),
    deleteUser: (id) => api.delete(`/admin/users/${id}`),
    getWorkdays: (year) => api.get('/admin/workdays', { params: { year } }),
    setWorkdays: (data) => api.post('/admin/workdays', data),
    getSalesStats: (params) => api.get('/admin/stats/sales', { params }),
    getSalesDetail: (params) => api.get('/admin/stats/sales-detail', { params }),
    getRdStats: (params) => api.get('/admin/stats/rd', { params }),
    getProjectStats: (params) => api.get('/admin/stats/project', { params }),
    getProjectDetail: (params) => api.get('/admin/stats/project-detail', { params }),
    getSummaryMatrix: (params) => api.get('/admin/summary-matrix', { params }),
    getSalesUsers: () => api.get('/admin/salesusers'),
    getRdUsers: () => api.get('/admin/rdusers'),
    getClients: () => api.get('/admin/clients'),
    createClient: (data) => api.post('/admin/clients', data),
    updateClient: (id, data) => api.put(`/admin/clients/${id}`, data),
    deleteClient: (id) => api.delete(`/admin/clients/${id}`),
    getProjectTypes: () => api.get('/admin/project-types'),
    createProjectType: (data) => api.post('/admin/project-types', data),
    deleteProjectType: (id) => api.delete(`/admin/project-types/${id}`),
    // Data management
    resetData: () => api.post('/admin/reset'),
    getBackups: () => api.get('/admin/backups'),
    restoreData: (data) => api.post('/admin/restore', data),
    exportExcel: (type, params) => {
        return axios.get(`/api/admin/export/${type}`, {
            params,
            responseType: 'blob',
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    },
    exportAllExcel: (params) => {
        return axios.get(`/api/admin/export/all`, {
            params,
            responseType: 'blob',
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    },
    exportMatrixExcel: (params) => {
        return axios.get(`/api/admin/export/matrix`, {
            params,
            responseType: 'blob',
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    },
    downloadBackup: () => {
        return axios.get(`/api/admin/backup/download`, {
            responseType: 'blob',
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    },
    downloadAutoBackup: (filename) => {
        return axios.get(`/api/admin/backups/${filename}`, {
            responseType: 'blob',
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    }
}

// R&D API
export const rdApi = {
    getClients: () => api.get('/rd/clients'),
    getProjectTypes: () => api.get('/rd/project-types'),
    getTimesheets: (params) => api.get('/rd/timesheets', { params }),
    createTimesheet: (data) => api.post('/rd/timesheets', data),
    updateTimesheet: (id, data) => api.put(`/rd/timesheets/${id}`, data),
    deleteTimesheet: (id) => api.delete(`/rd/timesheets/${id}`),
    getStats: (params) => api.get('/rd/stats', { params })
}
