<template>
  <div class="deep-dig-container">
    <div class="left-section">
      <!-- Module 1: 被诉企业列表 -->
      <div class="box company-list-box">
        <div class="box-header">
          <div class="header-left-bar"></div>
          <div class="title">被诉企业列表</div>
          <div class="header-right">
            <div class="icon">
              <img src="@/assets/icons/box-header-icon3.png" alt="" />
            </div>
          </div>
        </div>
        <div class="box-content">
          <div class="filter-row">
            <el-select v-model="selectedArea" placeholder="全部领域" class="area-select" clearable @change="fetchEnterpriseList">
              <el-option label="全部领域" value="" />
              <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-input
              v-model="searchText"
              placeholder="搜索实体"
              class="search-input"
              :suffix-icon="Search"
              clearable
              @input="handleSearchInput"
            />
          </div>
          <div class="enterprise-list" v-loading="listLoading">
            <div class="list-label">企业名称</div>
            <div
              v-for="(item, index) in enterpriseList"
              :key="item.ORGID || index"
              class="enterprise-item"
              :class="{ active: activeIndex === index }"
              @click="handleEnterpriseClick(item, index)"
            >
              <div class="icon">
                <img src="@/assets/icons/default-icon1.png" alt="" />
              </div>
              <div class="name">{{ item.ORGNAME }}</div>
            </div>
            <el-empty v-if="!enterpriseList.length && !listLoading" description="暂无数据" />
          </div>
        </div>
      </div>
    </div>

    <div class="right-section">
      <!-- Module 2: 进出口数据 -->
      <div class="box chart-box">
        <div class="box-header">
          <div class="header-left-bar"></div>
          <div class="title">进出口数据</div>
          <div class="header-right">
            <div class="btn-group">
              <div class="btn active">出口收入</div>
            </div>
            <div class="icon-group">
              <div class="icon"><img src="@/assets/icons/box-header-icon1.png" alt="" /></div>
              <div class="icon"><img src="@/assets/icons/box-header-icon2.png" alt="" /></div>
              <div class="icon"><img src="@/assets/icons/box-header-icon3.png" alt="" /></div>
            </div>
          </div>
        </div>
        <div class="box-content chart-content">
          <div class="chart-wrapper" v-loading="exportLoading">
            <div ref="exportChartRef" class="echarts-container"></div>
          </div>
          <div class="footer-msg">
            <div class="msg-left">
              <img src="@/assets/icons/box-footer-left-icon.png" alt="" />
            </div>
            <div class="msg-center">列入实体清单后企业营收初期下降，后基本趋于稳定。</div>
            <div class="msg-right">
              <img src="@/assets/icons/box-footer-right-icon.png" alt="" />
            </div>
          </div>
        </div>
      </div>

      <!-- Module 3: 企业经营情况 -->
      <div class="box chart-box">
        <div class="box-header">
          <div class="header-left-bar"></div>
          <div class="title">企业经营情况</div>
          <div class="header-right">
            <div class="btn-group">
              <div 
                class="btn" 
                :class="{ active: businessActiveBtn === '营收' }"
                @click="handleBusinessToggle('营收')"
              >营收</div>
              <div 
                class="btn"
                :class="{ active: businessActiveBtn === '净利润' }"
                @click="handleBusinessToggle('净利润')"
              >净利润</div>
            </div>
            <div class="icon-group">
              <div class="icon"><img src="@/assets/icons/box-header-icon1.png" alt="" /></div>
              <div class="icon"><img src="@/assets/icons/box-header-icon2.png" alt="" /></div>
              <div class="icon"><img src="@/assets/icons/box-header-icon3.png" alt="" /></div>
            </div>
          </div>
        </div>
        <div class="box-content chart-content">
          <div class="chart-wrapper" v-loading="businessLoading">
            <div ref="businessChartRef" class="echarts-container"></div>
          </div>
          <div class="footer-msg">
            <div class="msg-left">
              <img src="@/assets/icons/box-footer-left-icon.png" alt="" />
            </div>
            <div class="msg-center">列入实体清单后企业研发资金投入逐渐提高。</div>
            <div class="msg-right">
              <img src="@/assets/icons/box-footer-right-icon.png" alt="" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import * as echarts from 'echarts';
