import React, { useState, useEffect, useRef } from 'react';
import { Button, Empty, Spin } from 'antd';
import echarts from 'echarts';
import style from './index.less';
import { ChartBoxTitle } from '../ChartBox';
import {
  defaultOptions,
  getOptions,
  getOptions2,
  getOptions3,
  getOptions4,
  getOptions5,
  getOptions6,
  getOptions7,
} from './chartConfig';
import { useRequest } from '@umijs/max';
import { queryConfigList } from '@/Project/services/DataMeter';

const { getOptions2: queryOptions } = require('./utils');

function DataCenter(props: DataMeter.IModelsProps) {
  const [chart, setChart] = useState<echarts.ECharts>();
  const [timer, setTimer] = useState<NodeJS.Timer>();
  const [showTabs, setShowTabs] = useState(false);
  const [title, setTitle] = useState('');
  // const [pfdOptions, setPfdOptions] = useState<any>(false);
  const [chartOptions, setChartOptions] = useState<any>(false);
  const chartEle = useRef<HTMLDivElement | null>(null);
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
  const signalRef = useRef<any>();
  // const [loading, setLoading] = useState(false);
  const { child, setActive, projectId, layout } = props;
  const { h, w } = layout;
  const [active, setSelfActive] = useState(
    layout.active ||
      child.find((item: DataMeter.ILayoutChild) => item.show)?.key,
  );
  const configRequest = useRequest(queryConfigList, {
    manual: true,
    onSuccess(data, params) {
      // if (data.type != 'pfd') {
      const { options } = data;
      // setPfdOptions(false);
      if (options.series[0].type != 'pie') {
        // 添加默认设置
        options.xAxis = {
          ...defaultOptions.xAxis,
          ...options.xAxis,
        };
        options.yAxis = {
          ...defaultOptions.yAxis,
          ...options.yAxis,
        };
      } else {
        options.legend = {
          ...defaultOptions.legend,
          ...options.legend,
        };
      }
      chart?.clear();
      chart?.setOption(data.options);
      // } else {
      //   setPfdOptions(data);
      // }
    },
  });

  const queryOptionsRequest = useRequest(queryOptions, {
    manual: true,
    onSuccess(data, params) {
      console.log('=================renderChart=======', data);
      iframeRef.current?.contentWindow?.render(data);
    },
  });

  // 旧版图表
  const getOptionsForConfig = (item: DataMeter.ILayoutChild) => {
    console.log(item);
    clearTimeout(timer);
    configRequest.run({
      projectId,
      chartId: item.key,
    });

    const t = setTimeout(() => {
      getOptionsForConfig(item);
    }, 1000 * 60);
    setTimer(t);
  };
  // 新版图表
  const getOptionsForConfig2 = (item: DataMeter.ILayoutChild) => {
    setChartOptions(item);
    // setPfdOptions(false);
    const t = setTimeout(() => {
      getOptionsForConfig2({ ...item });
    }, 1000 * 60);
    setTimer(t);
  };

  const handleClickTabs = (key: number | string) => {
    const item = child.find((c) => c.key == key);
    if (!item) return;
    if (item.type != 'chartConfig') {
      // setPfdOptions(false);
      setChartOptions(false);
      let option;
      switch (Number(key) % 7) {
        case 0:
          option = getOptions2();
          break;
        case 1:
          option = getOptions();
          break;
        case 2:
          option = getOptions3();
          break;
        case 3:
          option = getOptions4();
          break;
        case 4:
          option = getOptions5();
          break;
        case 5:
          option = getOptions6();
          break;
        case 6:
          option = getOptions7();
          break;
        default:
          option = getOptions();
          break;
      }
      chart?.clear();
      chart?.setOption(option);
    } else {
      // setLoading(true);
      if (item.is_new) {
        getOptionsForConfig2(item);
      } else {
        setChartOptions(false);
        getOptionsForConfig(item);
      }
    }
  };

  const renderChart = async () => {
    const datas = chartOptions.configs;
    const values = chartOptions.options;
    const formula = JSON.parse(chartOptions.formula || '[]');
    // setLoading(true);
    try {
      queryOptionsRequest.run(values, datas, formula, projectId);
      // const options = await queryOptions(values, datas, formula, projectId);
      // iframeRef.current?.contentWindow?.render(options);
    } catch (error) {
      // console.log(error);
    }
    // setLoading(false);
  };

  useEffect(() => {
    if (!chartEle.current) return;
    const chart = echarts.init(chartEle.current);
    setChart(chart);
    const controller = new AbortController();
    signalRef.current = controller;
    // handleClickTabs(active)
    // let option = getOptions({});
    // chart.setOption(option);
    return () => {
      clearTimeout(timer);
      signalRef.current.abort();
    };
  }, []);

  useEffect(() => {
    if (chart) {
      chart.resize();
    }
  }, [h, w, showTabs]);

  useEffect(() => {
    if (!chart || child.length == 0) return;
    let { active } = layout;
    if (!active) active = child[0].key;
    handleClickTabs(active);
    let current = child.find(
      (item: DataMeter.ILayoutChild) => item.key == active,
    );
    if (current) {
      setTitle(current.title);
    }
  }, [layout.active, chart, child.length]);

  useEffect(() => {
    const chartWindow = iframeRef.current?.contentWindow;
    if (!chartWindow) return;
    if (chartWindow.render) {
      renderChart();
    } else {
      chartWindow.onload = () => {
        renderChart();
      };
    }
  }, [chartOptions]);

  return (
    <div className={style.modelBox}>
      <ChartBoxTitle
        title={title}
        showTabs={showTabs}
        setShowTabs={setShowTabs}
        width={layout.w}
      />
      {showTabs && (
        <Spin spinning={configRequest.loading || queryOptionsRequest.loading}>
          <ul className={style.tabsList}>
            {(child || [])
              .filter((item) => item.show)
              .map((item) => (
                <li
                  key={item.key}
                  className={`${active == item.key ? style.active : ''}`}
                  onClick={() => {
                    handleClickTabs(item.key);
                    setActive(item.key);
                    setSelfActive(item.key);
                  }}
                >
                  {item.title}
                </li>
              ))}
          </ul>
        </Spin>
      )}
      <div
        style={{ paddingTop: '0.1rem', overflow: 'hidden' }}
        className={style.modelContent}
      >
        {/* {pfdOptions && <Pfd data={pfdOptions} />} */}
        {chartOptions && chartOptions.template && (
          <iframe
            ref={iframeRef}
            style={{ width: '100%', height: '98%', border: 'none' }}
            srcDoc={chartOptions.template.Content}
          />
        )}
        <div
          ref={chartEle}
          style={{
            // display: pfdOptions || chartOptions,
            height: '100%',
          }}
        />
      </div>
    </div>
  );
}

export default DataCenter;

// const Pfd = (props:any) => {
//   const {
//     data: { configs, options },
//   } = props;
//   const { series } = options;
//   const getStyle = (item) => {
//     return {
//       top: `${item.topPercent * 100}%`,
//       left: `${item.leftPercent * 100}%`,
//       color: item.color,
//     };
//   };

//   return (
//     <div
//       key={key}
//       className={style.pfdBox}
//       style={{ backgroundImage: `url(${options.fileUrl})` }}
//     >
//       {series.map((item, index) => (
//         <>
//           <div
//             key={`name-${index}`}
//             style={getStyle(item.name)}
//             className={style.pfdFont}
//           >
//             {item.paramsName}
//           </div>
//           <div
//             key={`data-${index}`}
//             style={getStyle(item.data)}
//             className={style.pfdFont}
//           >
//             {configs[index].value}
//           </div>
//         </>
//       ))}
//       {/* <img src={options.fileUrl} /> */}
//     </div>
//   );
// };

