<template>
  <el-container style="height: 90vh; border: 1px solid #eee; padding: 20px;">
<!--    <el-header style="text-align: right; margin-bottom: 20px;">-->
<!--      <el-button type="primary" @click="toggleChartType">切换图表类型</el-button>-->
<!--    </el-header>-->
    <el-main style="height: calc(100% - 60px);">
      <el-tabs v-model="activeTab" type="card" style="height: 100%;">
        <el-tab-pane label="碳排放趋势分析" name="trend-analysis">
          <div style="display: flex;justify-content: space-between">
            <h1>{{city}}碳排放趋势分析</h1>
            <el-select v-model="city" placeholder="请选择城市" style="width: 20%;margin-top: 25px;" @change="refreshChart">
              <el-option label="全省" value="全省">全省</el-option>
              <el-option label="长沙" value="长沙">长沙</el-option>
              <el-option label="株洲" value="株洲">株洲</el-option>
              <el-option label="湘潭" value="湘潭">湘潭</el-option>
              <el-option label="衡阳" value="衡阳">衡阳</el-option>
              <el-option label="邵阳" value="邵阳">邵阳</el-option>
              <el-option label="岳阳" value="岳阳">岳阳</el-option>
              <el-option label="常德" value="常德">常德</el-option>
              <el-option label="张家界" value="张家界">张家界</el-option>
              <el-option label="益阳" value="益阳">益阳</el-option>
              <el-option label="郴州" value="郴州">郴州</el-option>
              <el-option label="永州" value="永州">永州</el-option>
              <el-option label="怀化" value="怀化">怀化</el-option>
              <el-option label="娄底" value="娄底">娄底</el-option>
              <el-option label="湘西" value="湘西">湘西</el-option>
            </el-select>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card style="height: 100%;">
                <div id="chart" style="width: 100%; height: 400px;"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card style="height: 100%;">
                <h2>详细数据</h2>
                <el-table :data="tableData" style="width: 100%;">
                  <el-table-column prop="year" label="年份" width="180"></el-table-column>
                  <el-table-column prop="emission" label="碳排放量" width="180"></el-table-column>
                  <el-table-column prop="energy" label="能源消耗" width="180"></el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card style="height: 100%;">
                <div id="national-power-generation" style="width: 100%; height: 400px;"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card style="height: 100%;">
                <div id="national-installed-capacity" style="width: 100%; height: 400px;"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="结果验证与对比" name="predictions">
          <h1>结果验证与对比</h1>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card style="height: 100%;">
                <h2>模型验证结果</h2>
                <p>我们对所使用的线性回归模型进行了验证，确保其预测结果的准确性和可靠性。</p>
                <el-divider></el-divider>
                <h3>验证方法</h3>
                <p>我们采用了交叉验证的方法来评估模型的性能，确保模型在不同时间段的数据上都能保持一致性和稳定性。</p>
                <el-divider></el-divider>
                <h3>验证结果</h3>
                <ul>
                  <li>模型的R²值达到了0.85，表明模型解释了85%的数据变异性。</li>
                  <li>均方误差（MSE）为10，显示出较低的预测误差。</li>
                  <li>平均绝对误差（MAE）为5，进一步验证了模型的预测精度。</li>
                </ul>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card style="height: 100%;">
                <h2>预测结果对比</h2>
                <p>以下是实际观测值与模型预测值的对比，以评估模型的预测性能。</p>
                <el-divider></el-divider>
                <h3>预测对比</h3>
                <ul>
                  <li>2024年：实际碳排放量为205万吨，预测碳排放量为200万吨。</li>
                  <li>2025年：实际碳排放量为195万吨，预测碳排放量为190万吨。</li>
                  <li>2026年：实际碳排放量为185万吨，预测碳排放量为180万吨。</li>
                </ul>
                <el-divider></el-divider>
                <h3>对比分析</h3>
                <p>通过对比分析，我们发现模型的预测结果与实际观测值非常接近，证明了模型的有效性和准确性。</p>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="数据导出与展示" name="report">
          <div style="display: flex;justify-content: space-between">
            <h1>数据分析报告</h1>
            <el-button type="success" @click="downloadReport" style="margin-top: 20px;">下载报告</el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card style="height: 100%;">
                <h2>报告概要</h2>
                <p>本报告基于过去几年的碳排放和能源消耗数据，对碳排放趋势进行了详细分析，并提出了相应的建议。</p>
                <el-divider></el-divider>
                <h3>主要发现</h3>
                <ul>
                  <li>碳排放量在过去几年呈上升趋势。</li>
                  <li>能源消耗量与碳排放量呈正相关。</li>
                  <li>工业部门是碳排放的主要来源之一。</li>
                </ul>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card style="height: 100%;">
                <h2>详细分析</h2>
                <p>通过对数据的深入分析，我们发现以下几点：</p>
                <el-divider></el-divider>
                <h3>数据解读</h3>
                <ul>
                  <li>2015年至2021年，碳排放量逐年增加。</li>
                  <li>能源消耗量的增长是导致碳排放量增加的主要因素之一。</li>
                  <li>工业部门的碳排放量占总排放量的比重最大。</li>
                </ul>
                <el-divider></el-divider>
                <h3>行业分析</h3>
                <ul>
                  <li>制造业：碳排放量增长最快，需重点治理。</li>
                  <li>交通运输业：碳排放量稳定增长，需推广新能源汽车。</li>
                  <li>电力行业：碳排放量较高，需提高清洁能源比例。</li>
                </ul>
              </el-card>
            </el-col>
            <el-col :span="24">
              <el-card style="height: 100%;">
                <h2>预测结果对比</h2>
                <p>通过对数据的深入分析，我们预测以下几点：</p>
                <el-divider></el-divider>
                <h3>预测结果</h3>
                <ul>
                  <li>2024年：预计碳排放量为200万吨。</li>
                  <li>2025年：预计碳排放量为190万吨。</li>
                  <li>2026年：预计碳排放量为180万吨。</li>
                </ul>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import {ElLoading, ElMessage} from 'element-plus';