import { getSuedOrg, getOrgImportAndExport, getRevenue, getNetProfit } from '@/api/marketAccessRestrictions';

const route = useRoute();
const selectedArea = ref('');
const searchText = ref('');
const activeIndex = ref(0);
const businessActiveBtn = ref('营收');
const listLoading = ref(false);
const exportLoading = ref(false);
const businessLoading = ref(false);

const areaOptions = [
  { label: '人工智能', value: '1' },
  { label: '生物科技', value: '2' },
  { label: '新一代通信技术', value: '3' },
  { label: '量子科技', value: '4' },
  { label: '新能源', value: '5' },
  { label: '集成电路', value: '6' },
  { label: '海洋', value: '7' },
  { label: '先进制造', value: '8' },
  { label: '新材料', value: '9' },
  { label: '航空航天', value: '10' },
  { label: '太空', value: '13' },
  { label: '深海', value: '11' },
  { label: '极地', value: '12' },
  { label: '核', value: '14' },
  { label: '政治', value: '20' },
  { label: '外交', value: '21' },
  { label: '经济', value: '22' },
  { label: '军事', value: '23' },
  { label: '科技', value: '24' },
  { label: '安全', value: '25' },
  { label: '其他', value: '99' },
];

const enterpriseList = ref([]);

const exportChartRef = ref(null);
const businessChartRef = ref(null);

let exportChart = null;
let businessChart = null;

const chartLabels = ref([]);
const chartData = ref([]);

const businessLabels = ref([]);
const businessData = ref([]);

// 获取企业列表
const fetchEnterpriseList = async () => {
  listLoading.value = true;
  try {
    const params = {
      searchId: route.query.searchId,
      orgName: searchText.value
    }
    if (selectedArea.value) {
      params.area = selectedArea.value;
    }
    const res = await getSuedOrg(params);
    if (res.code === 200) {
      enterpriseList.value = res.data || [];
      // 默认选中第一个并加载其进出口数据
      if (enterpriseList.value.length > 0) {
        handleEnterpriseClick(enterpriseList.value[0], 0);
      }
    }
  } catch (error) {
    console.error('获取被诉企业列表失败:', error);
  } finally {
    listLoading.value = false;
  }
};

// 获取进出口数据
const fetchExportData = async (orgId) => {
  exportLoading.value = true;
  chartLabels.value = [];
  chartData.value = [];
  try {
    const res = await getOrgImportAndExport({ id: orgId });
    if (res.code === 200 && res.data && res.data.length > 0) {
      // 对数据按年份排序
      const sortedData = res.data.sort((a, b) => a.year - b.year);
      
      const labels = [];
      const values = [];
      
      sortedData.forEach(item => {
        ['q1', 'q2', 'q3', 'q4'].forEach(q => {
          if (item[q] !== undefined && item[q] !== null) {
            labels.push(`${item.year} ${q.toUpperCase()}`);
            values.push(item[q]);
          }
        });
      });

      // 更新图表
      chartLabels.value = labels;
      chartData.value = values;
    }
    updateExportChart();
  } catch (error) {
    console.error('获取进出口数据失败:', error);
    updateExportChart();
  } finally {
    exportLoading.value = false;
  }
};

// 获取经营情况数据
const fetchBusinessData = async (orgId) => {
  businessLoading.value = true;
  businessLabels.value = [];
  businessData.value = [];
  try {
    const api = businessActiveBtn.value === '营收' ? getRevenue : getNetProfit;
    const res = await api({ id: orgId });
    if (res.code === 200 && res.data && res.data.length > 0) {
      const sortedData = res.data.sort((a, b) => a.year - b.year);
      businessLabels.value = sortedData.map(item => item.year + '年');
      businessData.value = sortedData.map(item => item.count);
    }
    updateBusinessChart();
  } catch (error) {
    console.error(`获取企业${businessActiveBtn.value}数据失败:`, error);
    updateBusinessChart();
  } finally {
    businessLoading.value = false;
  }
};

