<template>
  <div class="data-report-main">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部区域：左侧看板列表 + 右侧新增图表 -->
      <div class="top-section">
        <!-- 左侧看板列表区域 -->
        <div class="dashboard-list-section">
          <div class="section-header">
            <h2 class="section-title">
              <el-icon>
                <Grid />
              </el-icon>
              {{ t('dataReport.dashboardList') }}
            </h2>
            <div class="section-actions">
              <el-button type="primary" @click="addDashboard">
                <el-icon>
                  <Plus />
                </el-icon>
                {{ t('dataReport.addDashboard') }}
              </el-button>
              <el-button type="primary" @click="addChart">
                <el-icon>
                  <Plus />
                </el-icon>
                {{ t('dataReport.addChart') }}
              </el-button>
            </div>
          </div>
          <div class="dashboard-buttons" v-loading="dashboardLoading">
            <div v-for="dashboard in dashboardList" :key="dashboard.id" class="dashboard-card"
              :class="{ active: selectedDashboard?.id === dashboard.id }" @click="selectDashboard(dashboard)">
              <div class="dashboard-content">
                <div class="dashboard-icon">
                  <el-icon>
                    <Grid />
                  </el-icon>
                </div>
                <div class="dashboard-info">
                  <div class="dashboard-name">{{ dashboard.name }}</div>
                </div>
                <div class="dashboard-actions">
                  <el-button size="small" type="text" @click.stop="editDashboard(dashboard)" class="action-btn">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                  <el-button size="small" type="text" @click.stop="deleteDashboard(dashboard)"
                    class="action-btn delete-btn">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </div>
            </div>
            <div v-if="!dashboardList.length" class="empty-state">
              <div class="empty-icon">📋</div>
              <div class="empty-text">{{ t('dataReport.noDashboardData') }}</div>
            </div>
          </div>
        </div>


      </div>

      <!-- 下方图表数据显示区域 -->
      <div class="charts-display-section">
        <div class="section-header">
          <h2 class="section-title">
            <el-icon>
              <TrendCharts />
            </el-icon>
            {{ selectedDashboard ? selectedDashboard.name : t('dataReport.dataChart') }}
          </h2>
          <div class="section-actions">
            <el-button @click="refreshChartData" :loading="loading" size="small">
              <el-icon>
                <Refresh />
              </el-icon>
              {{ t('dataReport.refreshData') }}
            </el-button>

          </div>
        </div>

        <!-- 图表网格 -->
        <div v-loading="loading" class="charts-grid">
          <div v-for="chart in currentCharts" :key="chart.id" class="chart-card">
            <div class="chart-header">
              <div class="chart-actions">
                <el-button text size="small" @click="showChartDetail(chart)">
                  <el-icon>
                    <View />
                  </el-icon>
                  {{ t('dataReport.viewDetail') }}
                </el-button>
                <el-button text size="small" @click="deleteChart(chart)" type="danger">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  {{ t('dataReport.deleteChart') }}
                </el-button>
                <el-button text size="small" @click="downloadChart(chart)" :loading="exportLoading"
                  :disabled="exportLoading">
                  <el-icon>
                    <TrendCharts />
                  </el-icon>
                  {{ exportLoading ? t('dataReport.exporting') : t('dataReport.exportChart') }}
                </el-button>
              </div>
            </div>
            <div class="chart-content">
              <reportChart :title="chart.name" :data="transformChartData(chart)" :type="chart.viewType || 'line'"
                :height="350" :show-date-picker="false" :x-axis-key="'x'" :y-axis-key="'y'" :series-key="'series'"
                :colors="legendColors" @chart-click="handleChartClick" />
            </div>
            <div class="chart-footer">
              <span class="update-time">{{ t('dataReport.updateTime') }}：{{ chart.updateTime ||
                t('dataReport.noUpdateTime') }}</span>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>





</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Grid, View, Edit, Delete, TrendCharts, Refresh } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import { useModal } from '@/sheep/hooks';
import { api } from '../data.service.js';

import dataDisplayEdit from './components/dataDisplayEdit.vue';
import dashboardEdit from './components/dashboardEdit.vue';
import chartEdit from './components/chartEdit.vue';
import reportChart from './components/report-chart.vue';

