<template>
  <view>
    <topHeader ref="topHeaderRef" @search="search"></topHeader>
    <a-space style="width: 100%; display: flex">
      <a-space direction="vertical" style="background-color: #fff; padding: 24px; width: 100%;">
        <a-space align="center">
          <span>性别分布</span>
          <a-popover position="tl">
            <a-button type="primary" class="pop-btn">
              <template #icon>
                <icon-question-circle />
              </template>
            </a-button>
            <template #content>
              <p>基于xxx获取数据xxx，一段文字描述该数据的获取方式和来源等xxx</p>
            </template>
          </a-popover>
        </a-space>
        <a-space>
          <div id="container" style="height: 180px; width: 180px"></div>

          <a-space direction="vertical" style="font-size: 14px">
            <a-space>
              <span style="width: 8px; height: 8px; background-color: #f64b31; border-radius: 50%"></span>
              <span>女性</span>
              <span style="width: 40px" v-if="genderData.length > 0">{{ genderData[0].rate * 100 }}%</span>
              <span>TGI</span>
              <span v-if="genderData.length > 0">{{ genderData[0].tgi }}</span>
            </a-space>
            <a-space>
              <span style="width: 8px; height: 8px; background-color: #2a59f3; border-radius: 50%"></span>
              <span>男性</span>
              <span style="width: 40px" v-if="genderData.length > 1">{{ genderData[1].rate * 100 }}%</span>
              <span>TGI</span>
              <span v-if="genderData.length > 1">{{ genderData[1].tgi }}</span>
            </a-space>
          </a-space>
        </a-space>
      </a-space>
      <a-space direction="vertical" style="background-color: #fff; padding: 24px; width: 100%;">
        <a-space style="display: flex; justify-content: space-between; width: 100%; font-size: 12px">
          <a-space align="center">
            <span>年龄分布</span>
            <a-popover position="tl">
              <a-button type="primary" class="pop-btn">
                <template #icon>
                  <icon-question-circle />
                </template>
              </a-button>
              <template #content>
                <p>基于xxx获取数据xxx，一段文字描述该数据的获取方式和来源等xxx</p>
              </template>
            </a-popover>
          </a-space>
          <a-space align="center">
            <span style="width: 16px; height: 8px; background-color: #6d4cfe; border-radius: 2px"></span>
            <span style="color: #6d4cfe">占比</span>
            <span style="width: 16px; height: 8px; background-color: #f64b31; border-radius: 2px"></span>
            <span style="color: #f64b31">TGI比</span>
          </a-space>
        </a-space>

        <a-space>
          <div id="age-container" style="height: 180px; width: 480px"></div>
        </a-space>
      </a-space>
    </a-space>
    <a-space direction="vertical" style="background-color: #fff; padding: 24px; flex: 1; margin-top: 24px">
      <a-space align="center">
        <span>地域分布</span>
        <a-popover position="tl">
          <a-button type="primary" class="pop-btn">
            <template #icon>
              <icon-question-circle />
            </template>
          </a-button>
          <template #content>
            <p>基于xxx获取数据xxx，一段文字描述该数据的获取方式和来源等xxx</p>
          </template>
        </a-popover>
      </a-space>
      <a-space>
        <a-space direction="vertical">
          <div id="chinaMap" style="height: 416px; width: 640px"></div>
          <a-space direction="vertical" style="font-size: 14px">
            <span>搜索指数</span>
            <a-space>
              <span>高</span>
              <span
                v-for="item in 5"
                :key="item"
                :style="{
                  width: `${18 - item * 2}px`,
                  height: `${18 - item * 2}px`,
                  backgroundColor: '#6D4CFE',
                  borderRadius: '50%',
                  display: 'inline-block',
                  margin: '0 2px',
                }"
              ></span>
              <span>低</span>
            </a-space>
          </a-space>
        </a-space>
        <a-space>
          <a-tabs default-active-key="1" @change="tabChange">
            <a-tab-pane key="1" title="省份">
              <a-table :data="geoList" :pagination="false">
                <template #columns>
                  <a-table-column title="排名" data-index="rank" />
                  <a-table-column title="省份" data-index="geo" />
                  <a-table-column title="分布占比" data-index="rate" />

                  <a-table-column title="TGI指数" data-index="tgi" />
                </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="2" title="城市">
              <a-table :data="geoList" :pagination="false">
                <template #columns>
                  <a-table-column title="排名" data-index="rank" />
                  <a-table-column title="城市" data-index="geo" />
                  <a-table-column title="分布占比" data-index="rate" />

                  <a-table-column title="TGI指数" data-index="tgi" />
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-space>
      </a-space>
    </a-space>
  </view>
</template>

