<template>
  <div class="carbon-footprint-module">
    <el-header class="header">
      <h2>碳足迹评估认证模块</h2>
    </el-header>
    <el-main>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="产品模型库" name="productLibrary">
          <h3>产品模型库</h3>
          <el-input v-model="searchQuery" placeholder="搜索产品" style="margin-bottom: 20px;" />
          <el-select v-model="selectedIndustry" placeholder="请选择行业" style="margin-bottom: 20px;">
            <el-option
                v-for="industry in industries"
                :key="industry.value"
                :label="industry.label"
                :value="industry.value"
            />
          </el-select>
          <el-table :data="filteredProducts" style="width: 100%" @row-click="showProductDetails">
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="carbonFootprint" label="碳足迹" />
          </el-table>
          <el-dialog v-model="productDialogVisible" title="产品详细信息">
            <p><strong>产品名称:</strong> {{ selectedProduct.name }}</p>
            <p><strong>描述:</strong> {{ selectedProduct.description }}</p>
            <p><strong>碳足迹:</strong> {{ selectedProduct.carbonFootprint }} kg CO2e</p>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="工序积木图" name="processDiagram">
          <h3>工序积木图</h3>
          <el-select v-model="selectedIndustry" placeholder="请选择行业" style="margin-bottom: 20px;">
            <el-option
                v-for="industry in industries"
                :key="industry.value"
                :label="industry.label"
                :value="industry.value"
            />
          </el-select>
          <div ref="processChart" style="width: 100%; height: 400px;"></div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { ElHeader, ElMain, ElSelect, ElOption, ElTable, ElTableColumn, ElTabs, ElTabPane, ElInput, ElDialog } from 'element-plus'

const activeTab = ref('productLibrary')
const selectedIndustry = ref('')
const searchQuery = ref('')
const productDialogVisible = ref(false)
const selectedProduct = ref({})

const industries = [
  { label: '钢铁', value: 'steel' },
  { label: '水泥', value: 'cement' },
  { label: '动力电池', value: 'battery' }
]

const industryData = {
  steel: [
    { name: '高炉炼铁', description: '高炉炼铁过程', carbonFootprint: 1.5 },
    { name: '电炉炼钢', description: '电炉炼钢过程', carbonFootprint: 0.8 },
    { name: '轧钢', description: '轧钢过程', carbonFootprint: 0.5 },
    { name: '热处理', description: '钢材热处理过程', carbonFootprint: 0.6 },
    { name: '冷轧', description: '冷轧过程', carbonFootprint: 0.4 },
    { name: '涂层', description: '钢材表面涂层过程', carbonFootprint: 0.3 },
    { name: '检验', description: '钢材质量检验过程', carbonFootprint: 0.2 },
    { name: '包装', description: '钢材包装过程', carbonFootprint: 0.1 }
  ],
  cement: [
    { name: '石灰石开采', description: '石灰石开采过程', carbonFootprint: 0.3 },
    { name: '熟料烧成', description: '熟料烧成过程', carbonFootprint: 1.2 },
    { name: '水泥粉磨', description: '水泥粉磨过程', carbonFootprint: 0.4 },
    { name: '包装', description: '水泥包装过程', carbonFootprint: 0.2 },
    { name: '运输', description: '水泥运输过程', carbonFootprint: 0.1 },
    { name: '存储', description: '水泥存储过程', carbonFootprint: 0.1 },
    { name: '检验', description: '水泥质量检验过程', carbonFootprint: 0.2 },
    { name: '销售', description: '水泥销售过程', carbonFootprint: 0.1 }
  ],
  battery: [
    { name: '锂矿开采', description: '锂矿开采过程', carbonFootprint: 0.5 },
    { name: '正极材料生产', description: '正极材料生产过程', carbonFootprint: 1.0 },
    { name: '负极材料生产', description: '负极材料生产过程', carbonFootprint: 0.8 },
    { name: '电解液制备', description: '电解液制备过程', carbonFootprint: 0.6 },
    { name: '电池组装', description: '电池组装过程', carbonFootprint: 0.7 },
    { name: '性能测试', description: '电池性能测试过程', carbonFootprint: 0.3 },
    { name: '包装', description: '电池包装过程', carbonFootprint: 0.2 },
    { name: '运输', description: '电池运输过程', carbonFootprint: 0.1 }
  ]
}

const filteredProducts = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return selectedIndustry.value
      ? industryData[selectedIndustry.value].filter(product =>
          product.name.toLowerCase().includes(query) ||
          product.description.toLowerCase().includes(query) ||
          product.carbonFootprint.toString().includes(query)
      )
      : []
})

const processChart = ref(null)

const initProcessChart = () => {
  const chart = echarts.init(processChart.value)
  const option = {
    title: {
      text: '工序积木图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        if (params.seriesType === 'sankey') {
          if (params.dataType === 'node') {
            const product = filteredProducts.value.find(p => p.name === params.name)
            return `<strong>${product.name}</strong><br>碳足迹: ${product.carbonFootprint} kg CO2e<br>描述: ${product.description}`
          } else if (params.dataType === 'edge') {
            const sourceProduct = filteredProducts.value.find(p => p.name === params.data.source)
            const targetProduct = filteredProducts.value.find(p => p.name === params.data.target)
            return `${sourceProduct.name} -> ${targetProduct.name}<br>碳足迹: ${params.data.value} kg CO2e`
          }
        }
        return ''
      }
    },
    legend: {
      data: ['低', '中', '高'],
      top: 'bottom'
    },
    series: [
      {
        type: 'sankey',
        layout: 'none',
        data: filteredProducts.value.map(product => ({
          name: product.name,
          itemStyle: {
            color: getColorForCarbonFootprint(product.carbonFootprint)
          }
        })),
        links: filteredProducts.value.map((product, index) => ({
          source: index === 0 ? '原料' : product.name,
          target: index === filteredProducts.value.length - 1 ? '成品' : filteredProducts.value[index + 1].name,
          value: product.carbonFootprint,
          lineStyle: {
            color: 'source'
          }
        })),
        lineStyle: {
          curveness: 0.5
        },
        emphasis: {
          focus: 'adjacency'
        }
      }
    ]
  }
  chart.setOption(option)

  // 直接设置高亮
  if (selectedIndustry.value) {
    chart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: 0
    })
  }

  // 添加点击事件
  chart.on('click', (params) => {
    if (params.dataType === 'node') {
      const product = filteredProducts.value.find(p => p.name === params.name)
      if (product) {
        selectedProduct.value = product
        productDialogVisible.value = true
      }
    }
  })
}

const getColorForCarbonFootprint = (carbonFootprint) => {
  if (carbonFootprint < 0.5) return '#67C23A' // 绿色
  if (carbonFootprint < 1.0) return '#E6A23C' // 橙色
  return '#F56C6C' // 红色
}

watch(selectedIndustry, (newVal) => {
  if (newVal && activeTab.value === 'processDiagram') {
    initProcessChart()
  }
})

onMounted(() => {
  if (selectedIndustry.value && activeTab.value === 'processDiagram') {
    initProcessChart()
  }
})

const showProductDetails = (row) => {
  selectedProduct.value = row
  productDialogVisible.value = true
}
</script>

<style scoped>
.carbon-footprint-module {
  display: flex;
  flex-direction: column;
  height: 90vh;
}

.header {
  background-color: #409eff;
  color: white;
  text-align: center;
  padding: 10px 0;
}

.main {
  flex: 1;
  padding: 20px;
}
</style>