// 使用国际化
const { t } = useI18n();

// 响应式数据
const loading = ref(false);
const dashboardLoading = ref(false);
const selectedDashboard = ref(null);
const dashboardList = ref([]);
const chartData = ref([]);
// 导出loading状态
const exportLoading = ref(false);

// 图例颜色配置
const legendColors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];

// 计算当前选中看板的图表数据
const currentCharts = computed(() => {
  if (!selectedDashboard.value) return [];
  return chartData.value.filter(chart =>
    chart.dashboardId === selectedDashboard.value.id
  );
});

// 获取看板列表数据
async function getDashboardList() {
  dashboardLoading.value = true;
  try {
    const { code, data } = await api.report.spectaculars.list({
      page: 1,
      size: 100,
      userId: '' // 可以根据实际需要传入用户ID
    });
    if (code == 200) {
      // 根据实际返回的数据结构处理
      dashboardList.value = data.list || data || [];

      // 如果当前没有选中的看板,或者选中的看板已经不在列表中,则选中第一个
      const currentSelectedExists = dashboardList.value.some(d => d.id === selectedDashboard.value?.id);

      if (dashboardList.value.length > 0 && (!selectedDashboard.value || !currentSelectedExists)) {
        selectedDashboard.value = dashboardList.value[0];
        // 自动调用第一个看板的详情接口
        await getChartData(dashboardList.value[0].id);
      } else if (dashboardList.value.length === 0) {
        // 如果列表为空,清空选中状态和图表数据
        selectedDashboard.value = null;
        chartData.value = [];
      }
    } else {
      ElMessage.error(t('dataReport.getDashboardListFailed'));
      dashboardList.value = [];
    }
  } catch (error) {
    console.error('获取看板列表失败:', error);
    ElMessage.error(t('dataReport.getDashboardListFailed'));
    dashboardList.value = [];
  } finally {
    dashboardLoading.value = false;
  }
}

// 获取图表数据
async function getChartData(dashboardId) {
  if (!dashboardId) return;

  loading.value = true;
  try {
    // const { code, data } = detailData
    const { code, data } = await api.report.spectaculars.detail({
      id: dashboardId,
      startTime: '', // 可以根据实际需要设置时间范围
      endTime: '',
      timeInterval: 7
    });
    if (code == 200) {
      // 更新当前看板的图表数据
      const newCharts = Array.isArray(data) ? data : [data];

      chartData.value = chartData.value.filter(chart => chart.dashboardId !== dashboardId);
      chartData.value.push(...newCharts.map(chart => ({ ...chart, dashboardId })));

      // 处理维度数据用于图表显示
      processChartData(data);
    } else {
      ElMessage.error(t('dataReport.getChartDataFailed'));
    }
  } catch (error) {
    console.error('获取图表数据失败:', error);
    ElMessage.error(t('dataReport.getChartDataFailed'));
  } finally {
    loading.value = false;
  }
}

// 刷新图表数据
async function refreshChartData() {
  if (selectedDashboard.value) {
    await getChartData(selectedDashboard.value.id);
  }
}

// 选择看板
async function selectDashboard(dashboard) {
  selectedDashboard.value = dashboard;
  await getChartData(dashboard.id);
}

// 处理图表数据
function processChartData(data) {
  // 处理从detail接口返回的数据，转换为图表可用格式
  if (data && data.dimensions) {
    // 将dimensions数据转换为图表数据
    const newCharts = data.dimensions.map((dimension, index) => ({
      ...dimension,
      id: dimension.id || `chart_${index}`, // 确保有id
      name: dimension.name || `图表${index + 1}`, // 确保有name
      viewType: dimension.viewType || 'line', // 确保有viewType，默认为折线图
      dashboardId: selectedDashboard.value?.id,
      sections: dimension.sections || [],
      updateTime: new Date().toLocaleString() // 添加更新时间
    }));

    // 更新图表数据
    chartData.value = chartData.value.filter(chart => chart.dashboardId !== selectedDashboard.value?.id);
    chartData.value.push(...newCharts);
  }
}

