<template>
  <div class="data-display-edit">
    <!-- 筛选表单 -->
    <div class="filter-form">
      <el-form :model="filterForm" :label-width="formLabelWidth" inline>
        <!-- 时间范围 -->
        <el-form-item :label="t('dataReport.timeRange')">
          <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
            :start-placeholder="t('dataReport.startDate')" :end-placeholder="t('dataReport.endDate')"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="default" clearable />
        </el-form-item>

        <!-- 时间区间 -->
        <el-form-item :label="t('dataReport.timeInterval')">
          <el-select v-model="filterForm.timeInterval" :placeholder="t('dataReport.selectTimeInterval')" size="default"
            clearable>
            <el-option :label="t('dataReport.yesterday')" :value="1" />
            <el-option :label="t('dataReport.past7Days')" :value="7" />
            <el-option :label="t('dataReport.past14Days')" :value="14" />
            <el-option :label="t('dataReport.past30Days')" :value="30" />
            <el-option :label="t('dataReport.past60Days')" :value="60" />
            <el-option :label="t('dataReport.past90Days')" :value="90" />
            <el-option :label="t('dataReport.past180Days')" :value="180" />
            <el-option :label="t('dataReport.past360Days')" :value="360" />
          </el-select>
        </el-form-item>

        <!-- 汇总周期 -->
        <el-form-item :label="t('dataReport.summaryPeriod')">
          <el-select v-model="filterForm.summaryPeriod" :placeholder="t('dataReport.selectSummaryPeriod')"
            size="default" clearable>
            <el-option :label="t('dataReport.byDay')" :value="1" />
            <el-option :label="t('dataReport.byWeek')" :value="2" />
            <el-option :label="t('dataReport.byMonth')" :value="3" />
            <el-option :label="t('dataReport.byYear')" :value="4" />
          </el-select>
        </el-form-item>

        <!-- 颗粒度 -->
        <el-form-item :label="t('dataReport.granularity')">
          <el-select v-model="filterForm.granularity" :placeholder="t('dataReport.selectGranularity')" size="default"
            clearable>
            <el-option :label="t('dataReport.applicationLevel')" :value="2" />
            <el-option :label="t('dataReport.pageLevel')" :value="1" />
            <el-option :label="t('dataReport.componentLevel')" :value="3" />
          </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="chartLoading">
            {{ t('dataReport.query') }}
          </el-button>
          <el-button @click="handleReset">
            {{ t('common.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <div class="chart-container" v-loading="chartLoading">
        <report-chart :data="chartData" :type="chartType" :height="500" :title="chartTitle" :show-date-picker="false"
          @type-change="handleChartTypeChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../../data.service.js';
import ReportChart from './report-chart.vue';

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

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '130px', zhWidth: '80px' });

const props = defineProps({
  modal: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['confirm', 'cancel']);

// 筛选表单数据
const filterForm = ref({
  dateRange: null, // 时间范围，默认为null
  timeInterval: 7, // 时间区间，默认过去7天
  summaryPeriod: 1, // 汇总周期，默认按日
  granularity: null // 颗粒度，默认为null
});

const chartType = ref('line');
const chartLoading = ref(false);
const dimensionData = ref(null);
const chartData = ref([]);

// 计算属性
const dialogTitle = computed(() => {
  return dimensionData.value?.name || t('dataReport.dataDetail');
});

const iconComponent = computed(() => {
  return TrendCharts;
});

const chartTitle = computed(() => {
  return dimensionData.value?.name || t('dataReport.dataAnalysis');
});



// 方法
const handleSearch = () => {
  loadDimensionDetail();
};

const handleReset = () => {
  filterForm.value = {
    dateRange: null,
    timeInterval: 7, // 默认过去7天
    summaryPeriod: 1, // 默认按日
    granularity: null
  };
  loadDimensionDetail();
};

// 处理图表类型切换
const handleChartTypeChange = async (newType) => {
  const dimensionId = props.modal.params.id;
  if (!dimensionId) {
    ElMessage.error(t('dataReport.missingDimensionId'));
    return;
  }

  try {
    await api.report.dimensions.update({
      viewType: newType,
      id: dimensionId
    });

    chartType.value = newType;
    ElMessage.success(t('dataReport.chartTypeUpdateSuccess'));
  } catch (error) {
    console.error('更新图表类型失败:', error);
    ElMessage.error(t('dataReport.updateChartTypeFailed'));
  }
};

const loadData = () => {
  loadDimensionDetail();
};

// 获取维度详情数据
const loadDimensionDetail = async () => {
  const dimensionId = props.modal?.params.id;
  if (!dimensionId) {
    console.warn(t('dataReport.missingDimensionId'));
    return;
  }

  chartLoading.value = true;

  try {
    const params = {
      id: dimensionId,
      timeInterval: filterForm.value.timeInterval || 7, // 默认月7天
      type: filterForm.value.summaryPeriod || 1, // 默认按日
      granularity: filterForm.value.granularity || null
    };

    // 根据时间区间计算起止时间
    if (filterForm.value.timeInterval && !filterForm.value.dateRange) {
      const { startTime, endTime } = calculateTimeRange(filterForm.value.timeInterval);
      params.startTime = startTime;
      params.endTime = endTime;
    } else if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
      // 优先使用手动选择的日期范围
      params.startTime = filterForm.value.dateRange[0];
      params.endTime = filterForm.value.dateRange[1];
    } else {
      // 默认过去7天
      const { startTime, endTime } = calculateTimeRange(7);
      params.startTime = startTime;
      params.endTime = endTime;
    }

    console.log('🔍 详情查询参数:', params);

    const { code, data } = await api.report.dimensions.detail(params);
    // const { code, data } = dsDetailData

    if (code === '200' && data) {
      dimensionData.value = data;
      processChartData(data);
      chartType.value = data.viewType || 'line';
    } else {
      ElMessage.error(t('dataReport.getDimensionDetailFailed'));
    }
  } catch (error) {
    console.error('获取维度详情失败:', error);
    ElMessage.error(t('dataReport.getDimensionDetailFailed'));
  } finally {
    chartLoading.value = false;
  }
};

// 根据时间区间计算起止时间
const calculateTimeRange = (days) => {
  const endDate = new Date();
  const startDate = new Date();

  if (days === 1) {
    // 昨天
    startDate.setDate(endDate.getDate() - 1);
    endDate.setDate(endDate.getDate() - 1);
  } else {
    // 过去 N 天
    startDate.setDate(endDate.getDate() - days);
  }

  return {
    startTime: startDate.toISOString().split('T')[0],
    endTime: endDate.toISOString().split('T')[0]
  };
};

// 处理图表数据 - 与index.vue保持一致的逻辑
const processChartData = (data) => {
  if (!data || !data.sections || data.sections.length === 0) {
    chartData.value = [];
    return;
  }

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

  if (!firstSection) {
    chartData.value = [];
    return;
  }

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

  // 为每个section生成数据点（包含汇总数据，与index.vue一致）
  data.sections.forEach(section => {
    if (section.statistics) {
      section.statistics.forEach(stat => {
        result.push({
          x: formatDateByPeriod(stat.cutDay, filterForm.value.summaryPeriod),
          y: stat.statisticsValue,
          series: section.name
        });
      });
    }
  });

  console.log('📈 详情页数据点:', result.length, '周期:', filterForm.value.summaryPeriod);
  chartData.value = result;
};

// 根据汇总周期格式化日期显示
const formatDateByPeriod = (dateStr, period) => {
  const date = new Date(dateStr);

  switch (period) {
    case 1: // 按日
      return dateStr; // 保持原格式 YYYY-MM-DD
    case 2: // 按周
      const weekStart = new Date(date);
      weekStart.setDate(date.getDate() - date.getDay());
      return `${weekStart.getFullYear()}-W${Math.ceil(weekStart.getDate() / 7)}`;
    case 3: // 按月
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    case 4: // 按年
      return `${date.getFullYear()}`;
    default:
      return dateStr;
  }
};


// 组件挂载时加载数据
onMounted(() => {
  loadData();
});


</script>

<style scoped>
.data-display-edit {
  width: 100%;
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.filter-form {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.filter-form .el-form {
  margin-bottom: 0;
}

.filter-form .el-form-item {
  margin-bottom: 16px;
}

.filter-form .el-form-item:last-child {
  margin-bottom: 0;
}

.chart-section {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.chart-container {
  min-height: 500px;
  padding: 20px;
}

.empty-chart {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

  .filter-form {
    padding: 16px;
  }

  .filter-form .el-form {
    flex-direction: column;
  }

  .filter-form .el-form-item {
    width: 100%;
  }

  .chart-container {
    padding: 16px;
    min-height: 400px;
  }

  .empty-chart {
    height: 400px;
  }
}
</style>