<script setup lang="ts">
import type { MateChatConfig, MateChatConfigs } from '@af-mobile-client-vue3/components/common/MateChat/types'
import MateChatContent from '@af-mobile-client-vue3/components/common/MateChat/components/MateChatContent.vue'
import PasswordDialog from '@af-mobile-client-vue3/components/common/MateChat/components/PasswordDialog.vue'
import { usePasswordManager } from '@af-mobile-client-vue3/components/common/MateChat/composables/usePasswordManager'
import { getConfigByNameAsync } from '@af-mobile-client-vue3/services/api/common'
// MateChat ai 对话相关
import { showFailToast, Button as VanButton, Icon as VanIcon, Loading as VanLoading } from 'vant'
import { computed, onMounted, ref } from 'vue'

interface MateChatProps {
  /**
   * 配置名称，用于从配置中心获取配置
   */
  configName: string
  /**
   * 服务名
   */
  serviceName?: string
}

const props = defineProps<MateChatProps>()

// 使用密码管理 composable
const { getStoredPassword, savePassword, clearPassword } = usePasswordManager()

// 配置加载状态
const isLoading = ref(true)
const configError = ref<string | null>(null)
const showPasswordDialog = ref(false)
const passwordDialogRef = ref<InstanceType<typeof PasswordDialog> | null>(null)

// 临时变量：强制保持 loading 状态（用于调整 loading 样式）
// 设置为 true 时，组件将始终保持 loading 状态
const forceLoading = ref(false)

// 计算最终的 loading 状态
// 当有错误时也应该保持 loading 状态（显示错误信息），而不是显示对话页面
const finalLoading = computed(() => forceLoading.value || isLoading.value || !!configError.value)

// 当前使用的配置
const currentConfig = ref<MateChatConfig | null>(null)

const defaultBackgroundGradient = 'background: linear-gradient(to bottom, #d0c9ff 0%, #e6d6f0 8%, #f1dbea 12%, #c8dcfb 40%, #abc6f6 60%, #87aefe 90%)'
// 琉璃配色
// background: linear-gradient(to bottom, #a8f0ed 0%, #a8e6cf 8%, #c5b3ff 12%, #e0b3ff 40%, #fff4b8 60%, #ffb8d1 90%);
// 紫罗兰配色
// background: linear-gradient(to bottom, #d0c9ff 0%, #e6d6f0 8%, #f1dbea 12%, #c8dcfb 40%, #abc6f6 60%, #87aefe 90%);
// 蓝白配色
// 'linear-gradient(to bottom, #1c57e0 0%, #3b82f6 20%, #60a5fa 40%, #93c5fd 60%, #dbeafe 80%, #ffffff 100%)'
// 计算背景渐变样式
const backgroundStyle = computed(() => {
  const gradient = currentConfig.value?.backgroundGradient || defaultBackgroundGradient
  return {
    background: gradient,
  }
})

// 存储原始配置数据
const rawConfigs = ref<MateChatConfigs | MateChatConfig | null>(null)

/**
 * 检查配置对象中是否有密码保护的配置
 */
function hasPasswordProtectedConfig(configs: MateChatConfigs | MateChatConfig | null): boolean {
  if (!configs) {
    return false
  }
  if (Array.isArray(configs)) {
    return configs.some(config => !!config.password)
  }
  if (typeof configs === 'object' && configs !== null) {
    // 如果是配置对象集合
    return Object.values(configs).some((config) => {
      if (typeof config === 'object' && config !== null && 'password' in config) {
        return !!config.password
      }
      return false
    })
  }
  // 单个配置对象
  return !!(configs as MateChatConfig).password
}

/**
 * 根据密码匹配配置
 */