// 转换图表数据格式
function transformChartData(chart) {
  if (!chart.sections || chart.sections.length === 0) {
    return [];
  }

  // 获取所有日期（从第一个section的statistics中提取）
  const firstSection = chart.sections.find(section => section.statistics && section.statistics.length > 0);

  if (!firstSection) {
    return [];
  }

  const dates = firstSection.statistics.map(stat => stat.cutDay);

  // 转换为report-chart组件期望的格式: {x, y, series}
  const result = [];

  // 为每个section生成数据点
  chart.sections.forEach(section => {
    if (section.statistics) {
      section.statistics.forEach(stat => {
        result.push({
          x: stat.cutDay,
          y: stat.statisticsValue,
          series: section.name
        });
      });
    }
  });

  console.log('📈', chart.name, '数据点:', result.length);
  return result;
}



// 处理图表点击事件 - 现在由 reportChart 组件内部处理
function handleChartClick(params) {
  console.log('图表点击事件:', params);
  // 这里可以添加额外的处理逻辑，如果需要的话
}

// 删除看板
function deleteDashboard(dashboard) {
  ElMessageBox.confirm(t('dataReport.confirmDeleteDashboard', { name: dashboard.name }), t('common.tip'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    try {
      // 记录是否删除的是当前选中的看板
      const isCurrentSelected = selectedDashboard.value?.id === dashboard.id;

      // 调用删除API
      const { code } = await api.report.spectaculars.delete(dashboard.id);
      if (code == 200) {
        ElMessage.success(t('dataReport.dashboardDeleteSuccess'));

        // 如果删除的是当前选中的看板,清空选中状态
        if (isCurrentSelected) {
          selectedDashboard.value = null;
          chartData.value = chartData.value.filter(chart => chart.dashboardId !== dashboard.id);
        }

        // 重新获取看板列表,会自动选中第一条
        await getDashboardList();
      } else {
        ElMessage.error(t('dataReport.dashboardDeleteFailed'));
      }
    } catch (error) {
      console.error('删除看板失败:', error);
      ElMessage.error(t('dataReport.dashboardDeleteFailed'));
    }
  }).catch(() => {
    // 取消删除
  });
}


