/**
 * 字典标签覆盖状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getTenantLabelOverrides,
  upsertTenantLabelOverride,
  deleteTenantLabelOverride,
  getPlatformLabelOverrides,
  upsertPlatformLabelOverride,
  deletePlatformLabelOverride
} from '@/api/dictionary/labelOverride'
import { $t } from '@/locales'

export const useLabelOverrideStore = defineStore('labelOverrideStore', () => {
  // ==================== 状态 ====================

  // 1. 租户端覆盖列表
  const tenantOverrides = ref<Api.Dictionary.LabelOverrideDto[]>([])

  // 2. 平台端覆盖列表（按租户 ID 分组）
  const platformOverrides = ref<Api.Dictionary.LabelOverrideDto[]>([])

  // 3. 当前选中的目标租户（平台管理用）
  const selectedTenantId = ref<string | null>(null)

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

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

  // ==================== 计算属性 ====================

  // 1. 按字典项 ID 索引的覆盖配置（方便快速查找）
  const tenantOverrideMap = computed(() => {
    const map: Record<string, Api.Dictionary.LabelOverrideDto> = {}
    tenantOverrides.value.forEach((item) => {
      map[item.dictionaryItemId] = item
    })
    return map
  })

  // 2. 平台覆盖按字典项 ID 索引
  const platformOverrideMap = computed(() => {
    const map: Record<string, Api.Dictionary.LabelOverrideDto> = {}
    platformOverrides.value.forEach((item) => {
      map[item.dictionaryItemId] = item
    })
    return map
  })

  // ==================== 租户端操作 ====================

  /**
   * 获取当前租户的所有标签覆盖
   */
  const fetchTenantOverrides = async () => {
    loading.value = true
    error.value = null

    try {
      const result = await getTenantLabelOverrides()
      tenantOverrides.value = result ?? []
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.loadLabelOverrides')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 租户创建/更新标签覆盖
   */
  const upsertTenantOverrideAction = async (data: Api.Dictionary.UpsertLabelOverrideRequest) => {
    loading.value = true
    error.value = null

    try {
      const result = await upsertTenantLabelOverride(data)

      // 1. 更新本地状态
      const idx = tenantOverrides.value.findIndex(
        (o) => o.dictionaryItemId === data.dictionaryItemId
      )
      if (idx >= 0) {
        tenantOverrides.value[idx] = result
      } else {
        tenantOverrides.value.push(result)
      }

      ElMessage.success($t('common.saveSuccess'))
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.saveLabelOverride')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 租户删除标签覆盖
   */
  const deleteTenantOverrideAction = async (dictionaryItemId: string) => {
    loading.value = true
    error.value = null

    try {
      await deleteTenantLabelOverride(dictionaryItemId)

      // 1. 从本地移除
      tenantOverrides.value = tenantOverrides.value.filter(
        (o) => o.dictionaryItemId !== dictionaryItemId
      )

      ElMessage.success($t('common.deleteSuccess'))
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.deleteLabelOverride')
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  // ==================== 平台端操作 ====================

  /**
   * 设置当前选中的目标租户
   */
  const setSelectedTenant = (tenantId: string | null) => {
    selectedTenantId.value = tenantId
    if (!tenantId) {
      platformOverrides.value = []
    }
  }

  /**
   * 获取指定租户的所有标签覆盖（平台管理员用）
   */
  const fetchPlatformOverrides = async (
    targetTenantId: string,
    overrideType?: Api.Dictionary.OverrideType
  ) => {
    loading.value = true
    error.value = null

    try {
      const result = await getPlatformLabelOverrides(targetTenantId, overrideType)
      platformOverrides.value = result ?? []
      selectedTenantId.value = targetTenantId
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.loadLabelOverrides')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 平台强制覆盖租户字典项的标签
   */
  const upsertPlatformOverrideAction = async (
    targetTenantId: string,
    data: Api.Dictionary.UpsertLabelOverrideRequest
  ) => {
    loading.value = true
    error.value = null

    try {
      const result = await upsertPlatformLabelOverride(targetTenantId, data)

      // 1. 更新本地状态
      const idx = platformOverrides.value.findIndex(
        (o) => o.dictionaryItemId === data.dictionaryItemId
      )
      if (idx >= 0) {
        platformOverrides.value[idx] = result
      } else {
        platformOverrides.value.push(result)
      }

      ElMessage.success($t('common.saveSuccess'))
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.saveLabelOverride')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 平台删除对租户的强制覆盖
   */
  const deletePlatformOverrideAction = async (targetTenantId: string, dictionaryItemId: string) => {
    loading.value = true
    error.value = null

    try {
      await deletePlatformLabelOverride(targetTenantId, dictionaryItemId)

      // 1. 从本地移除
      platformOverrides.value = platformOverrides.value.filter(
        (o) => o.dictionaryItemId !== dictionaryItemId
      )

      ElMessage.success($t('common.deleteSuccess'))
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.deleteLabelOverride')
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  // ==================== 辅助方法 ====================

  /**
   * 清空缓存
   */
  const clearCache = () => {
    tenantOverrides.value = []
    platformOverrides.value = []
    selectedTenantId.value = null
    error.value = null
  }

  /**
   * 检查某个字典项是否已有覆盖（租户端）
   */
  const hasTenantOverride = (dictionaryItemId: string) => {
    return !!tenantOverrideMap.value[dictionaryItemId]
  }

  /**
   * 检查某个字典项是否已有平台覆盖
   */
  const hasPlatformOverride = (dictionaryItemId: string) => {
    return !!platformOverrideMap.value[dictionaryItemId]
  }

  /**
   * 获取字典项的覆盖配置（租户端）
   */
  const getTenantOverride = (dictionaryItemId: string) => {
    return tenantOverrideMap.value[dictionaryItemId] ?? null
  }

  /**
   * 获取字典项的平台覆盖配置
   */
  const getPlatformOverride = (dictionaryItemId: string) => {
    return platformOverrideMap.value[dictionaryItemId] ?? null
  }

  return {
    // 状态
    tenantOverrides,
    platformOverrides,
    selectedTenantId,
    loading,
    error,

    // 计算属性
    tenantOverrideMap,
    platformOverrideMap,

    // 租户端操作
    fetchTenantOverrides,
    upsertTenantOverride: upsertTenantOverrideAction,
    deleteTenantOverride: deleteTenantOverrideAction,

    // 平台端操作
    setSelectedTenant,
    fetchPlatformOverrides,
    upsertPlatformOverride: upsertPlatformOverrideAction,
    deletePlatformOverride: deletePlatformOverrideAction,

    // 辅助方法
    clearCache,
    hasTenantOverride,
    hasPlatformOverride,
    getTenantOverride,
    getPlatformOverride
  }
})