<script setup>
import topHeader from './topHeader.vue';
import { fetchAgeDistributionsList, fetchGeoDistributionsList, fetchGenderDistributionsList } from '@/api/all/index';
import { ref, onMounted, computed } from 'vue';
import * as echarts from 'echarts';
import chinaJson from '@/assets/maps/china.json';

echarts.registerMap('china', chinaJson);
const scope = ref(1); //地域范围，1-省，2-市
const chartInstance = (ref < echarts.ECharts) | (null > null);
const topHeaderRef = ref();
// 从topHeader获取统一的状态
const selectedIndustry = computed(() => topHeaderRef.value?.selectedIndustry);
const selectedSubCategory = computed(() => topHeaderRef.value?.selectedSubCategory);
const selectedTimePeriod = computed(() => topHeaderRef.value?.selectedTimePeriod);
const genderData = ref([]);
const genderValueData = ref([]);
const ageValueData = ref([]);
const geoList = ref([]);
// 监听筛选条件变化
watch([selectedIndustry, selectedTimePeriod, selectedSubCategory], () => {
  getAgeDistributionsList();
  getGeoDistributionsList();
  getGenderDistributionsList();
  drawChinaMap();
});

const search = () => {
  getAgeDistributionsList();
  getGeoDistributionsList();
  getGenderDistributionsList();
  drawChinaMap();
};

// 获取年龄分布列表
const getAgeDistributionsList = async () => {
  const params = {
    industry_id: selectedIndustry.value,
    time_dimension: selectedTimePeriod.value,
  };
  if (selectedIndustry.value == undefined) {
    return;
  }
  if (selectedSubCategory.value == undefined) {
    return;
  }
  if (selectedSubCategory.value != 0) {
    parms['industry_id'] = selectedSubCategory.value;
  }
  const res = await fetchAgeDistributionsList(params);
  console.log('年龄分布：', res);
  ageValueData.value = res;
  drawAgeChart();
};

// 获得地理分布列表
const getGeoDistributionsList = async () => {
  const params = {
    scope: scope.value,
    industry_id: selectedIndustry.value,
    time_dimension: selectedTimePeriod.value,
  };
  if (selectedIndustry.value == undefined) {
    return;
  }
  if (selectedSubCategory.value == undefined) {
    return;
  }
  if (selectedSubCategory.value != 0) {
    parms['industry_id'] = selectedSubCategory.value;
  }
  const res = await fetchGeoDistributionsList(params);
  console.log('地理分布：', res);
  geoList.value = res;
};
// 获取性别分布列表
const getGenderDistributionsList = async () => {
  const params = {
    industry_id: selectedIndustry.value,
    time_dimension: selectedTimePeriod.value,
  };
  if (selectedIndustry.value == undefined) {
    return;
  }
  if (selectedSubCategory.value == undefined) {
    return;
  }
  if (selectedSubCategory.value != 0) {
    parms['industry_id'] = selectedSubCategory.value;
  }
  const res = await fetchGenderDistributionsList(params);
  genderData.value = [];
  genderData.value = [...res];
  await nextTick();
  genderValueData.value = [];
  for (let i = 0; i < res.length; i++) {
    genderValueData.value.push({
      value: res[i].rate * 100,
    });
  }

  drawChart();
};

const drawChart = () => {
  var dom = document.getElementById('container');
  var myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false,
  });
  var option;
  option = {
    color: ['#F64B31', '#2A59F3'],
    series: [
      {
        type: 'pie',
        avoidLabelOverlap: false,
        data: genderValueData.value,
        labelLine: {
          show: false, // 不显示引导线
        },
        radius: ['40%', '55%'],
      },
    ],
  };
  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }
};