function findConfigByPassword(
  configs: MateChatConfigs | MateChatConfig | null,
  password: string,
): MateChatConfig | null {
  if (!configs) {
    return null
  }
  if (typeof configs === 'object' && configs !== null) {
    // 如果是配置对象集合（MateChatConfigs）
    if (props.configName in configs) {
      const targetConfig = (configs as MateChatConfigs)[props.configName]
      if (targetConfig && targetConfig.password === password) {
        return targetConfig
      }
    }
    // 遍历所有配置查找匹配的密码
    for (const config of Object.values(configs)) {
      if (typeof config === 'object' && config !== null && 'password' in config) {
        if (config.password === password) {
          return config as MateChatConfig
        }
      }
    }
  }
  // 单个配置对象
  const singleConfig = configs as MateChatConfig
  if (singleConfig && singleConfig.password === password) {
    return singleConfig
  }
  return null
}

/**
 * 获取配置（无密码保护时）
 */
function getConfigWithoutPassword(
  configs: MateChatConfigs | MateChatConfig | null,
): MateChatConfig | null {
  if (!configs) {
    return null
  }
  if (typeof configs === 'object' && configs !== null) {
    // 如果是配置对象集合，根据 configName 获取
    if (props.configName in configs) {
      return (configs as MateChatConfigs)[props.configName]
    }
    // 如果没有找到，返回第一个配置
    const firstConfig = Object.values(configs)[0]
    if (firstConfig && typeof firstConfig === 'object' && 'appId' in firstConfig) {
      return firstConfig as MateChatConfig
    }
  }
  // 单个配置对象，直接返回
  return configs as MateChatConfig
}

/**
 * 处理密码确认
 */
function handlePasswordConfirm(password: string) {
  if (!rawConfigs.value) {
    showFailToast('配置数据异常')
    return
  }

  const matchedConfig = findConfigByPassword(rawConfigs.value, password)
  if (matchedConfig) {
    // 验证配置的有效性
    if (!validateConfig(matchedConfig)) {
      configError.value = '配置不完整，请联系管理员检查配置'
      showPasswordDialog.value = false
      isLoading.value = false
      return
    }
    // 验证成功，保存密码
    savePassword(password)
    currentConfig.value = matchedConfig
    showPasswordDialog.value = false
    isLoading.value = false
  }
  else {
    // 验证失败，清除保存的密码
    clearPassword()
    // 清空输入框并显示错误，保持对话框打开
    passwordDialogRef.value?.clearPassword()
    passwordDialogRef.value?.setError('密码错误，请重新输入')
  }
}

/**
 * 处理密码取消
 */
function handlePasswordCancel() {
  // 取消时保持 loading 状态，不加载配置
  showPasswordDialog.value = false
}

/**
 * 验证配置的有效性
 * @param config 配置对象
 * @returns 如果配置有效返回 true，否则返回 false
 */
function validateConfig(config: MateChatConfig | null): boolean {
  if (!config) {
    return false
  }

  // 检查必需的字段
  if (!config.appId || typeof config.appId !== 'string' || config.appId.trim() === '') {
    return false
  }

  if (!config.appKey || typeof config.appKey !== 'string' || config.appKey.trim() === '') {
    return false
  }

  return true
}

/**
 * 获取友好的错误提示信息
 */
function getFriendlyErrorMessage(error: string | null): string {
  if (!error) {
    return '加载配置失败，请稍后再试'
  }

  // 根据错误信息返回更友好的提示
  if (error.includes('未找到') || error.includes('资源')) {
    return '未找到相关配置，请联系管理员'
  }

  if (error.includes('网络') || error.includes('请求')) {
    return '网络连接异常，请检查网络后重试'
  }

  if (error.includes('超时')) {
    return '请求超时，请稍后重试'
  }

  // 默认返回原始错误信息，但可以稍作优化
  return error.length > 50 ? `${error.substring(0, 50)}...` : error
}

/**
 * 处理重试
 */
function handleRetry() {
  loadConfig()
}

/**
 * 加载配置
 */
