import { useMain as useStatisticsMain } from "@/views/dataManage/index/hooks/statistics.ts";
import { useMain as useCircleChatMain } from "@/views/dataManage/index/hooks/circleChat.ts";
import { useMain as useLineChatMain } from "@/views/dataManage/index/hooks/lineChat.ts";
import { useMain as useDataExportMain } from "@/views/dataManage/index/hooks/dataExport.ts";
import { useMain as useRadarChatMain } from "@/views/dataManage/index/hooks/radarChat.ts";
import { useSpectrumDiagramChatHooks } from '@/views/dataManage/index/hooks/spectrumDiagramChat.ts'

import { ref } from "vue";

export const useMain = () => {
  const { options: spectrumDiagramChatOptions } = useSpectrumDiagramChatHooks()
  const { options: circleChatOptions } = useCircleChatMain();
  const {
    listRequest: exportDataListRequest,
    updateRequest,
    exportUrlRequest,
  } = useDataExportMain();

  const {
    options: lineChatOptions,
    createSeriesOptions: createLineSeriesOptions,
    tooltipFormat,
  } = useLineChatMain();

  const {
    options: radarChatOptions,
    createSeriesData: createRadarSeriesData,
    tooltipFormat: radarTooltipFormat,
    startScanAnimation: radarStartScanAnimation,
    stopScanAnimation: radarStopScanAnimation,
  } = useRadarChatMain();

  const { statisticsRequest, lineStatisticsRequest, } = useStatisticsMain();
  const { lineStatisticsRequest: radarStatisticsRequest } = useStatisticsMain();
  const { lineStatisticsRequest: SpectrumDiagramStatisticsRequest, getSpectrumImgRequest  } = useStatisticsMain();

  const statisticsData = ref({});

  // 获取统计数据数据
  const getStatisticsData = async () => {
    const res = await statisticsRequest.request();
    console.log("getStatisticsData", res);
    if (res?.code == 200) {
      statisticsData.value = res.data;
    }
    return res;
  };

  // 更新环型图表配置
  const updateCircleChatOptions = (chatData: Record<string, any>) => {
    const { batch_count, hrrp_by_model, model_count } = chatData;
    circleChatOptions.value.title.text = `{a|批次}\n{b|${batch_count}}`;
    const showData: Record<string, any>[] = [];
    for (const plane in hrrp_by_model) {
      showData.push({
        name: `${plane}`,
        value: hrrp_by_model[plane],
      });
    }
    circleChatOptions.value = {
      ...circleChatOptions.value,
      title: {
        ...circleChatOptions.value.title,
        text: `{a|批次}\n{b|${batch_count}}`,
      },
      series: [
        {
          ...circleChatOptions.value.series[0],
          data: showData,
        },
      ],
    };
  };

  // 根据batchId获取折线图、雷达图统计数据
  const lineStatisticsData = ref({});
  const getLineStaticsData = async (batchId: string) => {
    const res = await lineStatisticsRequest.request(batchId);
    if (res.code == 200) {
      lineStatisticsData.value = res.data;
    }
  };

  // 折线图
  const updateLineChatOptions = (chatData: Record<string, any>) => {
    if (!chatData || !chatData.hrrp) return;
    const { hrrp } = chatData;
    console.log("hrrp", hrrp);
    // 获取hrrp数组的子数组里最长的长度
    const maxLen = Math.max(...hrrp.map((item: number[] | string[]) => item.length));
    // 获取最值
    const maxValue = Math.max(...hrrp.flat(Infinity));
    const xPoint = 10;
    const xSide = Math.ceil(maxLen / xPoint);
    const xAxis = [];
    for (let i = 0; i < maxLen + 1; i++) {
      xAxis.push(i);
    }
    lineChatOptions.value.xAxis[0].data = xAxis;
    const series = hrrp.map((item: number[]) => {
      const seriesItem = createLineSeriesOptions({
        title: "",
        data: [...item],
      });
      return seriesItem;
    });
    lineChatOptions.value.yAxis[0].name = "幅度";
    lineChatOptions.value.series = series;
    lineChatOptions.value = {
      ...lineChatOptions.value,
    };
    console.log("lineChatOptions", lineChatOptions.value);
  };

  const onUpdateLineChat = async (batchId: string) => {
    if (!batchId) return;
    await getLineStaticsData(batchId);
    updateLineChatOptions(lineStatisticsData.value);
  };

  // 频谱图
  const spectrumDiagramChatData = ref({});
  const spectrumDiagramChatImgs = ref<string[]>([])
  const spectrumImgsLoading = ref(false)

  const getSpectrumDiagramChatData = async (batchId: string) => {
    if (!batchId) return;
    const res = await SpectrumDiagramStatisticsRequest.request(batchId);
    if (res?.code == 200) {
      spectrumDiagramChatData.value = res.data;
    }
  }

  // 更新图谱数据
  const updateChatImgs = async (batchId: string, rawData: Record<string, any>) => {
    const useJem = (rawData?.jem || []).slice(0, 5);
    spectrumDiagramChatImgs.value = []
    await Promise.all([
      await useJem.map(async (item: Record<string, any>, index: number) => {

        const params = {
          batchId: batchId,
          index: index,
        }
        const jemRes = await getSpectrumImgRequest.request(params)
        console.log('jemRes', jemRes)
        const imgBlob = await jemRes.blob()
        // 回显为base64图片
        return new Promise(resolve => {
          const reader = new FileReader();
          reader.readAsDataURL(imgBlob);
          reader.onload = function () {
            spectrumDiagramChatImgs.value.push(reader.result);
            resolve(void 0)
          };
        })

      })


    ])

    // spectrumDiagramChatImgs.value = imgs
  }


  // 频谱图
  const onUpdateSpectrumDiagramChatOptions = (chatData: Record<string, any>) => {
    const { jem } = chatData
    console.log('jem', jem)
    // const imax = jem.length
    // const jmax = 80
    const data = jem.data
    const xData = jem.xData
    const yData = jem.yData
    // for (let i = 0; i < jem.length; i++) {
    //   for (let j = 0; j < jem[i].length; j++) {
    //     data.push([jem[i][j]]);
    //   }
    // }
    console.log('data', data)
    spectrumDiagramChatOptions.value.series[0].data = data;
    spectrumDiagramChatOptions.value.yAxis.data = yData;
    spectrumDiagramChatOptions.value.xAxis.data = xData;
    spectrumDiagramChatOptions.value = {
      ...spectrumDiagramChatOptions.value,
    };
  }

  const onUpdateSpectrumDiagramChat = async (batchId: string) => {
    if (!batchId) return;
    spectrumImgsLoading.value = true
    await getSpectrumDiagramChatData(batchId);
    await updateChatImgs(batchId, spectrumDiagramChatData.value)
    spectrumImgsLoading.value = false

    // onUpdateSpectrumDiagramChatOptions(spectrumDiagramChatData.value);
  }

  // 根据batchId获取雷达图统计数据
  const radarStatisticsData = ref({});
  const getRadatStaticsData = async (batchId: string) => {
    if (!batchId) return;
    const res = await radarStatisticsRequest.request(batchId);
    if (res.code == 200) {
      radarStatisticsData.value = res.data;
    }
  };

  // 雷达图
  const updateRadarChatOptions = (chatData: Record<string, any>) => {
    if (!chatData || !chatData.dis) return;
    const { dis, height, azimuth } = chatData;
    console.log("chatData", chatData);
    const pointKey = "dis";
    const pointData = chatData[pointKey] || [];
    const maxPoint = Math.max(...pointData);
    radarChatOptions.value.radiusAxis.max = Math.ceil(maxPoint / 10) * 10;
    const showData = [];
    for (let i = 0; i < azimuth.length; i++) {
      showData.push({
        radius: pointData[i],
        angle: azimuth[i] * (180 / Math.PI),
        azimuth: azimuth[i],
        dis: dis[i],
        height: height[i],
        // value: [pointData[i], azimuth[i] * (180/Math.PI)],
        // name: "",
      });
    }
    const seriesData = createRadarSeriesData(showData);
    console.log("seriesData", seriesData);
    radarChatOptions.value.series[0].data = seriesData;
    radarChatOptions.value = {
      ...radarChatOptions.value,
    };
  };

  const onUpdateRadarChat = async (batchId: string) => {
    await getRadatStaticsData(batchId);
    updateRadarChatOptions(radarStatisticsData.value);
  };

  // 更新图表
  const onUpdateChat = async () => {
    await getStatisticsData();
    updateCircleChatOptions(statisticsData.value);
  };

  const exportData = ref<Record<string, any>>([]);
  const exportListParams = ref({});

  // 获取导出数据
  const getExportData = async () => {
    const res = await exportDataListRequest.request();
    if (res?.code == 200) {
      exportData.value = res.data;
    }
    return res;
  };

  const state = {
    statisticsData: statisticsData,
    circleChatOptions,
    lineStatisticsData: lineStatisticsData,
    lineChatOptions,
    radarStatisticsData: radarStatisticsData,
    radarChatOptions,
    spectrumDiagramChatOptions: spectrumDiagramChatOptions,
    spectrumDiagramChatImgs,
    spectrumImgsLoading,
    exportData: exportData,
  };

  const api = {
    getStatisticsData,
    updateCircleChatOptions,
    onUpdateSpectrumDiagramChatOptions,
    getSpectrumDiagramChatData,
    onUpdateChat,
    onUpdateLineChat,
    onUpdateRadarChat,
    onUpdateSpectrumDiagramChat,
    radarStartScanAnimation,
    radarStopScanAnimation,
    getExportData,
  };

  return {
    state,
    api,
    requestMap: {
      statisticsRequest,
      lineStatisticsRequest,
      radarStatisticsRequest,
      exportDataListRequest,
    },
  };
};