const drawAgeChart = () => {
  const dom = document.getElementById('age-container');
  // 数据准备
  const xAxis = ageValueData.value.map((item) => item.age);
  const yAxis = ageValueData.value.map((item) => item.rate * 100);
  const yAxis2 = ageValueData.value.map((item) => item.tgi);
  const average = yAxis2.reduce((sum, val) => sum + val, 0) / yAxis2.length;

  // 图表初始化（强制使用2D渲染）
  const myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false,
    devicePixelRatio: window.devicePixelRatio * 1.5, // 提高渲染精度
  });

  // 动态计算刻度间隔
  const calcInterval = (data, base = 10) => {
    const range = Math.max(...data) - Math.min(...data);
    return Math.max(base, Math.ceil(range / 4 / base) * base);
  };

  // 核心配置
  const option = {
    animation: false, // 小尺寸下关闭动画提升性能
    tooltip: {
      trigger: 'axis',
      confine: true, // 确保tooltip不超出容器
      axisPointer: {
        type: 'shadow',
        label: {
          fontSize: 12, // 调小提示标签字号
          backgroundColor: 'rgba(0,0,0,0.7)',
        },
      },
    },
    grid: {
      top: 10,
      right: 30,
      bottom: 25,
      left: 40,
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: xAxis,
      axisLabel: {
        interval: 0,
        rotate: 0,
        fontSize: 12,
        margin: 2,
        hideOverlap: true, // 自动隐藏重叠标签
      },
      axisTick: {
        alignWithLabel: true,
        length: 3, // 缩短刻度线
      },
      axisLine: {
        lineStyle: {
          width: 0.5, // 减细轴线
        },
      },
    },
    yAxis: [
      {
        // 左侧百分比轴
        type: 'value',
        name: '占比',
        nameLocation: 'top',
        nameGap: 8,
        nameTextStyle: {
          fontSize: 12,
          padding: [0, 0, 3, 0], // 微调名称位置
        },
        min: 0,
        max: Math.ceil(Math.max(...yAxis) / 20) * 20,
        interval: calcInterval(yAxis, 20),
        axisLabel: {
          formatter: '{value}%',
          fontSize: 8,
          margin: 4,
          showMinLabel: true,
          showMaxLabel: true,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: 'rgba(255,255,255,0.3)',
            width: 0.8,
          },
        },
      },
      {
        // 右侧TGI轴
        type: 'value',
        name: 'TGI指数',
        nameLocation: 'top',
        nameGap: 8,
        nameTextStyle: {
          fontSize: 10,
          color: '#F64B31',
          padding: [0, 0, 3, 0],
        },
        min: Math.floor(Math.min(...yAxis2) / 50) * 50,
        max: Math.ceil(Math.max(...yAxis2) / 50) * 50,
        interval: calcInterval(yAxis2, 50),
        axisLabel: {
          fontSize: 8,
          margin: 4,
          color: '#F64B31',
        },
        axisLine: {
          lineStyle: {
            color: '#F64B31',
            width: 0.8,
          },
        },
      },
    ],
    series: [
      {
        // 柱状图
        name: '占比',
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          color: '#6d4cfe',
          borderRadius: [1, 1, 0, 0], // 微圆角
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%',
          fontSize: 8,
          color: '#fff',
          distance: 1, // 减小标签与柱子的距离
        },
        data: yAxis,
      },
      {
        // 折线图
        name: 'TGI',
        type: 'line',
        yAxisIndex: 1,
        symbol: 'none',
        lineStyle: {
          color: '#F64B31',
          width: 1.8,
        },
        markLine: {
          silent: true,
          symbol: 'none',
          lineStyle: {
            color: '#FFAE00',
            width: 1.2,
            type: 'dashed',
          },
          label: {
            fontSize: 8,
            color: '#FFAE00',
            formatter: (params) => {
              // 改用回调函数
              const avg = params.data.coord[1]; // 获取平均值坐标
              return 'TGI:' + avg.toFixed(0); // 格式化显示
            },
            position: 'end',
          },
          data: [{ type: 'average' }],
        },
        data: yAxis2,
      },
    ],
  };

  // 应用配置
  myChart.setOption(option);

  // 超小尺寸适配
  const handleResize = () => {
    const currentWidth = dom.clientWidth;
    if (currentWidth < 400) {
      myChart.setOption({
        xAxis: { axisLabel: { rotate: 90, fontSize: 7 } },
        grid: { bottom: 35 },
      });
    }
    myChart.resize();
  };

  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
};

const tabChange = (val) => {
  scope.value = val;
  getGeoDistributionsList();
};

const drawChinaMap = () => {
  const dom = document.getElementById('chinaMap');
  // 图表初始化（强制使用2D渲染）
  const myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false,
    devicePixelRatio: window.devicePixelRatio * 1.5, // 提高渲染精度
  });

  const option = {
    series: [
      {
        name: '中国',
        type: 'map',
        map: 'china',
        label: {
          show: false,
        },
        data: [
          { name: '北京', value: 1000 },
          { name: '上海', value: 800 },
          { name: '广东', value: 900 },
          // 其他省份数据...
        ],
      },
    ],
  };
  myChart.setOption(option);
};

onMounted(() => {
  getAgeDistributionsList();
  getGeoDistributionsList();
  getGenderDistributionsList();
  drawChinaMap();
});
</script>

<style scoped>
/* 自定义样式 */
:deep(.arco-table-th) {
  background-color: var(--color-fill-2);
}

:deep(.arco-table-tr):hover {
  background-color: var(--color-fill-1);
}
:deep(.arco-statistic-content .arco-statistic-value-integer) {
  font-size: 14px;
}

.pop-btn {
  background: #fff !important;
  border-color: #fff !important;
  color: #737478 !important;
  margin-left: -5px;
}

:deep(.arco-btn-outline) {
  color: #6d4cfe !important;
  border-color: #6d4cfe !important;
}
</style>