async function loadConfig() {
  try {
    isLoading.value = true
    configError.value = null

    const configs = await getConfigByNameAsync(props.configName, props.serviceName)

    // 检查配置是否为空或无效
    if (!configs) {
      configError.value = '未找到有效配置'
      isLoading.value = false
      return
    }

    rawConfigs.value = configs

    // 检查是否有密码保护的配置
    if (hasPasswordProtectedConfig(configs)) {
      // 尝试从 localStorage 读取保存的密码
      const storedPassword = getStoredPassword()
      if (storedPassword) {
        // 自动验证保存的密码
        const matchedConfig = findConfigByPassword(configs, storedPassword)
        if (matchedConfig) {
          // 验证配置的有效性
          if (validateConfig(matchedConfig)) {
            // 验证成功，直接加载配置
            currentConfig.value = matchedConfig
            isLoading.value = false
            return
          }
          else {
            // 配置无效，清除密码并显示对话框
            clearPassword()
            showPasswordDialog.value = true
            return
          }
        }
        else {
          // 密码不匹配，清除保存的密码并显示对话框
          clearPassword()
          showPasswordDialog.value = true
          return
        }
      }
      // 没有保存的密码，显示密码输入对话框
      showPasswordDialog.value = true
      // 保持 loading 状态，等待密码验证
      return
    }

    // 没有密码保护，直接加载配置
    const config = getConfigWithoutPassword(configs)
    if (config) {
      // 验证配置的有效性
      if (!validateConfig(config)) {
        configError.value = '配置不完整，请联系管理员检查配置'
        isLoading.value = false
        return
      }
      currentConfig.value = config
      isLoading.value = false
    }
    else {
      configError.value = '未找到有效配置'
      isLoading.value = false
    }
  }
  catch (error: any) {
    console.error('加载配置失败:', error)
    configError.value = error?.message || '加载配置失败，请稍后再试'
    isLoading.value = false
  }
}

onMounted(() => {
  loadConfig()
})
</script>

<template>
  <div id="mate-chat-view" :style="backgroundStyle">
    <!-- 密码输入对话框 -->
    <PasswordDialog
      ref="passwordDialogRef"
      :visible="showPasswordDialog"
      @confirm="handlePasswordConfirm"
      @cancel="handlePasswordCancel"
    />
    <!-- Loading 状态 -->
    <div v-if="finalLoading" class="loading-container">
      <div v-if="configError" class="error-container">
        <VanIcon name="warning-o" size="48" class="error-icon" />
        <div class="error-title">
          抱歉，加载失败
        </div>
        <div class="error-message">
          {{ getFriendlyErrorMessage(configError) }}
        </div>
        <VanButton
          type="primary"
          size="small"
          class="retry-button"
          @click="handleRetry"
        >
          重试
        </VanButton>
      </div>
      <VanLoading v-else vertical>
        <template #icon>
          <VanIcon name="star-o" size="30" />
        </template>
        加载中...
      </VanLoading>
    </div>
    <!-- 对话内容 -->
    <MateChatContent
      v-else-if="currentConfig"
      :config="currentConfig"
    />
  </div>
</template>

<style scoped lang="less">
#mate-chat-view {
  /* 外层渐变背景容器 */
  width: 100%;
  height: 100%;
  min-height: 100%;
  /* 背景色通过 :style 绑定从配置中获取 */
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  box-sizing: border-box;

  /* 移动端适配 */
  @media (max-width: 768px) {
    padding: 8px;
  }

  .loading-container {
    width: 100%;
    max-width: 1200px;
    height: calc(100vh - 40px);
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    padding: 20px;
    box-sizing: border-box;

    /* 移动端适配 */
    @media (max-width: 768px) {
      height: calc(100% - 18px);
      border-radius: 16px;
      padding: 8px;
    }

    .loading-message {
      font-size: 14px;
      color: #71757f;
      text-align: center;
    }

    .error-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 24px;
      text-align: center;

      .error-icon {
        color: #ff9800;
        margin-bottom: 16px;
      }

      .error-title {
        font-size: 16px;
        font-weight: 500;
        color: #323233;
        margin-bottom: 8px;
      }

      .error-message {
        font-size: 14px;
        color: #969799;
        line-height: 1.5;
        margin-bottom: 24px;
        max-width: 280px;
      }

      .retry-button {
        min-width: 100px;
      }
    }
  }
}
</style>
