import axios from 'axios'
import { ElMessage } from 'element-plus'

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

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

api.interceptors.response.use(
  response => {
    const data = response.data
    if (data.code !== 200) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message))
    }
    return data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      window.location.href = '/login'
    }
    ElMessage.error(error.response?.data?.message || '网络错误')
    return Promise.reject(error)
  }
)

export default api

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

// Organization API
export const orgApi = {
  getTree: () => api.get('/org/departments/tree').then(r => r.data),
  createDept: data => api.post('/org/departments', data).then(r => r.data),
  updateDept: (id, data) => api.put(`/org/departments/${id}`, data),
  deleteDept: id => api.delete(`/org/departments/${id}`),
  getUsers: () => api.get('/org/users').then(r => r.data),
  createUser: data => api.post('/org/users', data).then(r => r.data),
  updateUser: (id, data) => api.put(`/org/users/${id}`, data),
  deleteUser: id => api.delete(`/org/users/${id}`),
  disableUser: id => api.put(`/org/users/${id}/disable`),
  markUserLeft: id => api.put(`/org/users/${id}/leave`),
  updateSuperior: (id, superiorId) => api.put(`/org/users/${id}/superior`, { superiorId }),
  updateDepartment: (id, departmentId) => api.put(`/org/users/${id}/department`, { departmentId }),
  getMySubordinates: () => api.get('/org/users/my-subordinates').then(r => r.data),
  getSuperiors: () => api.get('/org/users/superiors').then(r => r.data),
  initSeed: () => api.post('/org/init-seed')
}

// Period API
export const periodApi = {
  list: () => api.get('/periods').then(r => r.data),
  get: id => api.get(`/periods/${id}`).then(r => r.data),
  getActive: () => api.get('/periods/active').then(r => r.data),
  create: data => api.post('/periods', data).then(r => r.data),
  batchCreate: data => api.post('/periods/batch', data).then(r => r.data),
  update: (id, data) => api.put(`/periods/${id}`, data),
  delete: id => api.delete(`/periods/${id}`),
  checkReadiness: (id, target) => api.get(`/periods/${id}/readiness`, { params: { target } }).then(r => r.data),
  transition: (id, status) => api.put(`/periods/${id}/status`, { status }),
  getParticipants: id => api.get(`/periods/${id}/participants`).then(r => r.data),
  addParticipant: (id, userId) => api.post(`/periods/${id}/participants/${userId}`).then(r => r.data),
  exemptParticipant: (id, userId, reason) => api.post(`/periods/${id}/participants/${userId}/exempt`, { reason }).then(r => r.data),
  activateParticipant: (id, userId) => api.put(`/periods/${id}/participants/${userId}/activate`).then(r => r.data)
}

// OKR API
export const okrApi = {
  submit: data => api.post('/okr/submit', data).then(r => r.data),
  update: (id, data) => api.put(`/okr/${id}/update`, data).then(r => r.data),
  review: (id, data) => api.put(`/okr/${id}/review`, data),
  updateProgress: (krId, data) => api.put(`/okr/kr/${krId}/progress`, data),
  getKrHistory: krId => api.get(`/okr/kr/${krId}/history`).then(r => r.data),
  getSuperiorOkrs: periodId => api.get(`/okr/period/${periodId}/superior`).then(r => r.data),
  getTopLevelOkrs: periodId => api.get(`/okr/period/${periodId}/top-level`).then(r => r.data),
  getMyOkr: periodId => api.get(`/okr/period/${periodId}/my`).then(r => r.data),
  canSubmit: periodId => api.get(`/okr/period/${periodId}/can-submit`).then(r => r.data),
  getSubordinates: periodId => api.get(`/okr/period/${periodId}/subordinates`).then(r => r.data),
  getPendingReviews: periodId => api.get(`/okr/period/${periodId}/pending-reviews`).then(r => r.data),
  getAllOkrs: periodId => api.get(`/okr/period/${periodId}/all`).then(r => r.data),
  getDetail: id => api.get(`/okr/${id}`).then(r => r.data),
  getTree: periodId => api.get(`/okr/period/${periodId}/tree`).then(r => r.data),
  getOrphans: periodId => api.get(`/okr/period/${periodId}/orphans`).then(r => r.data),
  setAlignment: (id, parentObjectiveId) => api.post(`/okr/${id}/align`, { parentObjectiveId }),
  getChildren: id => api.get(`/okr/${id}/children`).then(r => r.data)
}

// KPI API
export const kpiApi = {
  listTemplates: () => api.get('/kpi/templates').then(r => r.data),
  getTemplateNames: () => api.get('/kpi/templates/names').then(r => r.data),
  getTemplateByPosition: position => api.get('/kpi/templates/by-position', { params: { position } }).then(r => r.data),
  createTemplate: data => api.post('/kpi/templates', data).then(r => r.data),
  updateTemplate: (id, data) => api.put(`/kpi/templates/${id}`, data),
  deleteTemplate: id => api.delete(`/kpi/templates/${id}`),
  getConfig: (periodId, userId) => api.get(`/kpi/configs/${periodId}/${userId}`).then(r => r.data),
  saveConfig: data => api.post('/kpi/configs', data).then(r => r.data),
  lockConfig: id => api.put(`/kpi/configs/${id}/lock`)
}

// Performance API
export const scoreApi = {
  submitSelf: data => api.post('/scores/self', data).then(r => r.data),
  submitSuperior: data => api.post('/scores/superior', data).then(r => r.data),
  publish: data => api.post('/scores/publish', data).then(r => r.data),
  confirm: data => api.post('/scores/confirm', data),
  getPage: (periodId, userId) => api.get('/scores/page', { params: { periodId, userId } }).then(r => r.data),
  getMyResult: periodId => api.get('/scores/my', { params: { periodId } }).then(r => r.data),
  getSubordinates: periodId => api.get('/scores/subordinates', { params: { periodId } }).then(r => r.data),
}

export const scoreAppealApi = {
  list: params => api.get('/score-appeals', { params }).then(r => r.data),
  submit: data => api.post('/score-appeals', data).then(r => r.data),
  resolve: (id, data) => api.put(`/score-appeals/${id}/resolve`, data).then(r => r.data)
}

// Feedback API
export const feedbackApi = {
  saveInterview: data => api.post('/feedback/interview', data).then(r => r.data),
  submitReply: data => api.post('/feedback/reply', data),
  close: data => api.post('/feedback/close', data).then(r => r.data),
  getPage: (periodId, userId) => api.get('/feedback/page', { params: { periodId, userId } }).then(r => r.data)
}

// Dimension API
export const dimensionApi = {
  list: () => api.get('/dimensions').then(r => r.data),
  create: data => api.post('/dimensions', data).then(r => r.data),
  update: (id, data) => api.put(`/dimensions/${id}`, data),
  delete: id => api.delete(`/dimensions/${id}`)
}

// System API
export const systemApi = {
  getLogs: params => api.get('/system/logs', { params }).then(r => r.data),
  backupDatabase: () => api.post('/maintenance/backup').then(r => r.data)
}

// Notification API
export const notificationApi = {
  getUnreadCount: () => api.get('/notifications/unread-count').then(r => r.data),
  getPage: (params) => api.get('/notifications', { params }).then(r => r.data),
  markRead: (id) => api.put(`/notifications/${id}/read`),
  markAllRead: () => api.put('/notifications/read-all')
}
