<template>
  <div class="data-warehouse">
    <div class="page-header">
      <h1>数据览仓</h1>
      <div class="filters">
        <a-input-group compact style="width: 300px; margin-right: 16px;">
          <a-input 
            v-model:value="dateRange[0]" 
            placeholder="开始日期" 
            style="width: 45%"
          />
          <a-input 
            style="width: 10%; text-align: center; pointer-events: none; background-color: #f5f5f5;" 
            placeholder="~" 
            disabled
          />
          <a-input 
            v-model:value="dateRange[1]" 
            placeholder="结束日期" 
            style="width: 45%"
          />
        </a-input-group>
        <a-button type="primary" @click="refreshData">刷新数据</a-button>
      </div>
    </div>

    <!-- 概览卡片 -->
    <div class="overview-cards">
      <a-card class="card-item" hoverable>
        <div class="card-content">
          <div class="card-title">总用户数</div>
          <div class="card-value">{{ overview.totalUsers }}</div>
        </div>
      </a-card>
      <a-card class="card-item" hoverable>
        <div class="card-content">
          <div class="card-title">保险申请总数</div>
          <div class="card-value">{{ overview.totalApplications }}</div>
        </div>
      </a-card>
      <a-card class="card-item" hoverable>
        <div class="card-content">
          <div class="card-title">保单总数</div>
          <div class="card-value">{{ overview.totalPolicies }}</div>
        </div>
      </a-card>
      <a-card class="card-item" hoverable>
        <div class="card-content">
          <div class="card-title">理赔总数</div>
          <div class="card-value">{{ overview.totalClaims }}</div>
        </div>
      </a-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 保险类型分布 -->
      <a-card title="保险类型分布" class="chart-item">
        <div ref="typeDistributionChart" class="chart"></div>
      </a-card>
      
      <!-- 申请状态分布 -->
      <a-card title="申请状态分布" class="chart-item">
        <div ref="statusDistributionChart" class="chart"></div>
      </a-card>
      
      <!-- 趋势图 -->
      <a-card title="近7天业务趋势" class="chart-item full-width">
        <div ref="trendChart" class="chart"></div>
      </a-card>
      
      <!-- 赔付统计 -->
      <a-card title="按保险类型赔付统计" class="chart-item full-width">
        <div ref="claimStatsChart" class="chart"></div>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance, nextTick } from 'vue';
import * as echarts from 'echarts';
import { message } from 'ant-design-vue';
import { dataWarehouseAPI } from '@/utils/api';
import dayjsLib from 'dayjs';

// 安全获取dayjs实例
const getSafeDayjs = () => {
  try {
    // 首先尝试使用导入的dayjs
    if (dayjsLib && typeof dayjsLib === 'function') {
      return dayjsLib;
    }
    
    // 尝试从Vue实例中获取全局配置的dayjs
    const instance = getCurrentInstance();
    if (instance && instance.appContext.config.globalProperties.$dayjs) {
      return instance.appContext.config.globalProperties.$dayjs;
    }
    
    // 尝试使用window上的dayjs实例
    if (window.dayjs && typeof window.dayjs === 'function') {
      return window.dayjs;
    }
    
    // 如果都失败，使用简单的兼容实现
    console.warn('使用简单的日期处理兼容实现');
    return createSimpleDayjs();
  } catch (error) {
    console.warn('获取dayjs失败，使用兼容实现:', error);
    return createSimpleDayjs();
  }
};

// 创建简单的dayjs兼容实现
const createSimpleDayjs = () => {
  const simpleDayjs = (date) => {
    const d = date ? new Date(date) : new Date();
    
    return {
      subtract: (num, unit) => {
        const ms = unit === 'day' ? 86400000 : 3600000;
        return simpleDayjs(new Date(d.getTime() - num * ms));
      },
      format: (fmt = 'YYYY-MM-DD') => {
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return fmt.replace('YYYY', year).replace('MM', month).replace('DD', day);
      },
      // 添加locale方法以兼容Ant Design Vue
      locale: () => simpleDayjs
    };
  };
  
  // 添加静态方法
  simpleDayjs.locale = () => simpleDayjs;
  
  return simpleDayjs;
};

// 数据状态
const overview = ref({
  totalUsers: 0,
  totalApplications: 0,
  totalPolicies: 0,
  totalClaims: 0,
  activePolicies: 0,
  approvedClaims: 0,
  pendingClaims: 0
});