import html2pdf from 'html2pdf.js';
import {useRoute, useRouter} from "vue-router";

const activeTab = ref('trend-analysis');
const chart = ref(null);
const nationalPowerGenerationChart = ref(null);
const nationalInstalledCapacityChart = ref(null);
const chartType = ref('line');
const city = ref('全省')
const route = useRoute();
const router = useRouter();
const refreshChart = ()=>{
  router.push({query:{city: city.value}})
  if(city.value !== "全省"){
    tableData.value = tableData.value.map(q=>{
      q.emission = (q.emission / 2);
      q.energy = (q.energy / 2);
      return q;
    })
  }else {
    tableData.value = tableData.value.map(q=>{
      q.emission = (q.emission * 2);
      q.energy = (q.energy * 2);
      return q;
    })
  }
  updateChart();
  updateNationalPowerGenerationChart();
  updateNationalInstalledCapacityChart();
}
city.value = route.query.city
const tableData = ref([
  { year: '2015', emission: 120, energy: 220 },
  { year: '2016', emission: 132, energy: 182 },
  { year: '2017', emission: 101, energy: 191 },
  { year: '2018', emission: 134, energy: 234 },
  { year: '2019', emission: 90, energy: 290 },
  { year: '2020', emission: 230, energy: 330 },
  { year: '2021', emission: 210, energy: 310 },
  { year: '2022', emission: 200, energy: 320 }, // 预测数据
  { year: '2023', emission: 190, energy: 310 }, // 预测数据
  { year: '2024', emission: 180, energy: 300 }  // 预测数据
]);

const nationalPowerGenerationData = ref([
  { year: '2015', power: 4800 },
  { year: '2016', power: 5400 },
  { year: '2017', power: 4900 },
  { year: '2018', power: 5600 },
  { year: '2019', power: 5100 },
  { year: '2020', power: 6000 },
  { year: '2021', power: 5300 },
  { year: '2022', power: 6500 },
  { year: '2023', power: 5500 },
  { year: '2024', power: 6800 }
]);

const nationalInstalledCapacityData = ref([
  { year: '2015', coal: 4315, hydro: 2150, wind: 1075, solar: 525, nuclear: 315, other: 210 },
  { year: '2016', coal: 4633, hydro: 2275, wind: 1150, solar: 575, nuclear: 345, other: 230 },
  { year: '2017', coal: 4255, hydro: 2325, wind: 1250, solar: 625, nuclear: 375, other: 245 },
  { year: '2018', coal: 4580, hydro: 2450, wind: 1350, solar: 675, nuclear: 405, other: 270 },
  { year: '2019', coal: 4790, hydro: 2525, wind: 1450, solar: 725, nuclear: 435, other: 290 },
  { year: '2020', coal: 5120, hydro: 2650, wind: 1550, solar: 775, nuclear: 465, other: 310 },
  { year: '2021', coal: 5340, hydro: 2775, wind: 1650, solar: 825, nuclear: 495, other: 330 },
  { year: '2022', coal: 5560, hydro: 2875, wind: 1750, solar: 875, nuclear: 525, other: 350 },
  { year: '2023', coal: 5780, hydro: 2975, wind: 1850, solar: 925, nuclear: 555, other: 370 },
  { year: '2024', coal: 5990, hydro: 3075, wind: 1950, solar: 975, nuclear: 585, other: 390 }
]);

