import { defineStore } from 'pinia'
import { taskCenterApi } from '@/api'

export const useTaskCenterStore = defineStore('taskCenter', {
  state: () => ({
    open: false,
    activeTab: 'all',
    listLoading: false,
    detailLoading: false,
    list: [],
    total: 0,
    selectedId: null,
    detail: null,
    runningTotal: 0,
    statusTotals: {
      processing: 0,
      failed: 0,
      pending: 0
    },
    pollTimer: null,
    listPollTimer: null
  }),

  getters: {
    runningCount(state) {
      return state.runningTotal || 0
    }
  },

  actions: {
    /**
     * 任务开始时调用：打开任务中心并显示全部任务
     */
    async notifyTaskStarted({ documentId } = {}) {
      this.open = true
      this.selectedId = null
      this.detail = null
      // 先设置为全部，确保能看到任务
      this.activeTab = 'all'
      
      // 等待一小段时间让后端任务创建完成
      await new Promise(resolve => setTimeout(resolve, 500))
      
      this.fetchRunningCount()
      this.fetchStatusTotals()
      await this.fetchList({ pageNum: 1, pageSize: 20 })
      this.startListPolling()

      // 如果传入了 documentId，尝试选中该任务
      if (documentId) {
        // 再等待一小段时间让任务创建完成
        setTimeout(async () => {
          try {
            const detail = await taskCenterApi.getByDocumentId(documentId)
            if (detail && detail.id) {
              this.selectTask(detail.id)
            }
          } catch (e) {
            console.warn('获取任务详情失败:', e)
          }
        }, 1000)
      }
    },

    toggleOpen() {
      this.open = !this.open
      if (!this.open) {
        this.stopPolling()
        this.stopListPolling()
      } else {
        this.fetchList()
        this.fetchStatusTotals()
        this.startListPolling()
      }
    },

    close() {
      this.open = false
      this.stopPolling()
      this.stopListPolling()
    },

    setActiveTab(tab) {
      this.activeTab = tab || 'all'
    },

    async fetchList({ pageNum = 1, pageSize = 20, silent = false } = {}) {
      if (!silent) {
        this.listLoading = true
      }
      try {
        const params = {
          status: this.activeTab === 'all' ? undefined : this.activeTab,
          pageNum,
          pageSize
        }
        const resp = await taskCenterApi.list(params)
        // resp 是分页对象 { records, total, current, size }
        this.list = resp?.records || []
        this.total = resp?.total || 0
      } catch (e) {
        console.error('获取任务列表失败:', e)
      } finally {
        if (!silent) {
          this.listLoading = false
        }
      }
    },

    async fetchRunningCount() {
      try {
        const resp = await taskCenterApi.list({
          status: 'processing',
          pageNum: 1,
          pageSize: 1
        })
        this.runningTotal = resp?.total || 0
      } catch (e) {
        // 失败不影响主流程
      }
    },

    async fetchStatusTotals() {
      try {
        const stats = await taskCenterApi.getStatistics()
        this.statusTotals = {
          processing: stats?.processing || 0,
          failed: stats?.failed || 0,
          pending: stats?.pending || 0
        }
      } catch (e) {
        // 统计失败不影响主流程
      }
    },

    async selectTask(taskId) {
      if (!taskId) return
      this.selectedId = taskId
      await this.fetchDetail(taskId)
      this.maybeStartPolling()
    },

    async fetchDetail(taskId, silent = false) {
      if (!silent) {
        this.detailLoading = true
      }
      try {
        const resp = await taskCenterApi.getById(taskId)
        this.detail = resp
      } catch (e) {
        console.error('获取任务详情失败:', e)
      } finally {
        if (!silent) {
          this.detailLoading = false
        }
      }
    },

    maybeStartPolling() {
      this.stopPolling()
      if (!this.open) return
      const status = this.detail?.status
      if (status !== 'processing') return

      this.pollTimer = setInterval(async () => {
        if (!this.selectedId) return
        try {
          await this.fetchDetail(this.selectedId, true)
          const s = this.detail?.status
          if (s === 'completed' || s === 'failed') {
            // 任务结束后刷新列表和统计
            await this.fetchList({ pageNum: 1, pageSize: 20, silent: true })
            this.fetchRunningCount()
            this.fetchStatusTotals()
            this.stopPolling()
          }
        } catch (e) {
          // 轮询异常不停止
        }
      }, 3000)
    },

    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
    },

    startListPolling(intervalMs = 5000) {
      this.stopListPolling()
      if (!this.open) return

      this.listPollTimer = setInterval(async () => {
        if (!this.open) {
          this.stopListPolling()
          return
        }
        try {
          await this.fetchList({ pageNum: 1, pageSize: 20, silent: true })
          this.fetchStatusTotals()
        } catch (e) {
          // 轮询异常不停止
        }
      }, intervalMs)
    },

    stopListPolling() {
      if (this.listPollTimer) {
        clearInterval(this.listPollTimer)
        this.listPollTimer = null
      }
    },

    async deleteTask(taskId) {
      try {
        await taskCenterApi.delete(taskId)
        // 如果删除的是当前选中的任务，清除选中状态
        if (this.selectedId === taskId) {
          this.selectedId = null
          this.detail = null
        }
        // 刷新列表和统计
        await this.fetchList()
        this.fetchRunningCount()
        this.fetchStatusTotals()
        return true
      } catch (e) {
        throw e
      }
    }
  }
})
