import axios from 'axios'

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

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

api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('cma_token')
      localStorage.removeItem('cma_user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const authApi = {
  login: (data: any) => api.post('/auth/login', data),
  register: (data: any) => api.post('/auth/register', data),
}

export const kpiApi = {
  list: (params?: any) => api.get('/kpis', { params }),
  get: (id: number) => api.get(`/kpis/${id}`),
  create: (data: any) => api.post('/kpis', data),
  update: (id: number, data: any) => api.put(`/kpis/${id}`, data),
  delete: (id: number) => api.delete(`/kpis/${id}`),
  listCategories: () => api.get('/kpis/categories'),
  associateMap: (id: number, data: any) => api.put(`/kpis/${id}/associate-map`, data),
  // KPI-5: 五档评分
  score: (params?: any) => api.get('/kpis/score', { params }),
  // KPI-6: 三级分解树
  hierarchy: (params?: any) => api.get('/kpis/hierarchy', { params }),
  // KPI-8: 因果链追踪
  causalityChain: (id: number) => api.get(`/kpis/${id}/causality-chain`),
}

export const mapApi = {
  list: () => api.get('/maps'),
  create: (data: any) => api.post('/maps', data),
  update: (id: number, data: any) => api.put(`/maps/${id}`, data),
  delete: (id: number) => api.delete(`/maps/${id}`),
  batchDelete: (ids: number[]) => api.post('/maps/batch-delete', { ids }),
  createWithTemplate: (data: any) => api.post('/maps/create-with-template', data),
}

export const dashboardApi = {
  summary: (role: string) => api.get('/dashboard/summary', { params: { role } }),
  kpis: (params: any) => api.get('/dashboard/kpis', { params }),
  myKpis: (params?: any) => api.get('/dashboard/my-kpis', { params }),
  financeAnalysis: (params?: any) => api.get('/dashboard/finance-analysis', { params }),
  predict: (params?: any) => api.get('/dashboard/predict', { params }),
}

export const templateApi = {
  list: (params?: any) => api.get('/templates', { params }),
  get: (id: number) => api.get(`/templates/${id}`),
  instantiate: (id: number, data: any) => api.post(`/templates/${id}/instantiate`, data),
  create: (data: any) => api.post('/templates', data),
  update: (id: number, data: any) => api.put(`/templates/${id}`, data),
  delete: (id: number) => api.delete(`/templates/${id}`),
}

export const dataApi = {
  importExcel: (file: File, qs?: string) => {
    const form = new FormData()
    form.append('file', file)
    return api.post(`/data/import-excel${qs ? '?' + qs : ''}`, form)
  },
  importExcelSmart: (file: File) => {
    const form = new FormData()
    form.append('file', file)
    return api.post('/data/import-excel-smart', form, { timeout: 60000 })
  },
  listSources: () => api.get('/data/sources'),
  createSource: (data: any) => api.post('/data/sources', data),
  updateSource: (id: number, data: any) => api.put(`/data/sources/${id}`, data),
  deleteSource: (id: number) => api.delete(`/data/sources/${id}`),
}

export const alertApi = {
  list: (params?: any) => api.get('/alerts', { params }),
  resolve: (id: number, data: any) => api.post(`/alerts/${id}/resolve`, data),
  riskMatrix: (params?: any) => api.get('/alerts/risk-matrix', { params }),
}

export const alertRulesApi = {
  list: (params?: any) => api.get('/alert-rules', { params }),
  getKpiRules: (kpiId: number) => api.get(`/alert-rules/kpi/${kpiId}`),
  create: (data: any) => api.post('/alert-rules', data),
  update: (id: number, data: any) => api.put(`/alert-rules/${id}`, data),
  delete: (id: number) => api.delete(`/alert-rules/${id}`),
  batchCreate: (data: any) => api.post('/alert-rules/batch', data),
  generateDefaults: () => api.post('/alert-rules/generate-defaults'),
  checkAll: () => api.post('/alert-rules/check-all'),
  calculateDynamic: () => api.post('/alert-rules/calculate-dynamic'),
  dynamicThresholds: (params?: any) => api.get('/alert-rules/dynamic-thresholds', { params }),
}

export const userApi = {
  list: () => api.get('/users'),
  create: (data: any) => api.post('/users', data),
  update: (id: number, data: any) => api.put(`/users/${id}`, data),
  delete: (id: number) => api.delete(`/users/${id}`),
}

export const notificationApi = {
  list: () => api.get('/notifications/channels'),
  create: (data: any) => api.post('/notifications/channels', data),
  update: (id: number, data: any) => api.put(`/notifications/channels/${id}`, data),
  delete: (id: number) => api.delete(`/notifications/channels/${id}`),
  test: (id: number) => api.post(`/notifications/channels/${id}/test`),
  logs: (params?: any) => api.get('/notifications/logs', { params }),
}

export const actionPlanApi = {
  list: (params?: any) => api.get('/action-plans', { params }),
  create: (data: any) => api.post('/action-plans', data),
  update: (id: number, data: any) => api.put(`/action-plans/${id}`, data),
  delete: (id: number) => api.delete(`/action-plans/${id}`),
  cosoChecklist: (params?: any) => api.get('/action-plans/coso-checklist', { params }),
}

