import type { LineConfig } from '@ant-design/charts';
import { Line } from '@ant-design/plots';
import './index.less';
import * as echarts from 'echarts/lib/echarts';
import { useEffect, useRef, useState } from 'react';
import { ECharts, getInstanceByDom } from 'echarts';
import MissingMaterialInfo from './missingMaterialInfo';
import { Modal } from 'antd';

type MissProps = {
  month: KANBAN.MaterialSynthesis.CountCurrentMonthLackMaterialKanbanDto[];
  lack: KANBAN.MaterialSynthesis.CountCurrentLackMaterialKanbanDto[];
};

type CommonProps = {
  data: MissProps['lack'];
  onClickBar: (workLine: string, flag: number) => void;
};

const lendTemp = {
  缺料种类: 1,
  超期一周: 2,
  当月缺料: 3,
};

const formatOptions = (data: any, label = '高压', isLenged = false) => {
  const option = {
    color: [
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#00214d', // 100% 处的颜色
          },
          {
            offset: 0,
            color: '#4ad4fe', // 0% 处的颜色
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#00214d',
          },
          {
            offset: 0,
            color: '#ffc000',
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#00214d',
          },
          {
            offset: 0,
            color: '#ff0000',
          },
        ],
        global: false, // 缺省为 false
      },
      {
        type: 'linear',
        x: 1,
        y: 0,
        x2: 0,
        y2: 0,
        colorStops: [
          {
            offset: 1,
            color: '#213045',
          },
          {
            offset: 0,
            color: '#ff0000',
          },
        ],
        global: false, // 缺省为 false
      },
    ],
    legend: {
      show: isLenged,
      orient: 'vertical',
      bottom: 0,
      right: 5,
      selectedMode: false,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
    },
    grid: {
      bottom: 30,
      top: -30,
      left: 10,
    },
    xAxis: {
      type: 'value',
      show: false,
    },
    yAxis: {
      type: 'category',
      data: [label],
      show: false,
      axisLabel: {
        color: '#fff',
        fontSize: 16,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    series: [],
  };

  const temp = {
    type: 'bar',
    name: '',
    barGap: 0,
    label: {
      show: true,
      position: 'right',
      color: '#fff',
    },
    barWidth: 30,
    data: [],
  };

  const i = data.findIndex((item) => item.workLine === label);
  if (i > -1) {
    option.series.push({ ...temp, name: '缺料种类', data: [data[i].normalNumber] });
    option.series.push({ ...temp, name: '超期一周', data: [data[i].beyondDayNumber] });
    option.series.push({ ...temp, name: '当月缺料', data: [data[i].currentMonthNumber] });
  }
  return option;
};

const HeightBar: React.FC<CommonProps> = ({ data, onClickBar }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  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?.dispose();
      chart?.off('click');
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '高压');
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        onClickBar('高压', lendTemp[params.seriesName as string]);
      });
    }
  }, [data]);
  return <div ref={chartRef} style={{ height: '170px' }}></div>;
};
const DowntBar: React.FC<CommonProps> = ({ data, onClickBar }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  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?.dispose();
      chart?.off('click');
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '中压');
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        onClickBar('中压', lendTemp[params.seriesName as string]);
      });
    }
  }, [data]);
  return <div ref={chartRef} style={{ height: '170px' }}></div>;
};
const CarBar: React.FC<CommonProps> = ({ data, onClickBar }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  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?.dispose();
      chart?.off('click');
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '低温车箱');
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        onClickBar('低温车箱', lendTemp[params.seriesName as string]);
      });
    }
  }, [data]);
  return <div ref={chartRef} style={{ height: '170px' }}></div>;
};
const TankBar: React.FC<CommonProps> = ({ data, onClickBar }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  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?.dispose();
      chart?.off('click');
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '低温罐', true);
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        onClickBar('低温罐', lendTemp[params.seriesName as string]);
      });
    }
  }, [data]);
  return <div ref={chartRef} style={{ height: '170px' }}></div>;
};

const MonthLine: React.FC<{ month: MissProps['month'] }> = ({ month }) => {
  const [data, setData] = useState([]);
  const countMax = () => {
    return Math.max(...data.map((item) => item.number)) * 1.2;
  };
  useEffect(() => {
    setData(
      month
        .sort((a, b) => a.day - b.day)
        .map((item) => {
          item.day += '';
          return item;
        }),
    );
  }, [month]);
  const config: LineConfig & React.RefAttributes<unknown> = {
    data,
    width: 946,
    height: 110,
    xField: 'day',
    yField: 'number',
    smooth: true,
    lineStyle: {
      stroke: '#1b46df',
      lineWidth: 4,
    },
    point: {
      size: 3,
      shape: 'square',
      style: {
        fill: 'white',
      },
    },
    xAxis: {
      line: null,
      tickLine: null,
      label: {
        style: {
          fill: '#fff',
        },
      },
    },
    label: {
      style: {
        fill: '#fff',
      },
    },
    yAxis: {
      tickLine: null,
      line: null,
      grid: null,
      label: {
        style: {
          fill: '#fff',
        },
      },
      max: countMax(),
    },
    tooltip: false,
  };
  return <Line {...config} />;
};

const Main: React.FC<MissProps> = ({ month, lack }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [missingInfoParams, setMissingInfoParams] = useState({
    workLine: '',
    flag: 1,
  });

  const closeModal = () => setIsModalOpen(false);
  const clickBar = (workLine: string, flag: number) => {
    setMissingInfoParams({
      workLine,
      flag,
    });
    setIsModalOpen(true);
  };
  return (
    <div className="missingMaterial-container">
      <div className="title">
        <h2>当前缺料分布</h2>
      </div>
      <div className="bar-container">
        <div className="item">
          <p>高压</p>
          <HeightBar data={lack} onClickBar={clickBar} />
        </div>
        <div className="item">
          <p>中压</p>
          <DowntBar data={lack} onClickBar={clickBar} />
        </div>
        <div className="item">
          <p>低温车箱</p>
          <CarBar data={lack} onClickBar={clickBar} />
        </div>
        <div className="item">
          <p>低温罐</p>
          <TankBar data={lack} onClickBar={clickBar} />
        </div>

        <Modal
          title={
            missingInfoParams.workLine +
            (missingInfoParams.flag === 1
              ? '缺料种类'
              : missingInfoParams.flag === 2
              ? '超期一周'
              : '当月缺料')
          }
          visible={isModalOpen}
          footer={null}
          width={'70%'}
          onCancel={closeModal}
        >
          <MissingMaterialInfo params={missingInfoParams} />
        </Modal>
      </div>
      <div className="line-container">
        <p>当月缺料趋势图</p>
        <MonthLine month={month} />
      </div>
    </div>
  );
};

export default Main;
