<template>
  <div class="dashboard">
    <a-page-header
      title="仪表板"
      sub-title="系统概览和统计数据"
    />

    <!-- 统计卡片 -->
    <a-row :gutter="16" style="margin-top: 24px">
      <a-col :span="6">
        <a-card>
          <div class="stat-card">
            <user-outlined style="color: #1890ff; font-size: 24px" />
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalUsers || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <div class="stat-card">
            <insurance-outlined style="color: #52c41a; font-size: 24px" />
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalApplications || 0 }}</div>
              <div class="stat-label">保险申请</div>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <div class="stat-card">
            <file-done-outlined style="color: #faad14; font-size: 24px" />
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalPolicies || 0 }}</div>
              <div class="stat-label">有效保单</div>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <div class="stat-card">
            <safety-certificate-outlined style="color: #f5222d; font-size: 24px" />
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalClaims || 0 }}</div>
              <div class="stat-label">理赔申请</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="16" style="margin-top: 24px">
      <a-col :span="12">
        <a-card title="申请状态分布" :bordered="false">
          <div style="height: 300px">
            <v-chart 
              :option="applicationTrendOption" 
              style="height: 100%; width: 100%"
              :loading="chartLoading"
            />
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="12">
        <a-card title="险种分布" :bordered="false">
          <div style="height: 300px">
            <v-chart 
              :option="policyDistributionOption" 
              style="height: 100%; width: 100%"
              :loading="chartLoading"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 最近活动 -->
    <a-card title="最近活动" style="margin-top: 24px">
      <a-list
        item-layout="horizontal"
        :data-source="recentActivities"
        :loading="loading"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta
              :description="item.description"
            >
              <template #title>
                <span :style="{ color: getActivityColor(item.type) }">{{ item.title }}</span>
              </template>
              <template #avatar>
                <a-avatar :style="{ backgroundColor: getActivityColor(item.type) }">
                  {{ getActivityIcon(item.type) }}
                </a-avatar>
              </template>
            </a-list-item-meta>
            <div>{{ formatTime(item.created_at) }}</div>
          </a-list-item>
        </template>
      </a-list>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  UserOutlined,
  InsuranceOutlined,
  FileDoneOutlined,
  SafetyCertificateOutlined,
  BarChartOutlined,
  PieChartOutlined
} from '@ant-design/icons-vue'
import { dashboardAPI, policyAPI, insuranceTypeAPI, applicationAPI } from '@/utils/api'
import { message } from 'ant-design-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册必要的组件
use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const loading = ref(false)
const chartLoading = ref(false)
const stats = ref({})
const recentActivities = ref([])
const applicationTrendOption = ref({})
const policyDistributionOption = ref({})

const getActivityColor = (type) => {
  const colors = {
    user: '#1890ff',
    application: '#52c41a',
    policy: '#faad14',
    claim: '#f5222d'
  }
  return colors[type] || '#666'
}

const getActivityIcon = (type) => {
  const icons = {
    user: 'U',
    application: 'A',
    policy: 'P',
    claim: 'C'
  }
  return icons[type] || '?'
}

const formatTime = (time) => {
  return new Date(time).toLocaleString()
}

const getLogType = (message) => {
  if (message.includes('用户') || message.includes('注册') || message.includes('登录')) {
    return 'user'
  } else if (message.includes('申请') || message.includes('投保')) {
    return 'application'
  } else if (message.includes('保单') || message.includes('合同')) {
    return 'policy'
  } else if (message.includes('理赔') || message.includes('赔偿')) {
    return 'claim'
  }
  return 'system'
}

const getLogTitle = (level, message) => {
  if (level === 'info') {
    if (message.includes('启动') || message.includes('连接')) {
      return '系统操作'
    }
    return '信息通知'
  } else if (level === 'warning') {
    return '警告信息'
  } else if (level === 'error') {
    return '错误报告'
  }
  return '系统消息'
}

const loadDashboardData = async () => {
  loading.value = true
  try {
    // 获取统计信息
    const statsResponse = await dashboardAPI.getStats()
    console.log('统计数据响应:', statsResponse)
    if (statsResponse.data && statsResponse.data.status === 'success') {
      stats.value = {
        totalUsers: statsResponse.data.data.totalUsers || 0,
        totalApplications: statsResponse.data.data.totalApplications || 0,
        totalPolicies: statsResponse.data.data.totalPolicies || 0,
        totalClaims: statsResponse.data.data.totalClaims || 0
      }
      console.log('统计数据设置成功:', stats.value)
    } else {
      console.log('统计数据响应格式错误:', statsResponse)
    }
    
    // 获取最近活动
    const activitiesResponse = await dashboardAPI.getRecentActivities()
    console.log('最近活动响应:', activitiesResponse)
    if (activitiesResponse.data && activitiesResponse.data.status === 'success') {
      recentActivities.value = activitiesResponse.data.data.map(activity => ({
        id: activity.id,
        type: getLogType(activity.type),
        title: activity.title,
        description: activity.description,
        created_at: activity.timestamp || new Date().toISOString()
      })) || []
      console.log('最近活动设置成功:', recentActivities.value)
    } else {
      console.log('最近活动响应格式错误:', activitiesResponse)
    }
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    message.error('加载数据失败')
    
    // 如果API调用失败，使用模拟数据
    stats.value = {
      totalUsers: 128,
      totalApplications: 356,
      totalPolicies: 289,
      totalClaims: 45
    }
    
    recentActivities.value = [
      {
        id: 1,
        type: 'application',
        title: '新的保险申请',
        description: '张三提交了车险申请',
        created_at: new Date().toISOString()
      },
      {
        id: 2,
        type: 'policy',
        title: '保单生效',
        description: '李四的寿险保单已生效',
        created_at: new Date(Date.now() - 3600000).toISOString()
      },
      {
        id: 3,
        type: 'claim',
        title: '理赔申请',
        description: '王五提交了医疗险理赔',
        created_at: new Date(Date.now() - 7200000).toISOString()
      },
      {
        id: 4,
        type: 'user',
        title: '新用户注册',
        description: '新用户赵六完成注册',
        created_at: new Date(Date.now() - 10800000).toISOString()
      }
    ]
  } finally {
    loading.value = false
  }
  
  // 无论统计数据和活动数据是否成功，都要加载图表数据
  await loadChartData()
}