// 初始化日期范围为字符串格式
const dayjsInstance = getSafeDayjs();
const dateRange = ref([
  dayjsInstance().subtract(7, 'day').format('YYYY-MM-DD'), 
  dayjsInstance().format('YYYY-MM-DD')
]);
const loading = ref(false);

// 图表引用
const typeDistributionChart = ref(null);
const statusDistributionChart = ref(null);
const trendChart = ref(null);
const claimStatsChart = ref(null);

// 图表实例
let typeChartInstance = null;
let statusChartInstance = null;
let trendChartInstance = null;
let claimChartInstance = null;

// 获取概览数据
const fetchOverview = async () => {
  try {
    const response = await dataWarehouseAPI.getOverview();
    console.log('概览数据响应:', response);
    if (response.data && response.data.success) {
      overview.value = response.data.data;
    } else {
      message.error('获取概览数据失败');
    }
  } catch (error) {
    message.error('获取概览数据失败');
    console.error('获取概览数据错误:', error);
  }
};

// 获取保险类型分布数据
const fetchTypeDistribution = async () => {
  try {
    const response = await dataWarehouseAPI.getInsuranceTypeDistribution();
    console.log('保险类型分布响应:', response);
    if (response.data && response.data.success) {
      console.log('保险类型分布数据:', response.data.data);
      await nextTick(); // 确保DOM更新
      ensureChartReady(typeDistributionChart, () => renderTypeDistributionChart(response.data.data));
    } else {
      console.log('保险类型分布响应格式错误:', response);
      message.error('获取保险类型分布数据失败');
      await nextTick();
      ensureChartReady(typeDistributionChart, () => renderTypeDistributionChart([]));
    }
  } catch (error) {
    message.error('获取保险类型分布数据失败');
    console.error('获取保险类型分布数据错误:', error);
    await nextTick();
    ensureChartReady(typeDistributionChart, () => renderTypeDistributionChart([]));
  }
};

// 获取申请状态分布数据
const fetchStatusDistribution = async () => {
  try {
    const response = await dataWarehouseAPI.getApplicationStatusDistribution();
    console.log('申请状态分布响应:', response);
    if (response.data && response.data.success) {
      console.log('申请状态分布数据:', response.data.data);
      await nextTick(); // 确保DOM更新
      renderStatusDistributionChart(response.data.data);
    } else {
      console.log('申请状态分布响应格式错误:', response);
      message.error('获取申请状态分布数据失败');
    }
  } catch (error) {
    message.error('获取申请状态分布数据失败');
    console.error('获取申请状态分布数据错误:', error);
  }
};

// 获取趋势数据
const fetchTrendData = async () => {
  try {
    const response = await dataWarehouseAPI.getTrendData();
    console.log('趋势数据响应:', response);
    if (response.data && response.data.success) {
      console.log('趋势数据:', response.data.data);
      renderTrendChart(response.data.data);
    } else {
      console.log('趋势数据响应格式错误:', response);
      message.error('获取趋势数据失败');
    }
  } catch (error) {
    message.error('获取趋势数据失败');
    console.error('获取趋势数据错误:', error);
  }
};

// 获取赔付统计数据
const fetchClaimStats = async () => {
  try {
    const response = await dataWarehouseAPI.getClaimStats();
    console.log('赔付统计响应:', response);
    if (response && response.data && response.data.success) {
      console.log('赔付统计数据:', response.data.data);
      renderClaimStatsChart(response.data.data || { statusDistribution: [], monthlyTrend: [] });
    } else {
      console.log('赔付统计数据响应格式错误:', response);
      message.error('获取赔付统计数据失败');
      // 使用空数据渲染图表，避免显示错误
      renderClaimStatsChart({ statusDistribution: [], monthlyTrend: [] });
    }
  } catch (error) {
    message.error('获取赔付统计数据失败');
    console.error('获取赔付统计数据错误:', error);
    // 出错时也使用空数据渲染图表
    renderClaimStatsChart({ statusDistribution: [], monthlyTrend: [] });
  }
};

// 刷新所有数据
const refreshData = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchOverview(),
      fetchTypeDistribution(),
      fetchStatusDistribution(),
      fetchTrendData(),
      fetchClaimStats()
    ]);
    message.success('数据刷新成功');
  } finally {
    loading.value = false;
  }
};

