import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getSkillList, uploadSkill, editSkill, deleteSkill } from '../api/skill'
import { connectSSE, disconnectSSE } from '../utils/sse'

export const useSkillStore = defineStore('skill', () => {
  const skills = ref([])
  const loading = ref(false)
  const uploading = ref(false)
  const uploadProgress = ref(0)

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(12)
  const total = ref(0)
  // 不带过滤条件的全量计数，用于左侧"全部技能"badge 的稳定显示
  const unfilteredTotal = ref(0)
  const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

  // 搜索和筛选状态
  const searchKeyword = ref('')
  const selectedCategoryId = ref(null)

  /**
   * 初始化：建立 SSE 连接 + 加载列表
   */
  function init() {
    connectSSE(onTranslationMessage)
    fetchSkills()
  }

  /**
   * SSE 翻译结果回调 —— 局部更新对应 Skill 的翻译字段
   */
  function onTranslationMessage(msg) {
    const { folderName, translatedDisplayName, translatedDescription } = msg
    const skill = skills.value.find(s => s.folderName === folderName)
    if (skill) {
      skill.translatedDisplayName = translatedDisplayName
      skill.translatedDescription = translatedDescription
    }
  }

  async function fetchSkills() {
    loading.value = true
    try {
      const params = {
        page: currentPage.value,
        size: pageSize.value
      }
      if (searchKeyword.value.trim()) {
        params.search = searchKeyword.value.trim()
      }
      if (selectedCategoryId.value) {
        params.categoryId = selectedCategoryId.value
      }
      const res = await getSkillList(params)
      const data = res.data || {}
      skills.value = data.content || []
      total.value = data.total || 0
      // 无过滤条件时同步更新全量计数
      if (!selectedCategoryId.value && !searchKeyword.value.trim()) {
        unfilteredTotal.value = total.value
      }
    } finally {
      loading.value = false
    }
  }

  async function createSkill(file) {
    uploading.value = true
    uploadProgress.value = 0
    try {
      await uploadSkill(file, (event) => {
        if (event.total) {
          uploadProgress.value = Math.round((event.loaded / event.total) * 100)
        }
      })
      await fetchSkills()
    } finally {
      uploading.value = false
      uploadProgress.value = 0
    }
  }

  async function updateSkill(folderName, data) {
    await editSkill(folderName, data)
    await fetchSkills()
  }

  async function removeSkill(folderName) {
    await deleteSkill(folderName)
    await fetchSkills()
  }

  function setPage(page) {
    currentPage.value = page
    fetchSkills()
  }

  function setSearch(keyword) {
    searchKeyword.value = keyword
    currentPage.value = 1
    fetchSkills()
  }

  function setCategory(categoryId) {
    selectedCategoryId.value = categoryId
    currentPage.value = 1
    fetchSkills()
  }

  /**
   * 销毁时断开 SSE
   */
  function destroy() {
    disconnectSSE()
  }

  return {
    skills,
    loading,
    uploading,
    uploadProgress,
    currentPage,
    pageSize,
    total,
    unfilteredTotal,
    totalPages,
    searchKeyword,
    selectedCategoryId,
    init,
    fetchSkills,
    createSkill,
    updateSkill,
    removeSkill,
    setPage,
    setSearch,
    setCategory,
    destroy
  }
})
