<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-form style="display: flex;">
            <el-form-item label="产品">
              <el-input v-model="searchQuery" placeholder="搜索产品" style="margin-bottom: 20px;"/>
            </el-form-item>
            <el-form-item label="行业">
              <el-select v-model="selectedIndustry" placeholder="请选择行业" style="width: 300px;margin-bottom: 20px;">
                <el-option
                    v-for="industry in industries"
                    :key="industry.value"
                    :label="industry.label"
                    :value="industry.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addProductModal">添加产品模型</el-button>
          <el-dialog v-model="addProductModalVisible">
            <template #header>
              添加产品模型
            </template>
            <template #default>
              <el-form ref="addForm">
                <el-form-item label="行业" required>
                  <el-select v-model="addProdForm.industry" placeholder="请选择行业">
                    <el-option
                        v-for="industry in industries"
                        :key="industry.value"
                        :label="industry.label"
                        :value="industry.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="产品名称" required>
                  <el-input v-model="addProdForm.name" placeholder="请输入产品名称"/>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input v-model="addProdForm.description" placeholder="请输入描述"/>
                </el-form-item>
                <el-form-item label="碳足迹">
                  <el-input-number min="0" step="0.1" v-model="addProdForm.carbonFootprint" placeholder="请输入碳足迹"/>
                </el-form-item>
              </el-form>
            </template>
            <template #footer>
              <el-button type="primary" @click="addProduct">确定</el-button>
            </template>
          </el-dialog>
          <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>
            <div ref="processChart" style="width: 100%; height: 400px;"></div>
          </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>-->
<!--          -->
<!--        </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,
  ElMessage
} from 'element-plus'

const activeTab = ref('productLibrary')
const selectedIndustry = ref('')
const searchQuery = ref('')
const productDialogVisible = ref(false)
const selectedProduct = ref({})
const addProductModalVisible = ref(false);
const addForm = reactive({});
const addProdForm = ref({
  industry: '',
  name: '',
  description: '',
  carbonFootprint: 0
})
const addProduct = () => {
  if (addProdForm.value.industry && addProdForm.value.name) {
    const industry = addProdForm.value.industry;
    industryData[industry].push({
      name: addProdForm.value.name,
      description: addProdForm.value.description,
      carbonFootprint: addProdForm.value.carbonFootprint
    });
    ElMessage.success('产品添加成功');
    addProductModalVisible.value = false;
    addProdForm.value = {
      industry: '',
      name: '',
      description: '',
      carbonFootprint: 0
    };
  } else {
    ElMessage.error('请填写完整信息');
  }
}
const addProductModal = () => {
  addProductModalVisible.value = true;
}
const industries = [
  {label: '钢铁', value: 'steel'},
  {label: '有色金属', value: 'nonferrous'},
  {label: '石化', value: 'petrochemical'},
  {label: '化工', value: 'chemical'},
  {label: '建材', value: 'construction'}
]

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}
  ],
  nonferrous: [
    {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}
  ],
  petrochemical: [
    {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}
  ],
  chemical: [
    {name: '氯碱化工模型', description: '氯碱化工生产过程', carbonFootprint: 0.3},
    {name: '烧碱模型', description: '烧碱生产过程', carbonFootprint: 1.2},
    {name: '聚氯乙烯(PVC)模型', description: '聚氯乙烯(PVC)生产过程', 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}
  ],
  construction: [
    {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}
  ]
}

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 = async () => {
  await nextTick(); // 确保 DOM 已经更新
  if (!processChart.value) {
    console.error('processChart is not available');
    return;
  }

  const chart = echarts.init(processChart.value);
  const selectedIndustryData = industryData[selectedIndustry.value] || [];
  const treeData = {
    name: industries.find(item => item.value === selectedIndustry.value).label,
    children: selectedIndustryData.map(product => ({
      name: product.name,
      value: product.carbonFootprint,
      itemStyle: {
        color: getColorForCarbonFootprint(product.carbonFootprint),
        borderColor: getColorForCarbonFootprint(product.carbonFootprint)
      }
    }))
  };

  const option = {
    backgroundColor: '#fff',
    title: {
      subtext: '碳排放路径图',
      left: 'center'
    },
    series: [
      {
        type: 'tree',
        id: 0,
        name: 'tree',
        data: [treeData],
        top: '18%',
        bottom: '14%',
        layout: 'orthogonal',
        symbol: 'emptyCircle',
        symbolSize: 7,
        initialTreeDepth: 3,
        animationDurationUpdate: 750,
        label: {
          position: 'left',
          verticalAlign: 'middle',
          align: 'right',
          fontSize: 16
        },
        leaves: {
          label: {
            position: 'right',
            verticalAlign: 'middle',
            align: 'left'
          }
        },
        expandAndCollapse: true,
        roam: true,
        itemStyle: {
          color: '#1f77b4',
          borderColor: '#1f77b4'
        }
      }
    ],
    tooltip: {
      trigger: 'item'
    }
  };
  chart.setOption(option);

  // 添加点击事件
  chart.on('click', (params) => {
    if (params.dataType === 'node') {
      const product = selectedIndustryData.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 = async (row) => {
  selectedProduct.value = row
  productDialogVisible.value = true
  await initProcessChart();
}
</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>
