<template>
  <div>
    <div v-if="error" class="bg-red-50 border border-red-200 text-red-800 p-4 rounded-md">
      <div class="flex items-start">
        <div class="flex-shrink-0 mt-0.5">
          <svg class="h-5 w-5 text-red-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="ml-3">
          <h3 class="text-sm font-medium">{{ title }}</h3>
          <div class="mt-1 text-sm">
            <p>{{ errorMessage }}</p>
            <button 
              v-if="retry" 
              @click="handleRetry" 
              class="mt-2 px-3 py-1 text-xs font-medium bg-red-100 text-red-800 rounded-md hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
            >
              {{ retryText }}
            </button>
          </div>
        </div>
      </div>
    </div>
    <slot v-else />
  </div>
</template>

<script setup lang="ts">
/**
 * 错误边界组件
 * 用于捕获和显示组件内部错误
 * @prop title - 错误标题
 * @prop error - 错误对象
 * @prop retry - 是否显示重试按钮
 * @prop retryText - 重试按钮文字
 * @emit retry - 点击重试按钮时触发
 */
import { computed } from 'vue';

const props = defineProps({
  title: {
    type: String,
    default: '发生错误'
  },
  error: {
    type: [Error, Object, null],
    default: null
  },
  retry: {
    type: Boolean,
    default: false
  },
  retryText: {
    type: String,
    default: '重试'
  }
});

const emit = defineEmits(['retry']);

/**
 * 格式化错误信息
 */
const errorMessage = computed(() => {
  if (!props.error) return '';
  
  if (props.error instanceof Error) {
    return props.error.message;
  }
  
  if (typeof props.error === 'object') {
    return JSON.stringify(props.error);
  }
  
  return String(props.error);
});

/**
 * 处理重试操作
 */
function handleRetry() {
  emit('retry');
}
</script> 