const initChart = () => {
  chart.value = echarts.init(document.getElementById('chart'));
  updateChart();
};

const initNationalPowerGenerationChart = () => {
  nationalPowerGenerationChart.value = echarts.init(document.getElementById('national-power-generation'));
  updateNationalPowerGenerationChart();
};

const initNationalInstalledCapacityChart = () => {
  nationalInstalledCapacityChart.value = echarts.init(document.getElementById('national-installed-capacity'));
  updateNationalInstalledCapacityChart();
};

const updateChart = () => {
  const option = {
    title: {
      text: '碳排放趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['碳排放量', '能源消耗'],
      bottom: '10px'
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: tableData.value.map(item => item.year),
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数值',
        min: 0,
        max: 400,
        interval: 50,
        axisLabel: {
          formatter: '{value} '
        }
      }
    ],
    series: [
      {
        name: '碳排放量',
        type: chartType.value,
        data: tableData.value.map(item => item.emission),
        areaStyle: {},
        itemStyle: {
          color: '#FF6347' // 修改为橙红色
        }
      },
      {
        name: '能源消耗',
        type: chartType.value,
        data: tableData.value.map(item => item.energy),
        areaStyle: {},
        itemStyle: {
          color: '#4682B4' // 修改为钢蓝色
        }
      }
    ]
  };

  if (chartType.value === 'pie') {
    option.series = [
      {
        name: '碳排放量',
        type: 'pie',
        radius: '50%',
        data: tableData.value.map(item => ({ value: item.emission, name: item.year })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          color: '#FF6347' // 修改为橙红色
        }
      },
      {
        name: '能源消耗',
        type: 'pie',
        radius: '50%',
        data: tableData.value.map(item => ({ value: item.energy, name: item.year })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          color: '#4682B4' // 修改为钢蓝色
        }
      }
    ];
  }

  chart.value.setOption(option);
};

const updateNationalPowerGenerationChart = () => {
  const option = {
    title: {
      text: '年度全国发电量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['火电', '水电', '风电', '太阳能', '核能', '其他能源'],
      bottom: '10px'
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: nationalPowerGenerationData.value.map(item => item.year),
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '发电量 (亿千瓦时)',
        min: 0,
        max: 7000,
        interval: 1000,
        axisLabel: {
          formatter: '{value} '
        }
      }
    ],
    series: [
      {
        name: '火电',
        type: 'line',
        data: [3000.5, 3101.2, 3202.8, 3153.4, 3304.1, 3405.7, 3506.3, 3607.9, 3708.5, 3809.1, 3910.7, 4011.3, 4112.9, 4053.5, 4204.1, 4305.7],
        areaStyle: {},
        itemStyle: {
          color: '#FF4500' // 橙色
        }
      },
      {
        name: '水电',
        type: 'line',
        data: [1000.1, 1101.2, 1202.3, 1153.4, 1304.5, 1405.6, 1506.7, 1607.8, 1708.9, 1809.0, 1910.1, 2011.2, 2112.3, 2053.4, 2204.5, 2305.6],
        areaStyle: {},
        itemStyle: {
          color: '#00BFFF' // 蓝色
        }
      },
      {
        name: '风电',
        type: 'line',
        data: [500.1, 551.2, 602.3, 575.4, 650.5, 701.6, 752.7, 803.8, 854.9, 905.0, 956.1, 1007.2, 1058.3, 1029.4, 1100.5, 1151.6],
        areaStyle: {},
        itemStyle: {
          color: '#32CD32' // 绿色
        }
      },
      {
        name: '太阳能',
        type: 'line',
        data: [300.1, 351.2, 402.3, 375.4, 450.5, 501.6, 552.7, 603.8, 654.9, 705.0, 756.1, 807.2, 858.3, 829.4, 900.5, 951.6],
        areaStyle: {},
        itemStyle: {
          color: '#FFD700' // 黄色
        }
      },
      {
        name: '核能',
        type: 'line',
        data: [200.1, 251.2, 302.3, 275.4, 350.5, 401.6, 452.7, 503.8, 554.9, 605.0, 656.1, 707.2, 758.3, 729.4, 800.5, 851.6],
        areaStyle: {},
        itemStyle: {
          color: '#8A2BE2' // 紫色
        }
      },
      {
        name: '其他能源',
        type: 'line',
        data: [100.1, 151.2, 202.3, 175.4, 250.5, 301.6, 352.7, 403.8, 454.9, 505.0, 556.1, 607.2, 658.3, 629.4, 700.5, 751.6],
        areaStyle: {},
        itemStyle: {
          color: '#FF69B4' // 粉红色
        }
      }
    ]
  };

  nationalPowerGenerationChart.value.setOption(option);
};

