/**
 * 目录浏览 Composable
 * 负责目录浏览、路径导航和文件扫描
 */

import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useTemplateStore } from '@/stores'
import * as directoryApi from '@/api/directory'

export function useDirectory() {
  const templateStore = useTemplateStore()
  
  // 状态
  const isBrowsing = ref(false)
  const pathInput = ref('')
  
  // 计算属性
  const currentPath = computed(() => templateStore.currentPath)
  const parentPath = computed(() => templateStore.parentPath)
  const directoryItems = computed(() => templateStore.directoryItems)
  const scanConfig = computed(() => templateStore.scanConfig)
  
  /**
   * 浏览指定路径
   */
  async function browsePath(path: string) {
    const trimmedPath = path.trim()
    if (!trimmedPath) {
      ElMessage.warning('请输入路径')
      return false
    }
    
    isBrowsing.value = true
    try {
      const result = await directoryApi.browseDirectory(trimmedPath)
      templateStore.setDirectory(result.current_path, result.items, result.parent_path)
      pathInput.value = result.current_path
      return true
    } catch (error: any) {
      ElMessage.error(`浏览目录失败: ${error.message}`)
      return false
    } finally {
      isBrowsing.value = false
    }
  }
  
  /**
   * 返回上级目录
   */
  async function goToParent() {
    if (templateStore.parentPath) {
      return await browsePath(templateStore.parentPath)
    }
    return false
  }
  
  /**
   * 设置为图片目录
   */
  function setAsImageDir() {
    if (!templateStore.currentPath) {
      ElMessage.warning('请先浏览到目标目录')
      return false
    }
    
    templateStore.setScanConfig({
      ...templateStore.scanConfig,
      imageDir: templateStore.currentPath
    })
    ElMessage.success('已设置图片目录')
    return true
  }
  
  /**
   * 设置为 JSON 目录
   */
  function setAsJsonDir() {
    if (!templateStore.currentPath) {
      ElMessage.warning('请先浏览到目标目录')
      return false
    }
    
    templateStore.setScanConfig({
      ...templateStore.scanConfig,
      jsonDir: templateStore.currentPath
    })
    ElMessage.success('已设置JSON目录')
    return true
  }
  
  /**
   * 扫描文件对
   */
  async function scanFiles() {
    if (!templateStore.scanConfig.imageDir || !templateStore.scanConfig.jsonDir) {
      ElMessage.warning('请先配置图片目录和JSON目录')
      return null
    }
    
    try {
      const result = await directoryApi.scanDirectory(
        templateStore.scanConfig.imageDir,
        templateStore.scanConfig.jsonDir,
        undefined,
        undefined,
        templateStore.scanConfig.outputDir
      )
      templateStore.setFilePairs(result.pairs)
      ElMessage.success(`扫描完成，找到 ${result.total} 个文件对`)
      return result
    } catch (error: any) {
      ElMessage.error(`扫描失败: ${error.message}`)
      return null
    }
  }
  
  /**
   * 浏览到主目录
   */
  async function browseToHome() {
    return await browsePath('~')
  }
  
  /**
   * 清除路径输入
   */
  function clearPathInput() {
    pathInput.value = ''
  }
  
  return {
    // 状态
    isBrowsing,
    pathInput,
    
    // 计算属性
    currentPath,
    parentPath,
    directoryItems,
    scanConfig,
    
    // 方法
    browsePath,
    goToParent,
    setAsImageDir,
    setAsJsonDir,
    scanFiles,
    browseToHome,
    clearPathInput
  }
}