// 确保图表容器准备就绪后初始化
const ensureChartReady = (chartRef, initCallback) => {
  const checkReady = () => {
    if (chartRef.value && chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
      initCallback();
    } else {
      setTimeout(checkReady, 50);
    }
  };
  checkReady();
};

// 处理日期范围变化
const handleDateChange = (dates) => {
  dateRange.value = dates;
  // 这里可以根据日期范围筛选数据
  // refreshData();
};

// 渲染保险类型分布图表
const renderTypeDistributionChart = (data) => {
  console.log('=== 开始渲染保险类型分布图表 ===');
  console.log('接收到的数据:', data);
  console.log('数据类型:', typeof data);
  console.log('是否为数组:', Array.isArray(data));
  console.log('数据长度:', data ? data.length : 'N/A');
  
  // 检查DOM元素是否存在
  if (!typeDistributionChart.value) {
    console.log('DOM元素不存在，延迟渲染');
    setTimeout(() => renderTypeDistributionChart(data), 200);
    return;
  }
  
  console.log('DOM元素存在，开始渲染。尺寸信息:', {
    clientWidth: typeDistributionChart.value.clientWidth,
    clientHeight: typeDistributionChart.value.clientHeight,
    offsetWidth: typeDistributionChart.value.offsetWidth,
    offsetHeight: typeDistributionChart.value.offsetHeight
  });
  
  console.log('DOM元素已准备好，开始初始化图表');
  
  if (!typeChartInstance) {
    typeChartInstance = echarts.init(typeDistributionChart.value);
    console.log('图表实例已创建');
  }
  
  // 验证数据格式
  if (!data || !Array.isArray(data) || data.length === 0) {
    console.warn('保险类型分布数据为空或格式错误:', data);
    return;
  }
  
  console.log('保险类型分布数据验证通过:', data);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.type)
    },
    series: [
      {
        name: '保险类型',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: data.map(item => ({ value: item.count, name: item.type })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}\n{c} ({d}%)'
        }
      }
    ]
  };
  
  console.log('设置图表选项:', option);
  typeChartInstance.setOption(option);
  console.log('保险类型分布图表渲染完成');
};

// 渲染申请状态分布图表
const renderStatusDistributionChart = (data) => {
  console.log('=== 开始渲染申请状态分布图表 ===');
  console.log('接收到的数据:', data);
  console.log('数据类型:', typeof data);
  console.log('是否为数组:', Array.isArray(data));
  console.log('数据长度:', data ? data.length : 'N/A');
  
  // 检查DOM元素是否存在且有尺寸
  if (!statusDistributionChart.value || statusDistributionChart.value.clientWidth === 0 || statusDistributionChart.value.clientHeight === 0) {
    console.log('DOM元素未准备好，延迟渲染。当前状态:', {
      element: statusDistributionChart.value,
      clientWidth: statusDistributionChart.value?.clientWidth,
      clientHeight: statusDistributionChart.value?.clientHeight,
      offsetWidth: statusDistributionChart.value?.offsetWidth,
      offsetHeight: statusDistributionChart.value?.offsetHeight
    });
    setTimeout(() => renderStatusDistributionChart(data), 200);
    return;
  }
  
  console.log('DOM元素已准备好，开始初始化图表');
  
  if (!statusChartInstance) {
    statusChartInstance = echarts.init(statusDistributionChart.value);
    console.log('图表实例已创建');
  }
  
  // 验证数据格式
  if (!data || !Array.isArray(data) || data.length === 0) {
    console.warn('申请状态分布数据为空或格式错误:', data);
    return;
  }
  
  console.log('申请状态分布数据验证通过:', data);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.label || item.status)
    },
    series: [
      {
        name: '申请状态',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: data.map(item => ({ value: item.count, name: item.label || item.status })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}\n{c} ({d}%)'
        }
      }
    ]
  };
  
  console.log('设置图表选项:', option);
  statusChartInstance.setOption(option);
  console.log('申请状态分布图表渲染完成');
};