const updateNationalInstalledCapacityChart = () => {
  const option = {
    title: {
      text: '全国装机容量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['火电', '水电', '风电', '太阳能', '核能', '其他能源'],
      bottom: '10px'
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: nationalInstalledCapacityData.value.map(item => item.year),
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '装机容量 (万千瓦)',
        min: 0,
        max: 15000,
        interval: 2000,
        axisLabel: {
          formatter: '{value} '
        }
      }
    ],
    series: [
      {
        name: '火电',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.coal),
        areaStyle: {},
        itemStyle: {
          color: '#ffd456' // 橙色
        }
      },
      {
        name: '水电',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.hydro),
        areaStyle: {},
        itemStyle: {
          color: '#346cff' // 蓝色
        }
      },
      {
        name: '风电',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.wind),
        areaStyle: {},
        itemStyle: {
          color: '#48d648' // 绿色
        }
      },
      {
        name: '太阳能',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.solar),
        areaStyle: {},
        itemStyle: {
          color: '#ff3c00' // 黄色
        }
      },
      {
        name: '核能',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.nuclear),
        areaStyle: {},
        itemStyle: {
          color: '#8100fa' // 紫色
        }
      },
      {
        name: '其他能源',
        type: 'line',
        data: nationalInstalledCapacityData.value.map(item => item.other),
        areaStyle: {},
        itemStyle: {
          color: '#ff0080' // 粉红色
        }
      }
    ]
  };

  nationalInstalledCapacityChart.value.setOption(option);
};

// const toggleChartType = () => {
//   const types = ['line', 'bar', 'pie'];
//   const currentIndex = types.indexOf(chartType.value);
//   chartType.value = types[(currentIndex + 1) % types.length];
//   updateChart();
//   updateNationalPowerGenerationChart();
//   updateNationalInstalledCapacityChart();
// };

const downloadReport = () => {
  //展示全屏loading
  ElLoading.service({
    lock: true,
    text: '正在生成报告，请稍等...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  const element = document.querySelector('.el-tab-pane[name="report"]');
  html2pdf().from(element).save('数据分析报告.pdf');

  setTimeout(() => {
    ElLoading.service().close();
    ElMessage.success('报告已成功下载');
  }, 2000);
};

onMounted(() => {
  initChart();
  initNationalPowerGenerationChart();
  initNationalInstalledCapacityChart();
});

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
  if (nationalPowerGenerationChart.value) {
    nationalPowerGenerationChart.value.dispose();
  }
  if (nationalInstalledCapacityChart.value) {
    nationalInstalledCapacityChart.value.dispose();
  }
});
</script>



<style scoped>
.el-main {
  padding: 20px;
  height: 100%;
  transition: background-color 0.3s ease;
}

.el-tabs__content {
  height: calc(100% - 40px);
}

.el-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.3s ease;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
}

.el-table {
  width: 100%;
  transition: background-color 0.3s ease;
  border-radius: 10px;
  overflow: hidden;
}

.el-divider {
  margin: 20px 0;
  border-color: #e0e0e0;
}

h2, h3 {
  margin-top: 0;
  color: #333;
}

ul, ol {
  margin: 10px 0;
  padding-left: 20px;
  list-style-type: disc;
}

p {
  margin: 10px 0;
  line-height: 1.6;
  color: #666;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

h2 {
  font-size: 20px;
  margin-bottom: 15px;
}

h3 {
  font-size: 18px;
  margin-bottom: 10px;
}
</style>