const updateExportChart = () => {
  if (exportChart) {
    const lastValue = chartData.value[chartData.value.length - 1];
    const lastLabel = chartLabels.value[chartLabels.value.length - 1];
    exportChart.setOption(getOption(chartData.value, lastValue, chartLabels.value, lastLabel));
  }
};

const updateBusinessChart = () => {
  if (businessChart) {
    const lastValue = businessData.value[businessData.value.length - 1];
    const lastLabel = businessLabels.value[businessLabels.value.length - 1];
    businessChart.setOption(getOption(businessData.value, lastValue, businessLabels.value, lastLabel));
  }
};

let searchTimer = null;
const handleSearchInput = () => {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    fetchEnterpriseList();
  }, 500);
};

const handleEnterpriseClick = (item, index) => {
  activeIndex.value = index;
  if (item.ORGID) {
    fetchExportData(item.ORGID);
    fetchBusinessData(item.ORGID);
  }
};

const getOption = (data, pointValue, labels, pointLabel) => {
  const hasData = data && data.length > 0;
  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderWidth: 0,
      boxShadow: '0 0 10px rgba(0,0,0,0.1)',
      textStyle: {
        color: '#3B414B',
      },
    },
    grid: {
      top: '40',
      left: '10',
      right: '40',
      bottom: '10',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: labels || [],
      axisLine: {
        lineStyle: {
          color: '#E0E0E0',
        },
      },
      axisLabel: {
        color: '#84888E',
        fontSize: 12,
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      splitNumber: 5,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#F0F0F0',
        },
      },
      axisLabel: {
        color: '#84888E',
        fontSize: 12,
        formatter: (value) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万';
          }
          return value;
        }
      },
    },
    series: [
      {
        name: '数据',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: data || [],
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(23, 107, 240, 0.2)' },
            { offset: 1, color: 'rgba(23, 107, 240, 0.02)' },
          ]),
        },
        lineStyle: {
          color: '#176BF0',
          width: 2,
        },
        markLine: hasData ? {
          symbol: 'none',
          label: {
            show: true,
            position: 'end',
            formatter: '337调查',
            color: '#F56C6C',
            backgroundColor: '#fff',
            padding: [2, 4],
            fontSize: 12,
          },
          lineStyle: {
            color: '#F56C6C',
            type: 'dashed',
            width: 1,
          },
          data: labels && labels.includes('2024 Q2') ? [{ xAxis: '2024 Q2' }] : [],
        } : null,
        markPoint: hasData ? {
          symbol: 'circle',
          symbolSize: 8,
          label: {
            show: true,
            position: 'top',
            offset: [0, -5],
            formatter: '{c}亿元',
            color: '#176BF0',
            fontWeight: 'bold',
            fontSize: 14,
          },
          itemStyle: {
            color: '#176BF0',
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: 5,
            shadowColor: 'rgba(0,0,0,0.2)',
          },
          data: [{ value: pointValue, xAxis: pointLabel || (labels ? labels[labels.length - 1] : ''), yAxis: pointValue }],
        } : null,
      },
    ],
  };
};

const initCharts = () => {
  if (exportChartRef.value) {
    exportChart = echarts.init(exportChartRef.value);
    exportChart.setOption(getOption([], 0, []));
  }

  if (businessChartRef.value) {
    businessChart = echarts.init(businessChartRef.value);
    businessChart.setOption(getOption([], 0, []));
  }
};

const handleBusinessToggle = (type) => {
  businessActiveBtn.value = type;
  const currentOrg = enterpriseList.value[activeIndex.value];
  if (currentOrg && currentOrg.ORGID) {
    fetchBusinessData(currentOrg.ORGID);
  }
};