export const budgetApi = {
  list: (params?: any) => api.get('/budget/plans', { params }),
  create: (data: any) => api.post('/budget/plans', data),
  update: (id: number, data: any) => api.put(`/budget/plans/${id}`, data),
  delete: (id: number) => api.delete(`/budget/plans/${id}`),
  autoDecompose: (data: any) => api.post('/budget/auto-decompose', data),
  deviationReport: (params?: any) => api.get('/budget/deviation-report', { params }),
  methodComparison: (data: any) => api.post('/budget/method-comparison', data),
}

export const costApi = {
  dashboard: (params?: any) => api.get('/cost/dashboard', { params }),
  overview: (params?: any) => api.get('/cost/overview', { params }),
  variance: (params?: any) => api.get('/cost/variance', { params }),
  breakdown: (params?: any) => api.get('/cost/breakdown', { params }),
  comparison: (params?: any) => api.get('/cost/comparison', { params }),
  listStandardCosts: (params?: any) => api.get('/cost/standard-costs', { params }),
  createStandardCost: (data: any) => api.post('/cost/standard-costs', data),
  updateStandardCost: (id: number, data: any) => api.put(`/cost/standard-costs/${id}`, data),
  deleteStandardCost: (id: number) => api.delete(`/cost/standard-costs/${id}`),
  listActualCosts: (params?: any) => api.get('/cost/actual-costs', { params }),
  createActualCost: (data: any) => api.post('/cost/actual-costs', data),
  listAbcActivities: () => api.get('/cost/abc/activities'),
  createAbcActivity: (data: any) => api.post('/cost/abc/activities', data),
  doAbcAllocate: (data: any) => api.post('/cost/abc/allocate', data),
  listAbcAllocations: (params?: any) => api.get('/cost/abc/allocations', { params }),
}

export const predictApi = {
  cvp: (data: any) => api.post('/predict/cvp', data),
  cvpDetailed: (data: any) => api.post('/predict/cvp-detailed', data),
  investment: (data: any) => api.post('/predict/investment', data),
  sensitivity: (data: any) => api.post('/predict/sensitivity', data),
  scenario: (data: any) => api.post('/predict/scenario', data),
  growthQuality: (data: any) => api.post('/predict/growth-quality', data),
}

export const deviationPushApi = {
  pushToMap: (data: any) => api.post('/deviation-push/push-to-map', data),
  getMapNodes: (mapId: number) => api.get(`/deviation-push/map-nodes/${mapId}`),
}

export const budgetGenerateApi = {
  getCandidates: () => api.get('/budget/kpi-budget-candidates'),
  generateFromKpis: (data: any) => api.post('/budget/generate-from-kpis', data),
}

export const knowledgeArticleApi = {
  list: (params?: any) => api.get('/knowledge-articles', { params }),
  get: (id: number) => api.get(`/knowledge-articles/${id}`),
}

export const roleApi = {
  list: () => api.get('/roles'),
  create: (data: any) => api.post('/roles', data),
  update: (id: number, data: any) => api.put(`/roles/${id}`, data),
  delete: (id: number) => api.delete(`/roles/${id}`),
}

export const permissionApi = {
  getMenuTree: () => api.get('/permissions/menu-tree'),
  getUserRoles: () => api.get('/user-roles'),
  setUserRoles: (data: any) => api.post('/user-roles', data),
}

export const kpiCausalityApi = {
  list: (params?: any) => api.get('/kpi-causality', { params }),
  get: (id: number) => api.get(`/kpi-causality/${id}`),
  create: (data: any) => api.post('/kpi-causality', data),
  update: (id: number, data: any) => api.put(`/kpi-causality/${id}`, data),
  delete: (id: number) => api.delete(`/kpi-causality/${id}`),
  getNetwork: (kpiId: number) => api.get(`/kpi-causality/kpi/${kpiId}/network`),
  getFullNetwork: () => api.get('/kpi-causality/full-network'),
  simulate: (data: any) => api.post('/kpi-causality/simulate', data),
}

export const dataQualityApi = {
  check: () => api.get('/data-quality/check'),
  stats: () => api.get('/data-quality/stats'),
  logs: (params?: any) => api.get('/data-quality/logs', { params }),
  updateLog: (id: number, data: any) => api.put(`/data-quality/logs/${id}`, data),
  deleteLog: (id: number) => api.delete(`/data-quality/logs/${id}`),
}

export const biReportApi = {
  listTemplates: () => api.get('/bi-reports/templates'),
  list: () => api.get('/bi-reports'),
  get: (id: number) => api.get(`/bi-reports/${id}`),
  create: (data: any) => api.post('/bi-reports', data),
  update: (id: number, data: any) => api.put(`/bi-reports/${id}`, data),
  delete: (id: number) => api.delete(`/bi-reports/${id}`),
  templates: () => api.get('/bi-reports/templates'),
  seedTemplates: () => api.post('/bi-reports/templates/seed'),
  analyze: (data: any) => api.post('/bi-reports/analyze', data),
  exportReport: (data: any) => api.post('/bi-reports/export', data),
}

export const entityApi = {
  list: () => api.get('/entities'),
  create: (data: any) => api.post('/entities', data),
  update: (id: number, data: any) => api.put(`/entities/${id}`, data),
}

export const ethicsQuizApi = {
  getQuestions: () => api.get('/knowledge/ethics-quiz'),
}

export default api
