<template>
  <el-container>
    <el-main>
      <div class="chart-edit-modal">
        <!-- 主要内容区域 -->
        <div class="main-content">
          <!-- 左侧图表列表 -->
          <div class="chart-list-section">
            <div class="list-header">
              <h4>{{ t('dataReport.selectDataDimension') }}</h4>
              <div class="search-box">
                <el-input v-model="searchKeyword" :placeholder="t('dataReport.searchChartName')" prefix-icon="Search"
                  clearable @input="filterCharts" />
              </div>
            </div>

            <div class="chart-list" v-loading="chartListLoading">
              <div v-for="chart in filteredCharts" :key="chart.id" class="chart-item"
                :class="{ active: selectedCharts.includes(chart.id) }" @click="toggleChart(chart)">
                <el-checkbox :model-value="selectedCharts.includes(chart.id)" @change="toggleChart(chart)"
                  class="chart-checkbox" />
                <div class="chart-info">
                  <div class="chart-name">{{ chart.name }}</div>
                </div>
              </div>

              <div v-if="!filteredCharts.length" class="empty-state">
                <el-icon class="empty-icon">
                  <Search />
                </el-icon>
                <div class="empty-text">{{ searchKeyword ? t('dataReport.noMatchingCharts') :
                  t('dataReport.noChartsAvailable') }}</div>
              </div>
            </div>
          </div>

          <!-- 右侧预览区域 -->
          <div class="preview-section">

            <div v-if="selectedCharts.length === 0" class="empty-preview">
              <el-icon class="empty-icon">
                <TrendCharts />
              </el-icon>
              <div class="empty-text">{{ t('dataReport.selectLeftDataDimension') }}</div>
              <div class="empty-desc">{{ t('dataReport.selectToShowPreview') }}</div>
            </div>

            <div v-else class="preview-content">
              <div class="chart-preview">
                <report-chart :type="'line'" :data="currentChartData" :height="300" :show-date-picker="false"
                  :title="lastSelectedChart?.name" />
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作按钮 -->
        <el-footer class="sa-footer--submit">
          <el-button @click="cancel">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="confirm" :disabled="selectedCharts.length === 0">
            <el-icon>
              <Plus />
            </el-icon>
            {{ t('dataReport.confirmAdd') }} ({{ selectedCharts.length }})
          </el-button>
        </el-footer>
      </div>
    </el-main>
  </el-container>
</template>

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

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

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

const emit = defineEmits(['modalCallBack']);

// 响应式数据
const chartListLoading = ref(false);
const chartList = ref([]);
const selectedCharts = ref([]); // 改为多选数组
const lastSelectedChart = ref(null); // 最后选中的图表用于预览

const searchKeyword = ref('');

// 根据图表名称生成对应的模拟数据
const generateMockData = (chartName) => {
  const dates = ['2025-08-28', '2025-08-29', '2025-08-30', '2025-08-31', '2025-09-01', '2025-09-02', '2025-09-03'];

  // 根据图表名称生成不同的数据模式
  const dataPatterns = {
    '商城停留时间统计': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 60) + 30, series: '停留时间(分钟)' })),
    '种子统计': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 1000) + 500, series: '种子数量' })),
    '装饰统计': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 200) + 100, series: '装饰销量' })),
    '虫子统计': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 50) + 10, series: '虫子数量' })),
    '次日留存': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 30) + 60, series: '留存率(%)' })),
    '7日留存': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 20) + 40, series: '留存率(%)' })),
    '入账笔数': () => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 500) + 200, series: '笔数' }))
  };

  // 如果有对应的数据模式，使用它；否则使用默认模式
  const generator = dataPatterns[chartName] || (() => dates.map((date, index) => ({ x: date, y: Math.floor(Math.random() * 1000) + 100, series: chartName || '默认数据' })));
  return generator();
};

// 当前图表数据（根据选中的图表动态生成）
const currentChartData = computed(() => {
  if (!lastSelectedChart.value) return [];
  return generateMockData(lastSelectedChart.value.name);
});

// 过滤后的图表列表
const filteredCharts = computed(() => {
  if (!searchKeyword.value) {
    return chartList.value;
  }
  return chartList.value.filter(chart =>
    chart.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    (chart.memo && chart.memo.toLowerCase().includes(searchKeyword.value.toLowerCase()))
  );
});