// 删除图表
function deleteChart(chart) {
  ElMessageBox.confirm(
    t('dataReport.confirmDeleteChart', { name: chart.name }),
    t('dataReport.deleteChart'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      const { code } = await api.report.dimensions.delete(chart.spectacularsDimensionId);
      if (code == 200) {
        ElMessage.success(t('dataReport.chartDeleteSuccess'));
        refreshChartData()
      }
    } catch (error) {
      console.error('删除图表失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
}

// 下载图表
async function downloadChart(chart) {
  if (exportLoading.value) return; // 防止重复点击

  exportLoading.value = true;
  try {
    // 构建导出参数，与列表请求参数保持一致，但排除分页相关数据
    const exportParams = {
      id: chart.spectacularsDimensionId,
      timeInterval: 7
    };

    // 调用导出API，所有下载逻辑都在REPORT函数中处理
    await api.report.dimensions.report(exportParams, '数据列表');
  } finally {
    exportLoading.value = false;
  }
}



// 显示数据展示页面
function showChartDetail(options) {
  useModal(
    dataDisplayEdit,
    {
      title: `${options.chart?.name || options.dataType || t('dataReport.dataDetail')} - ${t('dataReport.dataDetail')}`,
      width: '90%',
      height: '80vh',
      id: options.spectacularsDimensionId,
    },
    {
      confirm: () => {
        getChartData(selectedDashboard.value?.id);
      }
    }
  );
}

// 新增看板
function addDashboard() {
  useModal(
    dashboardEdit,
    { title: t('dataReport.addDashboard'), type: 'add', width: '500px' },
    {
      confirm: () => {
        getDashboardList();
      }
    }
  );
}

// 编辑看板
function editDashboard(row) {
  useModal(
    dashboardEdit,
    {
      title: t('dataReport.editDashboard'),
      type: 'edit',
      width: '500px',
      id: row.id,
      dashboardData: row
    },
    {
      confirm: () => {
        getDashboardList();
      }
    }
  );
}



// 新增图表
function addChart() {
  if (!selectedDashboard.value) {
    ElMessage.warning(t('dataReport.pleaseSelectDashboard'));
    return;
  }

  useModal(
    chartEdit,
    {
      title: t('dataReport.addChart'),
      type: 'add',
      spectId: selectedDashboard.value?.id
    },
    {
      confirm: () => {
        getChartData(selectedDashboard.value?.id);
      }
    }
  );
}

// 编辑图表
function editChart(row) {
  useModal(
    chartEdit,
    {
      title: t('dataReport.editChart'),
      type: 'edit',
      id: row.id,
      chartData: row,
      dashboardId: selectedDashboard.value?.id
    },
    {
      confirm: () => {
        getChartData(selectedDashboard.value?.id);
      }
    }
  );
}

// 格式化数值
function formatValue(value, unitType) {
  if (unitType === 1) {
    // 金额类型
    return `¥${value.toLocaleString()}`;
  } else {
    // 数量类型
    return value.toLocaleString();
  }
}

// 获取图表类型标签
function getChartTypeLabel(viewType) {
  const typeMap = {
    line: '折线图',
    bar: '柱状图',
    pie: '饼图',
    area: '面积图'
  };
  return typeMap[viewType] || '图表';
}





onMounted(() => {
  getDashboardList();
});
</script>
<style scoped>
.data-report-main {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 20px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

/* 顶部区域 */
.top-section {
  display: flex;
  gap: 20px;
}

/* 左侧看板列表区域 */
.dashboard-list-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.dashboard-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 14px;
  overflow-y: auto;
}

.dashboard-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  min-width: 180px;
  max-width: 300px;
  width: fit-content;
}

.dashboard-card.active {
  border-color: #409eff;
  background: linear-gradient(135deg, #ecf5ff 0%, #f0f9ff 100%);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.dashboard-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.dashboard-icon {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.dashboard-info {
  flex: 1;
  min-width: 0;
}

.dashboard-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-all;
}

.dashboard-actions {
  display: flex;
  gap: 2px;
  opacity: 1;
  flex-shrink: 0;
  margin-left: 8px;
}

.action-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.delete-btn:hover {
  background: #fef0f0;
  color: #f56c6c;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #909399;
  text-align: center;
  min-height: 100px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  margin-bottom: 16px;
}





/* 下方图表显示区域 */
.charts-display-section {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 图表网格 */
.charts-grid {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  overflow-y: auto;
  padding: 16px 0;
  align-content: flex-start;
}

.chart-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  min-width: 370px;
  min-height: 400px;
  margin: 10px;
  display: flex;
  flex-direction: column;
  /* 移除固定宽高，改为最小尺寸以确保图表有足够显示空间 */
}

.chart-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.chart-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.chart-actions {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 4px;
  opacity: 1;
}

.chart-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-footer {
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
}

.update-time {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.chart-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 8px;
  margin-bottom: 12px;
}

.summary-item {
  text-align: center;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.summary-label {
  font-size: 11px;
  color: #909399;
  margin-bottom: 2px;
}

.summary-value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.chart-placeholder {
  height: 80px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}

.chart-type-indicator {
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 12px;
  border-radius: 12px;
  font-weight: 500;
}

/* 空状态 */
.empty-charts {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
  text-align: center;
}

.empty-charts .empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-charts .empty-text {
  font-size: 14px;
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-report-main {
    padding: 12px;
  }

  .top-section {
    flex-direction: column;
    height: auto;
  }

  .dashboard-list-section {
    height: 250px;
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .section-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 图表点击悬浮弹窗样式 */
.chart-tooltip-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-tooltip {
  position: absolute;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  min-width: 280px;
  max-width: 400px;
  z-index: 10000;
  transform: translate(-50%, -100%);
  margin-top: -10px;
}

.tooltip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.tooltip-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.tooltip-content {
  padding: 16px;
}

.tooltip-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.tooltip-item .label {
  color: #909399;
  font-size: 13px;
  margin-right: 12px;
}

.tooltip-item .value {
  color: #303133;
  font-weight: 500;
  font-size: 13px;
}
</style>
