import { Modal } from 'antd';
import { ECharts, getInstanceByDom } from 'echarts';
import * as echarts from 'echarts/lib/echarts';
import React, { useEffect, useRef, useState } from 'react';
import ModalChart from './modalChart';
import QualityErrorTable from './qualityErrorTable';
import { queryPunctualityPenetratingByKanban } from '../../services/api';

type ProcessFailProps = {
  data: KANBAN.QiPingComprehens.ProcessDefectRatioData[];
  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: '#2f8eb9', // 0% 处的颜色
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#011126',
          },
          {
            offset: 0,
            color: '#ffc000',
          },
        ],
        global: false, // 缺省为 false
      },
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      valueFormatter: (v) => v + '%',
    },
    xAxis: {
      type: 'value',
      show: false,
    },
    dataZoom: [
      {
        type: 'slider',
        orient: 'vertical',
        show: false,
        startValue: 0,
        endValue: 3,
      },
    ],
    grid: {
      left: 70,
      bottom: 30,
      right: 40,
    },
    legend: {
      orient: 'vertical',
      selectedMode: false,
      right: 0,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
    },
    yAxis: {
      type: 'category',
      triggerEvent: true,
      data: [],
      axisLabel: {
        color: '#fff',
        fontSize: 14,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    series: [],
  };
  if (data && data.length) {
    const lenged = [
      { label: '基准率', field: 'standRatio' },
      { label: '未通过率', field: 'defectRatio' },
    ];
    const xAxisData = data.map((item: any) => item.stepName);
    const series = lenged.map((item) => {
      return {
        type: 'bar',
        name: item.label,
        barGap: 0,
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          formatter: '{c}%',
        },
        data: data.map((v) => v[item.field]),
      };
    });
    option.yAxis.data = xAxisData;
    option.series = series;
  }
  return option;
};

const Main: React.FC<ProcessFailProps> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [modalData, setModalData] = useState<KANBAN.QiPingComprehens.PassRateTrendChart[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalTableOpen, setIsModalTableOpen] = useState(false);
  const [proName, setProName] = useState('');
  const closeModal = () => setIsModalOpen(false);
  const closeModalTable = () => setIsModalTableOpen(false);
  const [processParams, setProcessParams] = useState({
    processName: '',
    boardType: 2,
    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.targetType === 'axisLabel') {
          // 显示弹窗
          queryPunctualityPenetratingByKanban({
            kanbanSettingId: setting.productionComprehensKanbanSettingId,
            processName: p.value as string,
            boardType: 2,
          }).then(({ data: cData }) => {
            setProName(p.value as string);
            setModalData(cData);
            setIsModalOpen(true);
            setIsModalTableOpen(false);
          });
        }
        if (p.seriesName === '未通过率') {
          setProcessParams({
            processName: p.name,
            boardType: 2,
            kanbanSettingId: setting.productionComprehensKanbanSettingId,
          });
          setIsModalTableOpen(true);
          setIsModalOpen(false);
        }
      });
      // 如果数据工序大于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 (
    <>
      <Modal
        title={proName + '工序当月一次未通过率'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <ModalChart data={modalData} />
      </Modal>
      <Modal
        title={'质量异常'}
        visible={isModalTableOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModalTable}
      >
        <QualityErrorTable params={processParams} />
      </Modal>
      <div ref={chartRef} style={{ height: '370px' }} />
    </>
  );
};

export default Main;