// 获取可选图表列表
async function getChartList() {
  try {
    chartListLoading.value = true;
    const spectId = props.modal.params.spectId;
    if (!spectId) {
      ElMessage.error(t('dataReport.missingDashboardId'));
      return;
    }

    const { code, data } = await api.report.spectaculars.addView(spectId);
    if (code === '200') {
      chartList.value = data || [];
    } else {
      ElMessage.error(t('dataReport.getChartListFailed'));
    }
  } catch (error) {
    console.error('获取图表列表失败:', error);
    ElMessage.error(t('dataReport.getChartListFailed'));
  } finally {
    chartListLoading.value = false;
  }
}

// 切换图表选择状态
function toggleChart(chart) {
  const index = selectedCharts.value.indexOf(chart.id);
  if (index > -1) {
    selectedCharts.value.splice(index, 1);
    // 如果取消选择的是当前预览的图表，更新预览
    if (lastSelectedChart.value?.id === chart.id) {
      lastSelectedChart.value = selectedCharts.value.length > 0
        ? chartList.value.find(c => c.id === selectedCharts.value[selectedCharts.value.length - 1])
        : null;
    }
  } else {
    selectedCharts.value.push(chart.id);
    lastSelectedChart.value = chart; // 更新预览图表
  }
}

// 过滤图表
function filterCharts() {
  // 搜索逻辑已通过computed实现
}

// 取消操作
function cancel() {
  emit('modalCallBack', { event: 'cancel' });
}

// 确认添加图表
async function confirm() {
  if (selectedCharts.value.length === 0) {
    ElMessage.warning(t('dataReport.selectAtLeastOneChart'));
    return;
  }

  try {
    const spectId = props.modal.params.spectId;
    const submitData = {
      id: spectId,
      dimensions: selectedCharts.value.map(chartId => ({
        dimensionId: chartId,
        viewType: 'line'
      }))
    };

    const { code } = await api.report.dimensions.add(submitData);
    if (code === '200') {
      ElMessage.success(t('dataReport.addChartsSuccess', { count: selectedCharts.value.length }));
      emit('modalCallBack', { event: 'confirm' });
    } else {
      ElMessage.error(t('dataReport.addChartsFailed'));
    }
  } catch (error) {
    console.error('添加图表失败:', error);
    ElMessage.error(t('dataReport.addChartsFailed'));
  }
}

// 初始化
async function init() {
  await getChartList();
}

onMounted(() => {
  init();
});
</script>

<style scoped>
.chart-edit-modal {
  display: flex;
  flex-direction: column;
  height: 700px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}



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

/* 左侧图表列表 */
.chart-list-section {
  width: 320px;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
}

.list-header {
  padding: 20px 20px 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
}

.list-header h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.search-box {
  position: relative;
}

.chart-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.chart-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 8px;
}

.chart-item:hover {
  border-color: var(--el-color-primary);
  background: #f9f5ff;
}

.chart-item.active {
  border-color: var(--el-color-primary);
  /* 淡紫色 */
  background: #f9f5ff;
  box-shadow: 0 0 0 1px var(--el-color-primary);
}

.chart-checkbox {
  margin-right: 8px;
}

.chart-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}

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

.chart-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  line-height: 1.4;
}

.chart-item.active .chart-name {
  color: #1e40af;
}

.chart-check {
  color: var(--el-color-primary);
  font-size: 20px;
  animation: checkIn 0.3s ease;
}

@keyframes checkIn {
  0% {
    transform: scale(0);
    opacity: 0;
  }

  50% {
    transform: scale(1.2);
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #9ca3af;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 14px;
  font-weight: 500;
}

/* 右侧预览区域 */
.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
  background: #fff;
}

.empty-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  background: #fafbfc;
  border-radius: 12px;
  border: 2px dashed #e5e7eb;
}

.empty-preview .empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.4;
}

.empty-preview .empty-text {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #6b7280;
}

.empty-preview .empty-desc {
  font-size: 14px;
  margin: 0;
  color: #9ca3af;
}

.preview-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.preview-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}

.preview-header .chart-desc {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.chart-preview {
  flex: 1;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 底部操作按钮 */
.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.footer-actions .el-button {
  min-width: 100px;
  font-weight: 600;
}

/* 滚动条样式 */
.chart-list::-webkit-scrollbar {
  width: 6px;
}

.chart-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.chart-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.chart-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-edit-modal {
    height: 100vh;
  }

  .main-content {
    flex-direction: column;
  }

  .chart-list-section {
    width: 100%;
    max-height: 300px;
  }

  .type-button {
    min-width: 70px;
    padding: 12px 16px;
  }
}
</style>