<template>
  <div class="deep-dig-container">
    <div class="left-section">
      <!-- Module 1: 被诉企业列表 -->
      <div class="box company-list-box" v-loading="box1loading">
        <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="areaInfo.id" :empty-values="[null, undefined]" class="area-select" @change="onEnterpriseList()">
              <el-option label="全部领域" value="" />
              <el-option v-for="item in areaInfo.list" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input v-model="searchText" placeholder="搜索实体" class="search-input" :prefix-icon="Search" clearable @clear="onEnterpriseList()" @keyup.enter="onEnterpriseList()" />
          </div>
          <div class="enterprise-list">
            <div class="list-label">企业名称</div>
            <div v-for="item in enterpriseList" :key="item.ORGID" class="enterprise-item"
              :class="{ active: activeOrg === item.ORGID }" @click="handleEnterpriseClick(item)"
            >
              <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" style="height: 100%;" description="暂无数据" />
          </div>
        </div>
      </div>
    </div>

    <div class="right-section">
      <!-- Module 2: 进出口数据 -->
      <div class="box chart-box" v-loading="box2loading">
        <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="chart-wrapper" v-show="chartLabels.length">
          <div ref="exportChartRef" class="echarts-container"></div>
        </div>
        <el-empty v-if="!chartLabels.length" style="height:20px; flex:auto;" description="暂无数据" />
        <AiReport ref="refAiReport2"></AiReport>
      </div>

      <!-- Module 3: 企业经营情况 -->
      <div class="box chart-box" v-loading="box3loading">
        <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="chart-wrapper" v-show="businessLabels.length">
          <div ref="businessChartRef" class="echarts-container"></div>
        </div>
        <el-empty v-if="!businessLabels.length" style="height:20px; flex:auto;" description="暂无数据" />
        <AiReport ref="refAiReport3"></AiReport>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, 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';
import { getDecreehylyList } from "@/api/decree/influence";

import AiReport from '@/views/marketAccessRestrictions/marketAccessHome/com/AiReport.vue';

const route = useRoute();
const searchText = ref('');
const activeOrg = ref('');
const businessActiveBtn = ref('营收');
const box1loading = ref(false);
const box2loading = ref(false);
const box3loading = ref(false);

const refAiReport2 = ref(null)
const refAiReport3 = ref(null)

// 行业领域
const areaInfo = reactive({
	list: [],
	id: "",
})
const handleGetHylyList = async () => {
	try {
		const res = await getDecreehylyList();
		console.log("行业领域:", res);
		if (res.code === 200) {
			areaInfo.list = res.data || [];
		}
	} catch (error) {}
};

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 onEnterpriseList = async () => {
  box1loading.value = true;
  try {
    const res = await getSuedOrg({
      searchId: route.query.searchId,
      orgName: searchText.value,
      area: areaInfo.id || null,
    });
    if (res.code==200 && res.data) {
      enterpriseList.value = res.data || [];
    } else {
      enterpriseList.value = [];
    }
  } catch (error) {
    enterpriseList.value = [];
  }
  // 默认选中第一个并加载其进出口数据
  if (enterpriseList.value.length > 0) {
    handleEnterpriseClick(enterpriseList.value[0]);
  } else {
    chartLabels.value = [];
    chartData.value = [];
    businessLabels.value = [];
    businessData.value = [];
    refAiReport2.value?.onDataInfo({ type: "折线图", name: "进出口数据", data: {label: [], data: []} })
    refAiReport3.value?.onDataInfo({ type: "折线图", name: "企业经营情况", data: {label: [], data: []} })
  }
  box1loading.value = false;
};

// 进出口数据
const fetchExportData = async (orgId) => {
  box2loading.value = true;
  try {
    const res = await getOrgImportAndExport({ id: orgId });
    chartLabels.value = [];
    chartData.value = [];
    if (res.code === 200 && res.data?.length) {
      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;
    }
  } catch (error) {}
  updateExportChart();
  refAiReport2.value?.onDataInfo({ type: "折线图", name: "进出口数据", data: {label: chartLabels.value, data: chartData.value} })
  box2loading.value = false;
};

// 企业经营情况
const fetchBusinessData = async (orgId) => {
  box3loading.value = true;
  try {
    const api = businessActiveBtn.value === '营收' ? getRevenue : getNetProfit;
    const res = await api({ id: orgId });
    businessLabels.value = [];
    businessData.value = [];
    if (res.code === 200 && res.data?.length) {
      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);
    }
  } catch (error) {}
  updateBusinessChart();
  refAiReport3.value?.onDataInfo({ type: "折线图", name: "企业经营情况", data: {label: businessLabels.value, data: businessData.value} })
  box3loading.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));
    nextTick(() => exportChart.resize() )
  }
};

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));
    nextTick(() => businessChart.resize() )
  }
};

const handleEnterpriseClick = (item) => {
  activeOrg.value = item.ORGID;
  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.find(item => item.ORGID === activeOrg.value);
  if (currentOrg) fetchBusinessData(currentOrg.ORGID);
};

onMounted(() => {
  handleGetHylyList();
  onEnterpriseList();
  initCharts();
});
</script>

<style lang="scss" scoped>
.deep-dig-container {
  width: 1600px;
  height: calc(100vh - 146px);
  margin: 0 auto;
  padding: 16px 0;
  overflow: hidden;
  display: flex;
  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;
      height: 20px;
      flex: auto;
      display: flex;
      flex-direction: column;
    }
  }

  .left-section {
    width: 480px;
    height: 100%;

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

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

        .area-select {
          width: 150px;
        }

        .search-input {
          flex: auto;
          width: 20px;
          background-color: #fff;
          border: 1px solid rgba(234, 236, 238, 1);
          border-radius: 4px;
        }
      }

      .enterprise-list {
        height: 20px;
        flex: auto;
        .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: 20px;
      flex: auto;
      position: relative;
      .chart-wrapper {
        padding-bottom: 12px;
        height: 20px;
        flex: auto;
        position: relative;
        .echarts-container {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