onMounted(() => {
  fetchEnterpriseList();
  nextTick(() => {
    initCharts();
    window.addEventListener('resize', () => {
      exportChart && exportChart.resize();
      businessChart && businessChart.resize();
    });
  });
});
</script>

<style lang="scss" scoped>
.deep-dig-container {
  display: flex;
  width: 1600px;
  margin: 20px auto;
  gap: 16px;

  .box {
    background: #ffffff;
    border-radius: 4px;
    box-shadow: 0px 0px 15px 0px rgba(60, 87, 126, 0.1);
    display: flex;
    flex-direction: column;

    .box-header {
      height: 56px;
      display: flex;
      align-items: center;
      padding: 0 16px;
      position: relative;
      border-bottom: 1px solid #f0f0f0;

      .header-left-bar {
        width: 8px;
        height: 16px;
        background: var(--color-main-active, #176bf0);
        border-radius: 0 4px 4px 0;
        position: absolute;
        left: 0;
      }

      .title {
        margin-left: 12px;
        font-size: 18px;
        font-weight: bold;
        color: var(--color-main-active, #176bf0);
      }

      .header-right {
        margin-left: auto;
        display: flex;
        align-items: center;
        gap: 12px;

        .btn-group {
          display: flex;
          border: 1px solid #e0e0e0;
          border-radius: 4px;
          overflow: hidden;

          .btn {
            padding: 4px 12px;
            font-size: 14px;
            color: #5f656c;
            cursor: pointer;
            background: #fff;

            &.active {
              background: #e7f3ff;
              color: #176bf0;
              border: 1px solid #176bf0;
              margin: -1px;
            }

            &:not(:last-child) {
              border-right: 1px solid #e0e0e0;
            }
          }
        }

        .icon-group {
          display: flex;
          gap: 4px;

          .icon {
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;

            img {
              width: 20px;
              height: 20px;
            }
          }
        }
        
        .icon {
          width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 20px;
            height: 20px;
          }
        }
      }
    }

    .box-content {
      padding: 16px;
      flex: 1;
    }
  }

  .left-section {
    width: 480px;
    flex-shrink: 0;

    .company-list-box {
      height: 100%;

      .filter-row {
        display: flex;
        gap: 8px;
        margin-bottom: 16px;

        .area-select {
          width: 150px;
        }

        .search-input {
          flex: auto;
          width: 20px;
        }
      }

      .enterprise-list {
        .list-label {
          font-size: 14px;
          font-weight: bold;
          color: #3b414b;
          margin-bottom: 12px;
        }

        .enterprise-item {
          display: flex;
          align-items: center;
          padding: 10px 12px;
          border-bottom: 1px solid #f5f5f5;
          cursor: pointer;
          transition: background 0.2s;

          &:hover {
            background: #f9f9f9;
          }

          &.active {
            background: #f0f7ff;
            border-left: 3px solid #176bf0;
            padding-left: 9px;

            .name {
              color: #176bf0;
              font-weight: bold;
            }
          }

          .icon {
            width: 16px;
            height: 16px;
            margin-right: 12px;
            img {
              width: 100%;
              height: 100%;
            }
          }

          .name {
            font-size: 14px;
            color: #3b414b;
          }
        }
      }
    }
  }

  .right-section {
    flex: auto;
    width: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .chart-box {
      height: 400px;

      .chart-content {
        display: flex;
        flex-direction: column;
        padding-bottom: 12px;

        .chart-wrapper {
          flex: 1;
          position: relative;
          .echarts-container {
            width: 100%;
            height: 100%;
          }
        }

        .footer-msg {
          margin-top: 12px;
          background: #f6fbff;
          border: 1px solid #e7f3ff;
          border-radius: 4px;
          padding: 8px 12px;
          display: flex;
          align-items: center;

          .msg-left {
            width: 18px;
            height: 18px;
            margin-right: 8px;
            img {
              width: 100%;
            }
          }

          .msg-center {
            flex: 1;
            font-size: 14px;
            color: #176bf0;
          }

          .msg-right {
            width: 16px;
            height: 16px;
            cursor: pointer;
            img {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style>
