<template>
  <div class="finance-container">
    <h1>金融服务</h1>
    <div v-if="loading" class="loading-indicator">数据加载中...</div>
    <div v-if="error" class="error-message">数据加载失败，请稍后重试。</div>
    <div v-if="!loading && !error">
      <div class="loan-section">
        <h3>贷款数据</h3>
        <div class="chart-container">
          <div id="loan-chart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      <div class="insurance-section">
        <h3>保险数据</h3>
        <div class="chart-container">
          <div id="insurance-chart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  setup() {
    const loanData = ref([]);
    const insuranceData = ref([]);
    const loading = ref(true);
    const error = ref(false);

    const fetchData = async () => {
      try {
        loading.value = true;
        error.value = false;
        const [loanResponse, insuranceResponse] = await Promise.all([
          axios.get('/api/loan-data'),
          axios.get('/api/insurance-data')
        ]);
        loanData.value = loanResponse.data;
        insuranceData.value = insuranceResponse.data;
        renderCharts();
      } catch (err) {
        error.value = true;
        console.error('获取数据失败:', err);
      } finally {
        loading.value = false;
      }
    };

    const renderCharts = () => {
      const loanChart = echarts.init(document.getElementById('loan-chart'));
      loanChart.setOption({
        tooltip: {},
        xAxis: { data: loanData.value.map(item => item.month) },
        yAxis: {},
        series: [{ type: 'bar', data: loanData.value.map(item => item.value) }]
      });

      const insuranceChart = echarts.init(document.getElementById('insurance-chart'));
      insuranceChart.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          data: insuranceData.value.map(item => item)
        }]
      });
    };

    onMounted(() => {
      fetchData();
    });

    return {
      loanData,
      insuranceData,
      loading,
      error
    };
  }
};
</script>

<style scoped>
.finance-container {
  padding: 20px;
}

.loan-section,
.insurance-section {
  margin-bottom: 20px;
}

.chart-container {
  background: white;
  border-radius: 4px;
  padding: 10px;
}

.loading-indicator,
.error-message {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #666;
}

.error-message {
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .loan-section,
  .insurance-section {
    margin-bottom: 15px;
  }

  .chart-container {
    padding: 5px;
  }

  #loan-chart,
  #insurance-chart {
    height: 250px;
  }
}
</style>