/**
 * 字段配置管理Composable
 * 用于加载和缓存设备类型的字段配置
 */

import { ref } from 'vue'
import type { FieldConfig } from '@/types/form'
import request from '@/utils/request'

/**
 * 字段配置管理Hook
 */
export function useFieldConfig() {
  // 字段配置缓存
  const fieldConfigs = ref<Record<string | number, FieldConfig[]>>({})

  // 加载状态
  const loading = ref(false)

  // 错误信息
  const error = ref<string | null>(null)

  /**
   * 从API加载字段配置
   * @param deviceTypeId 设备类型ID
   */
  const loadFieldConfig = async (deviceTypeId: string | number): Promise<FieldConfig[]> => {
    // 检查缓存
    const cached = getCachedFieldConfig(deviceTypeId)
    if (cached) {
      return cached
    }

    loading.value = true
    error.value = null

    try {
      // 调用API获取字段配置
      const response = await request({
        url: `/device-types/${deviceTypeId}/fields`,
        method: 'get'
      })

      // 转换API字段配置为前端字段配置
      const fields = transformApiFieldsToFieldConfigs(response)

      // 缓存字段配置
      fieldConfigs.value[deviceTypeId] = fields

      return fields
    } catch (err: any) {
      error.value = err.message || '加载字段配置失败'
      console.error('加载字段配置失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 从缓存获取字段配置
   * @param deviceTypeId 设备类型ID
   */
  const getCachedFieldConfig = (deviceTypeId: string | number): FieldConfig[] | null => {
    return fieldConfigs.value[deviceTypeId] || null
  }

  /**
   * 批量加载字段配置
   * @param deviceTypeIds 设备类型ID列表
   */
  const loadFieldConfigs = async (deviceTypeIds: Array<string | number>): Promise<void> => {
    const promises = deviceTypeIds.map((id) => loadFieldConfig(id))
    await Promise.all(promises)
  }

  /**
   * 清除缓存
   * @param deviceTypeId 设备类型ID（不传则清除所有缓存）
   */
  const clearCache = (deviceTypeId?: string | number) => {
    if (deviceTypeId) {
      delete fieldConfigs.value[deviceTypeId]
    } else {
      fieldConfigs.value = {}
    }
  }

  /**
   * 设置字段配置（用于手动设置）
   * @param deviceTypeId 设备类型ID
   * @param fields 字段配置
   */
  const setFieldConfig = (deviceTypeId: string | number, fields: FieldConfig[]) => {
    fieldConfigs.value[deviceTypeId] = fields
  }

  /**
   * 转换API字段配置为前端字段配置
   */
  const transformApiFieldsToFieldConfigs = (apiFields: any[]): FieldConfig[] => {
    return apiFields.map((apiField) => ({
      id: String(apiField.id),
      name: apiField.fieldCode,
      label: apiField.fieldName,
      fieldType: transformFieldType(apiField.fieldType),
      required: apiField.isRequired || false,
      placeholder: apiField.placeholder,
      options: apiField.options || [],
      validationRules: transformValidationRules(apiField.validationRules),
      defaultValue: apiField.defaultValue,
      span: 24, // 默认占满一行
      description: apiField.description
    }))
  }

  /**
   * 转换字段类型
   */
  const transformFieldType = (apiType: string): FieldConfig['fieldType'] => {
    const typeMap: Record<string, FieldConfig['fieldType']> = {
      text: 'text',
      textarea: 'textarea',
      number: 'number',
      date: 'date',
      select: 'select',
      multiselect: 'multiselect',
      checkbox: 'boolean',
      boolean: 'boolean',
      url: 'url',
      email: 'email',
      phone: 'phone'
    }

    return typeMap[apiType] || 'text'
  }

  /**
   * 转换验证规则
   */
  const transformValidationRules = (apiRules?: any) => {
    if (!apiRules) return undefined

    return {
      min: apiRules.min_length || apiRules.min,
      max: apiRules.max_length || apiRules.max,
      pattern: apiRules.pattern
    }
  }

  return {
    // 状态
    fieldConfigs,
    loading,
    error,

    // 方法
    loadFieldConfig,
    loadFieldConfigs,
    getCachedFieldConfig,
    setFieldConfig,
    clearCache
  }
}

/**
 * 全局字段配置管理单例
 */
let globalFieldConfigInstance: ReturnType<typeof useFieldConfig> | null = null

/**
 * 获取全局字段配置管理实例
 */
export function getGlobalFieldConfigManager() {
  if (!globalFieldConfigInstance) {
    globalFieldConfigInstance = useFieldConfig()
  }
  return globalFieldConfigInstance
}
