<template>
  <div class="error-boundary">
    <div v-if="hasError" class="error-content">
      <div class="error-icon">
        <el-icon size="64" color="#F56C6C">
          <Warning />
        </el-icon>
      </div>
      <div class="error-text">
        <h3>{{ title || '出现错误' }}</h3>
        <p>{{ message || '应用程序遇到了意外错误' }}</p>
        <el-button type="primary" @click="handleRetry" v-if="retryable">
          重试
        </el-button>
        <el-button @click="$router.push('/')">
          返回首页
        </el-button>
      </div>
    </div>
    <slot v-else />
  </div>
</template>

<script>
import { ref } from 'vue'
import { Warning } from '@element-plus/icons-vue'

export default {
  name: 'ErrorBoundary',
  components: {
    Warning
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    message: {
      type: String,
      default: ''
    },
    retryable: {
      type: Boolean,
      default: true
    }
  },
  setup(props, { emit }) {
    const hasError = ref(false)
    const errorMessage = ref('')
    
    const handleRetry = () => {
      hasError.value = false
      errorMessage.value = ''
      emit('retry')
    }
    
    const errorCaptured = (err, vm, info) => {
      hasError.value = true
      errorMessage.value = err.message
      console.error('Error caught by error boundary:', err, info)
      // 防止错误继续向上传播
      return false
    }
    
    return {
      hasError,
      errorMessage,
      handleRetry,
      errorCaptured
    }
  }
}
</script>

<style scoped>
.error-boundary {
  width: 100%;
}

.error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.error-icon {
  margin-bottom: 20px;
}

.error-text h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-weight: 500;
}

.error-text p {
  margin: 0 0 30px 0;
  color: #909399;
  max-width: 500px;
}

.error-text .el-button {
  margin: 0 6px;
}
</style>