import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';

type ProcessOutProps = {
  data: KANBAN.ProductionComprehens.ProcessYieldData[];
  setting: any;
};

const formatOptions = (data: any) => {
  const option = {
    color: [
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#011126', // 100% 处的颜色
          },
          {
            offset: 0,
            color: '#00ced3', // 0% 处的颜色
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#011126',
          },
          {
            offset: 0,
            color: '#3ba7cc',
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#011126',
          },
          {
            offset: 0,
            color: '#7bb249',
          },
        ],
        global: false, // 缺省为 false
      },
    ],
    tooltip: {},
    xAxis: {
      type: 'value',
      show: false,
    },
    dataZoom: [
      {
        type: 'slider',
        orient: 'vertical',
        show: false,
        startValue: 0,
        endValue: 3,
      },
    ],
    grid: {
      left: 82,
      bottom: 30,
      right: 40,
    },
    legend: {
      show: false
    },
    yAxis: {
      type: 'category',
      triggerEvent: true,
      data: [],
      axisLabel: {
        color: '#fff',
        fontSize: 14,
        formatter: function (value: string) {
          return (value.length > 4 ? (value.slice(0,4)+"...") : value )
        }
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    series: [],
  };
  if (data && data.length) {
    const xAxisData = data.map((item: any) => item.cause);
    const series = [{
      type: 'bar',
      barGap: 0,
      label: {
        show: true,
        position: 'right',
        color: '#fff',
      },
      data: data.map((item: any) => item.ct),
    }];
    option.yAxis.data = xAxisData;
    option.series = series;
  }
  console.log('option', option)
  return option;
};

const Main: React.FC<ProcessOutProps> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const closeModal = () => setIsModalOpen(false);
  const [processParams, setProcessParams] = useState({
    dataRange: 1,
    processName: '',
    current: 1,
    pageSize: 10,
    kanbanSettingId: '',
  });
  useEffect(() => {
    // Initialize chart
    let chart: ECharts | undefined;
    if (chartRef.current !== null) {
      chart = echarts.init(chartRef.current);
    }

    // Add chart resize listener
    // ResizeObserver is leading to a bit janky UX
    function resizeChart() {
      chart?.resize();
    }
    window.addEventListener('resize', resizeChart);

    // Return cleanup function
    return () => {
      chart?.off('click');
      chart?.dispose();
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    let timer: NodeJS.Timer | null = null;
    // Update chart
    if (chartRef.current !== null) {
      if (timer !== null) clearInterval(timer);
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data);
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (p) => {
        if (p.seriesName === '完成量') {
          console.log(setting.productionComprehensKanbanSettingId, '----');
          setProcessParams({
            dataRange: setting.dataRange,
            processName: p.name,
            current: 1,
            pageSize: 10,
            kanbanSettingId: setting.productionComprehensKanbanSettingId,
          });
          setIsModalOpen(true);
        }
      });
      // 如果数据工序大于5那么需要自动轮训播放
      if (option.yAxis.data.length > 4 && setting.rowMovingTime > 0) {
        timer = setInterval(() => {
          option.dataZoom[0].startValue++;
          if (option.dataZoom[0].endValue++ >= option.yAxis.data.length - 1) {
            option.dataZoom[0].startValue = 0;
            option.dataZoom[0].endValue = 3;
          }
          chart?.setOption(option);
        }, setting.rowMovingTime * 1000);
      }
    }
    return () => {
      if (timer !== null) clearInterval(timer);
    };
  }, [data, setting]);
  return (
    <>
      <div ref={chartRef} style={{ height: '260px' }} />
    </>
  );
};

export default Main;