import { defineStore } from 'pinia'
import { adminAPI } from '@/services/admin'
import { ElMessage } from 'element-plus'

export const useAdminStore = defineStore('admin', {
  state: () => ({
    stats: null,
    users: [],
    allJobs: [],
    systemLogs: [],
    apiUsageStats: [],
    costReport: null,
    systemHealth: null,
    systemMetrics: null,
    loading: false,
    pagination: {
      page: 1,
      per_page: 50,
      total: 0,
      pages: 0
    }
  }),
  
  getters: {
    // 系統概覽統計
    overviewStats: (state) => state.stats?.overview || {},
    
    // 每日統計資料
    dailyStats: (state) => state.stats?.daily_stats || [],
    
    // 使用者排名
    userRankings: (state) => state.stats?.user_rankings || [],
    
    // 活躍使用者數量
    activeUsersCount: (state) => state.stats?.overview?.active_users_today || 0,
    
    // 總成本
    totalCost: (state) => state.stats?.overview?.total_cost || 0,
    
    // 系統是否健康
    isSystemHealthy: (state) => state.systemHealth?.status === 'healthy'
  },
  
  actions: {
    /**
     * 取得系統統計資訊
     * @param {string} period - 統計週期
     */
    async fetchStats(period = 'month') {
      try {
        this.loading = true
        
        const response = await adminAPI.getStats(period)
        
        if (response.success) {
          this.stats = response.data
          return response.data
        }
      } catch (error) {
        console.error('取得統計資訊失敗:', error)
        ElMessage.error('載入統計資訊失敗')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 取得所有使用者任務
     * @param {Object} params - 查詢參數
     */
    async fetchAllJobs(params = {}) {
      try {
        this.loading = true
        
        const response = await adminAPI.getAllJobs(params)
        
        if (response.success) {
          this.allJobs = response.data.jobs
          this.pagination = response.data.pagination
          return response.data
        }
      } catch (error) {
        console.error('取得所有任務失敗:', error)
        ElMessage.error('載入任務資料失敗')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 取得使用者列表
     */
    async fetchUsers() {
      try {
        const response = await adminAPI.getUsers()
        
        if (response.success) {
          this.users = response.data.users
          return response.data
        }
      } catch (error) {
        console.error('取得使用者列表失敗:', error)
        ElMessage.error('載入使用者資料失敗')
      }
    },
    
    /**
     * 更新使用者狀態
     * @param {number} userId - 使用者 ID
     * @param {Object} data - 更新資料
     */
    async updateUser(userId, data) {
      try {
        const response = await adminAPI.updateUser(userId, data)
        
        if (response.success) {
          // 更新本地使用者資料
          const userIndex = this.users.findIndex(user => user.id === userId)
          if (userIndex !== -1) {
            this.users[userIndex] = { ...this.users[userIndex], ...response.data }
          }
          
          ElMessage.success('使用者資料更新成功')
          return response.data
        }
      } catch (error) {
        console.error('更新使用者失敗:', error)
        ElMessage.error('更新使用者失敗')
      }
    },
    
    /**
     * 取得 API 使用統計
     * @param {Object} params - 查詢參數
     */
    async fetchApiUsageStats(params = {}) {
      try {
        const response = await adminAPI.getApiUsageStats(params)
        
        if (response.success) {
          this.apiUsageStats = response.data.stats
          return response.data
        }
      } catch (error) {
        console.error('取得 API 使用統計失敗:', error)
        ElMessage.error('載入 API 統計失敗')
      }
    },
    
    /**
     * 取得系統日誌
     * @param {Object} params - 查詢參數
     */
    async fetchSystemLogs(params = {}) {
      try {
        this.loading = true
        
        const response = await adminAPI.getSystemLogs(params)
        
        if (response.success) {
          this.systemLogs = response.data.logs
          return response.data
        }
      } catch (error) {
        console.error('取得系統日誌失敗:', error)
        ElMessage.error('載入系統日誌失敗')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 取得成本報表
     * @param {Object} params - 查詢參數
     */
    async fetchCostReport(params = {}) {
      try {
        const response = await adminAPI.getCostReport(params)
        
        if (response.success) {
          this.costReport = response.data
          return response.data
        }
      } catch (error) {
        console.error('取得成本報表失敗:', error)
        ElMessage.error('載入成本報表失敗')
      }
    },
    
    /**
     * 匯出報表
     * @param {string} type - 報表類型
     * @param {Object} params - 查詢參數
     */
    async exportReport(type, params = {}) {
      try {
        const response = await adminAPI.exportReport(type, params)
        
        // 下載檔案
        const blob = new Blob([response], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${type}_report_${new Date().toISOString().slice(0, 10)}.xlsx`
        link.click()
        
        window.URL.revokeObjectURL(url)
        ElMessage.success('報表匯出成功')
      } catch (error) {
        console.error('匯出報表失敗:', error)
        ElMessage.error('匯出報表失敗')
      }
    },
    
    /**
     * 取得系統健康狀態
     */
    async fetchSystemHealth() {
      try {
        const response = await adminAPI.getSystemHealth()
        this.systemHealth = response
        return response
      } catch (error) {
        console.error('取得系統健康狀態失敗:', error)
        this.systemHealth = { status: 'unhealthy' }
      }
    },
    
    /**
     * 取得系統指標
     */
    async fetchSystemMetrics() {
      try {
        const response = await adminAPI.getSystemMetrics()
        
        if (response.success || response.jobs) {
          this.systemMetrics = response
          return response
        }
      } catch (error) {
        console.error('取得系統指標失敗:', error)
      }
    },
    
    /**
     * 清理舊檔案
     */
    async cleanupOldFiles() {
      try {
        const response = await adminAPI.cleanupOldFiles()
        
        if (response.success) {
          ElMessage.success('檔案清理完成')
          return response.data
        }
      } catch (error) {
        console.error('清理檔案失敗:', error)
        ElMessage.error('清理檔案失敗')
      }
    },
    
    /**
     * 重置管理員資料
     */
    resetAdminData() {
      this.stats = null
      this.users = []
      this.allJobs = []
      this.systemLogs = []
      this.apiUsageStats = []
      this.costReport = null
      this.systemHealth = null
      this.systemMetrics = null
    }
  }
})