// 渲染趋势图表
const renderTrendChart = (data) => {
  // 检查DOM元素是否存在且有尺寸
  if (!trendChart.value || trendChart.value.clientWidth === 0 || trendChart.value.clientHeight === 0) {
    setTimeout(() => renderTrendChart(data), 100);
    return;
  }
  
  if (!trendChartInstance) {
    trendChartInstance = echarts.init(trendChart.value);
  }
  
  console.log('趋势数据:', data);
  
  // 确保data是对象
  if (!data || typeof data !== 'object') {
    console.warn('趋势数据格式错误:', data);
    data = { applications: [], policies: [], claims: [] };
  }
  
  // 处理数据结构，合并三个数组的数据
  const applications = data.applications || [];
  const policies = data.policies || [];
  const claims = data.claims || [];
  
  // 获取所有日期并排序
  const allDates = [...new Set([
    ...applications.map(item => item.date),
    ...policies.map(item => item.date),
    ...claims.map(item => item.date)
  ])].sort();
  
  // 为每个日期创建数据映射
  const applicationMap = new Map(applications.map(item => [item.date, item.count]));
  const policyMap = new Map(policies.map(item => [item.date, item.count]));
  const claimMap = new Map(claims.map(item => [item.date, item.count]));
  
  const dates = allDates;
  const newApplications = allDates.map(date => applicationMap.get(date) || 0);
  const newPolicies = allDates.map(date => policyMap.get(date) || 0);
  const newClaims = allDates.map(date => claimMap.get(date) || 0);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['新增申请', '新增保单', '新增理赔']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增申请',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: newApplications
      },
      {
        name: '新增保单',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: newPolicies
      },
      {
        name: '新增理赔',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: newClaims
      }
    ]
  };
  
  trendChartInstance.setOption(option);
};

// 渲染赔付统计图表
const renderClaimStatsChart = (data) => {
  // 检查DOM元素是否存在且有尺寸
  if (!claimStatsChart.value || claimStatsChart.value.clientWidth === 0 || claimStatsChart.value.clientHeight === 0) {
    setTimeout(() => renderClaimStatsChart(data), 100);
    return;
  }
  
  if (!claimChartInstance) {
    claimChartInstance = echarts.init(claimStatsChart.value);
  }
  
  console.log('赔付统计数据:', data);
  
  // 确保data是对象且有statusDistribution属性
  if (!data || typeof data !== 'object') {
    console.warn('赔付统计数据格式错误:', data);
    data = { statusDistribution: [], monthlyTrend: [] };
  }
  
  // 处理数据结构，使用statusDistribution数组
  const chartData = data.statusDistribution || [];
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['赔付金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.map(item => item.label || item.status),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '金额（元）',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [
      {
        name: '赔付金额',
        type: 'bar',
        data: chartData.map(item => ({
          value: item.totalAmount || 0,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} 元'
          }
        }))
      }
    ]
  };
  
  claimChartInstance.setOption(option);
};

// 处理窗口大小变化，重新调整图表
const handleResize = () => {
  typeChartInstance?.resize();
  statusChartInstance?.resize();
  trendChartInstance?.resize();
  claimChartInstance?.resize();
};

// 组件挂载时初始化
onMounted(() => {
  console.log('=== DataWarehouse组件已挂载 ===');
  console.log('图表容器引用:', {
    typeDistributionChart: typeDistributionChart.value,
    statusDistributionChart: statusDistributionChart.value,
    trendChart: trendChart.value,
    claimStatsChart: claimStatsChart.value
  });
  
  // 延迟一点时间确保DOM完全渲染
  setTimeout(() => {
    console.log('延迟检查图表容器尺寸:', {
      typeDistributionChart: typeDistributionChart.value ? {
        clientWidth: typeDistributionChart.value.clientWidth,
        clientHeight: typeDistributionChart.value.clientHeight
      } : 'null',
      statusDistributionChart: statusDistributionChart.value ? {
        clientWidth: statusDistributionChart.value.clientWidth,
        clientHeight: statusDistributionChart.value.clientHeight
      } : 'null'
    });
    
    refreshData();
  }, 100);
  
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  typeChartInstance?.dispose();
  statusChartInstance?.dispose();
  trendChartInstance?.dispose();
  claimChartInstance?.dispose();
});
</script>

<style scoped>
.data-warehouse {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.filters {
  display: flex;
  align-items: center;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.card-item {
  height: 120px;
}

.card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #1890ff;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.chart-item {
  height: 400px;
}

.chart-item.full-width {
  grid-column: span 2;
}

.chart {
  width: 100%;
  height: calc(100% - 50px);
  min-height: 300px;
  min-width: 200px;
}

@media (max-width: 1200px) {
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .chart-item.full-width {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filters {
    width: 100%;
  }
}
</style>