import { ref, Ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";

/**
 * 雷达图扫描区域功能实现
 * 提供30度扇形扫描区域，带动画旋转和渐变效果
 */
export const useMain = () => {
  // 主色调定义
  const primaryColor = "#509e38";
  const splitLineColor = "rgba(80, 158, 56, 0.7)"; // 主色调的70%透明度
  // 扫描动画相关变量
  let animationTimer: number | null = null;
  let currentAngle = 0;

  // 动画配置参数
  const animationConfig = {
    rotationSpeed: -2,   // 每次旋转的角度
    interval: 16,       // 旋转间隔时间(毫秒)
    scanAngle: 45,      // 扫描扇形角度
    isRunning: false    // 动画运行状态标记
  };

  // 自定义数据提示框格式化函数
  const tooltipFormat = (params: Array<Record<string, any>>) => {
    // 标题部分 - 黑色
    let result = `<div style="color:#000; font-weight:bold; margin-bottom:10px;">${params[0].axisValue}</div>`;

    // 每项数据
    params.forEach((item: Record<string, any>, index: number) => {
      const { angle, dis, height } = item.data?._rawData || {};
      if (!item.data?._rawData) return;
      const marginBottom = index < params.length - 1 ? "margin-bottom:4px;" : "";
      result += `
        <div style="
          background: #fff;
          padding:5px 10px;
          border-radius:4px;
          box-shadow: 6px 0px 20px 0px rgba(34,87,188,0.1);
          ${marginBottom};
          display: flex;
          align-items: start;
          width: 200px;
        ">
          <div>
            ${item.marker}
            <span style="font-weight:bold;">${item.seriesName}</span>
          </div >
          <div style="margin-left: 10px">
            角度: ${angle.toFixed(2)}° <br />
            距离: ${(dis / 1000).toFixed(2)}km <br />
            高度: ${(height / 1000).toFixed(2)}km
          </div>
        </div>
      `;
    });
    return result;
  };

  // ECharts配置项
  const options = ref<Record<string, any>>({
    title: {
      text: "",
    },
    legend: {
      show: false,
    },
    polar: {},
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: primaryColor,
        },
        angleAxis: {
          type: "line",
        },
        radiusAxis: {
          type: "line",
        },
      },
      formatter: tooltipFormat,
    },
    angleAxis: {
      type: "value",
      min: 0,
      max: 360,
      interval: 20,
      sliptNumber: 360,
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
        fontSize: 12,
        color: "#333",
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: primaryColor,
          width: 3,
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: splitLineColor,
          width: 1,
          type: "solid",
        },
      },
    },
    radiusAxis: {
      type: "value",
      min: 0,
      max: 0,
      splitNumber: 3,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
        formatter: (value: number) => value.toFixed(2),
        fontSize: 12,
        color: "#333",
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: splitLineColor,
          width: 1,
          type: "solid",
        },
      },
    },
    series: [
      // 主要数据点系列
      {
        coordinateSystem: "polar",
        name: "",
        animation: false,
        zlevel: 20,
        symbolSize: 15,
        label: {
          normal: {
            show: true,
            formatter: "{b}",
            position: "inside",
            textStyle: {
              color: "#fff",
              fontSize: 15,
            },
          },
        },
        type: "scatter",
        data: [],
      },
      // 扫描区域系列 - 使用饼图实现30度扇形
      {
        type: "pie",
        radius: ["0%", "80%"],
        startAngle: 0,
        zlevel: 10,
        animation: false,
        legend: {
          show: false,
        },
        tooltip: {
          show: false,
        },
        label: {
          show: false,
        },
        labelLine: {
          show: false,
        },
        data: [
          // 30度扫描扇形
          {
            value: animationConfig.scanAngle,  // 30度扇形区域
            name: "扫描区",
            itemStyle: {
              color: {
                type: "linear",
                x: 0.5 - Math.cos(animationConfig.scanAngle / 2 * Math.PI / 180) * 0.5,  // animationConfig.scanAngle / 2度扇形的中线角度
                y: 0.5 - Math.sin(animationConfig.scanAngle / 2 * Math.PI / 180) * 0.5,
                x2: 0.5 + Math.cos(animationConfig.scanAngle / 2 * Math.PI / 180) * 0.5,
                y2: 0.5 + Math.sin(animationConfig.scanAngle / 2 * Math.PI / 180) * 0.5,
                colorStops: [
                  { offset: 0, color: "rgba(128, 251, 128, 1)" },  // 左侧完全不透明
                  { offset: 1, color: "rgba(80, 158, 56, 0)" }     // 右侧完全透明
                ],
                global: false
              }
            }
          },
          // 剩余330度透明区域
          {
            value: 360 - animationConfig.scanAngle,
            itemStyle: {
              color: 'transparent'  // 透明，只显示30度的扫描扇形
            }
          }
        ],
      },
    ],
  });

  /**
   * 创建系列数据
   * @param data 原始数据数组
   * @returns 处理后的ECharts数据格式
   */
  const createSeriesData = (data: Array<Record<string, any>>) => {
    const points = data.map((item) => {
      const itemStyle = {
        color: {
          type: "radial",
          x: 0.5,
          y: 0.5,
          r: 0.5,
          colorStops: [
            { offset: 0, color: "#80fb80" },
            { offset: 0.5, color: "rgba(80, 158, 56, 0.7)" },
            { offset: 1, color: "rgba(80, 158, 56, 0)" },
          ],
          global: false,
        },
      };
      const point = {
        value: [item.radius.toFixed(2), item.angle.toFixed(2)],
        _rawData: item,
        itemStyle: itemStyle,
      };
      return point;
    });
    return points;
  };



  /**
   * 启动扫描动画
   * 使30度扇形区域以指定速度旋转
   */
  const startScanAnimation = (echartsRef: Ref<echarts.ECharts | null>) => {
    // 清除已有的定时器
    if (animationTimer) {
      clearInterval(animationTimer);
    }

    animationConfig.isRunning = true;

    // 创建新的定时器
    animationTimer = window.setInterval(() => {
      if (!echartsRef.value) return;
      // 更新当前角度，确保在0-360范围内
      currentAngle = (currentAngle + animationConfig.rotationSpeed) % 360;
      if (echartsRef.value) {
        // 计算扇形中线角度，用于渐变方向
        const gradientAngle = currentAngle + (animationConfig.scanAngle / 2);

        // 局部更新扫描区域的起始角度和渐变方向
        echartsRef.value.setOption({
          series: [
            {}, // 第一个系列保持不变
            {
              startAngle: currentAngle,
              data: [
                {
                  value: animationConfig.scanAngle,
                  itemStyle: {
                    color: {
                      type: "linear",
                      x: 0.5 - Math.cos(gradientAngle * Math.PI / 180) * 0.5,
                      y: 0.5 - Math.sin(gradientAngle * Math.PI / 180) * 0.5,
                      x2: 0.5 + Math.cos(gradientAngle * Math.PI / 180) * 0.5,
                      y2: 0.5 + Math.sin(gradientAngle * Math.PI / 180) * 0.5,
                      colorStops: [
                        { offset: 0, color: "rgba(128, 251, 128, 1)" },
                        { offset: 1, color: "rgba(80, 158, 56, 0)" }
                      ],
                      global: false
                    }
                  }
                },
                { value: 360 - animationConfig.scanAngle, itemStyle: { color: 'transparent' } }
              ]
            }
          ]
        }, false); // 第二个参数设为 false，禁止合并动画
      }
    }, animationConfig.interval);
  };

  /**
   * 停止扫描动画
   */
  const stopScanAnimation = () => {
    if (animationTimer) {
      clearInterval(animationTimer);
      animationTimer = null;
      animationConfig.isRunning = false;
    }
  };

  /**
   * 设置动画速度
   * @param speed 新的旋转速度
   */
  // const setAnimationSpeed = (speed: number) => {
  //   animationConfig.rotationSpeed = speed;
  //   // 如果动画正在运行，重新启动以应用新速度
  //   if (animationConfig.isRunning) {
  //     startScanAnimation();
  //   }
  // };




  return {
    options,
    createSeriesData,
    tooltipFormat,
    startScanAnimation,
    stopScanAnimation,
    // setAnimationSpeed
  };
};