// 加载图表数据
const loadChartData = async () => {
  console.log('开始加载图表数据...')
  chartLoading.value = true
  
  // 独立加载申请状态分布数据
  try {
    console.log('正在获取申请状态分布数据...')
    const applicationsResponse = await applicationAPI.getList({
      page: 1,
      limit: 100 // 获取所有申请用于状态统计
    })
    
    console.log('申请状态分布响应:', applicationsResponse)
    if (applicationsResponse.data && applicationsResponse.data.status === 'success') {
      console.log('设置申请状态分布图表，数据:', applicationsResponse.data.data)
      setupApplicationStatusChart(applicationsResponse.data.data)
    } else {
      console.log('申请状态分布响应格式错误:', applicationsResponse)
    }
  } catch (error) {
    console.error('加载申请状态分布数据失败:', error)
  }
  
  // 独立加载险种分布数据
  try {
    console.log('正在获取险种分布数据...')
    const insuranceTypesResponse = await insuranceTypeAPI.getList({
      page: 1,
      pageSize: 100, // 获取所有险种用于分布统计
      name: ''
    })
    
    console.log('险种分布响应:', insuranceTypesResponse)
    if (insuranceTypesResponse.data && insuranceTypesResponse.data.status === 'success') {
      console.log('设置险种分布图表，数据:', insuranceTypesResponse.data.data)
      setupInsuranceTypeDistributionChart(insuranceTypesResponse.data.data)
    } else {
      console.log('险种分布响应格式错误:', insuranceTypesResponse)
    }
  } catch (error) {
    console.error('加载险种分布数据失败:', error)
    message.error('加载险种分布数据失败')
  }
  
  chartLoading.value = false
  console.log('图表数据加载完成')
}

// 创建饼图配置的通用函数
const createPieChartOption = (seriesName, data) => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        color: '#666',
        fontSize: 12
      },
      itemGap: 15
    },
    color: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16'],
    series: [
      {
        name: seriesName,
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['65%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            color: '#333'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: data,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  }
}

// 设置申请状态分布图表
const setupApplicationStatusChart = (data) => {
  console.log('设置申请状态分布图表，接收数据:', data)
  if (!data || !Array.isArray(data) || data.length === 0) {
    console.warn('申请状态分布数据为空或格式错误，使用默认数据')
    // 使用默认数据
    const defaultData = [
      { name: '待审核', value: 0 },
      { name: '已通过', value: 0 },
      { name: '已拒绝', value: 0 }
    ]
    applicationTrendOption.value = createPieChartOption('申请数量', defaultData)
    return
  }
  
  // 统计各状态的申请数量
  const statusCounts = {}
  data.forEach(app => {
    const status = app.status || 'unknown'
    statusCounts[status] = (statusCounts[status] || 0) + 1
  })
  
  // 转换为图表数据格式
  const chartData = Object.entries(statusCounts).map(([status, count]) => ({
    name: getApplicationStatusLabel(status),
    value: count
  }))
  
  console.log('处理后的申请状态分布图表数据:', chartData)
  
  applicationTrendOption.value = createPieChartOption('申请数量', chartData)
}

// 设置险种分布图表
const setupInsuranceTypeDistributionChart = (data) => {
  console.log('设置险种分布图表，接收数据:', data)
  if (!data || !Array.isArray(data) || data.length === 0) {
    console.warn('险种分布数据为空或格式错误，使用默认数据')
    // 使用默认数据
    const defaultData = [
      { name: '人寿保险', value: 0 },
      { name: '健康保险', value: 0 },
      { name: '财产保险', value: 0 }
    ]
    policyDistributionOption.value = createPieChartOption('险种数量', defaultData)
    return
  }
  
  // 统计每个险种的数量（这里假设每个险种都有相同的权重，实际项目中可能需要根据保单数量统计）
  const chartData = data.map((item, index) => ({
    name: item.name || `险种${index + 1}`,
    value: 1 // 每个险种计数为1，实际项目中可以根据保单数量统计
  }))
  
  console.log('处理后的险种分布图表数据:', chartData)
  
  policyDistributionOption.value = createPieChartOption('险种数量', chartData)
}

// 获取申请状态标签
const getApplicationStatusLabel = (status) => {
  const statusMap = {
    'pending': '待审核',
    'initial_approved': '初审通过',
    'under_review': '复审中',
    'approved': '已通过',
    'rejected': '已拒绝',
    'unknown': '未知状态'
  }
  return statusMap[status] || status
}

// 获取保单状态标签
const getPolicyStatusLabel = (status) => {
  const statusMap = {
    'active': '有效',
    'expired': '已过期',
    'cancelled': '已取消',
    'suspended': '暂停'
  }
  return statusMap[status] || status
}

onMounted(() => {
  console.log('Dashboard组件已挂载')
  console.log('图表选项初始状态:', {
    applicationTrendOption: applicationTrendOption.value,
    policyDistributionOption: policyDistributionOption.value
  })
  
  // 直接加载动态数据，不再设置测试数据
  console.log('开始加载动态图表数据...')
  loadDashboardData()
})
</script>

<style scoped>
.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.dashboard {
  padding: 0;
}
</style>