import * as echarts from 'echarts/lib/echarts';
import { ECharts, getInstanceByDom } from 'echarts';
import './index.less';
import { useEffect, useRef, useState } from 'react';
import { Modal } from 'antd';
import moment from 'moment';
import DeviceAbnormal from './deviceAbnormal';
import ProductAbnormal from './productAbnormal';
import QualityAbnormal from './qualityAbnormal';
type ErrorDetailCriteria = KANBAN.ProductionComprehens.ErrorDetailCriteria;
type ErrorDetailSetting = KANBAN.ProductionComprehens.ErrorDetailSetting;

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
      },
    ],
    legend: {
      show: isLenged,
      orient: 'vertical',
      bottom: 5,
      right: 5,
      selectedMode: false,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
    },
    grid: {
      bottom: 20,
      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: [],
  };

  option.series.push({ ...temp, name: '当月异常', data: [data.currentMonthNumber] });
  option.series.push({ ...temp, name: '未关闭', data: [data.createIssueNumber] });
  option.series.push({ ...temp, name: '超期', data: [data.beyondNumber] });
  return option;
};

const ProductBar: React.FC<{ data: any; setting: ErrorDetailSetting }> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [criteria, setCriteria] = useState<ErrorDetailCriteria>();
  const closeModal = () => setIsModalOpen(false);
  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();
      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) => {
        if (params.seriesName == '当月异常') {
          setCriteria({
            workshopName: setting.workshopName,
            status: '1,2,3,4',
            createdDateFrom: moment()
              .date(1)
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .format('YYYY-MM-DD HH:mm'),
            createdDateTo: moment().format('YYYY-MM-DD HH:mm'),
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '未关闭') {
          setCriteria({
            workshopName: setting.workshopName,
            createdDateFrom: null,
            createdDateTo: null,
            //createdDateFrom: moment().date(1).hour(0).minute(0).second(0).millisecond(0).format('YYYY-MM-DD HH:mm'),
            //createdDateTo: moment().format('YYYY-MM-DD HH:mm'),
            status: '1,2,3',
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '超期') {
          setCriteria({
            workshopName: setting.workshopName,
            createdDateFrom: moment()
              .date(1)
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .format('YYYY-MM-DD HH:mm'),
            createdDateTo: moment().format('YYYY-MM-DD HH:mm'),
            status: '1,2,3',
            gtErrorDays: setting.abnormalOverdueSetting.diffDayProduction,
            current: 1,
            pageSize: 10,
          });
        }
        setIsModalOpen(true);
      });
    }
  }, [setting]);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '生产');
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'生产异常明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <ProductAbnormal values={criteria} />
      </Modal>
    </>
  );
};
const QualitytBar: React.FC<{ data: any; setting: ErrorDetailSetting }> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [criteria, setCriteria] = useState<ErrorDetailCriteria>();
  const closeModal = () => setIsModalOpen(false);
  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(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '质量');
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        if (params.seriesName == '当月异常') {
          setCriteria({
            werks: setting.werks,
            fevor: setting.fevors,
            status: '1,2,3',
            createdDateFrom: moment()
              .date(1)
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .format('YYYY-MM-DD HH:mm'),
            createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '未关闭') {
          setCriteria({
            werks: setting.werks,
            fevor: setting.fevors,
            createdDateFrom: null,
            createdDateTo: null,
            //createdDateFrom: moment().date(1).hour(0).minute(0).second(0).millisecond(0).format('YYYY-MM-DD HH:mm'),
            //createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            status: '1,2',
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '超期') {
          setCriteria({
            werks: setting.werks,
            fevor: setting.fevors,
            createdDateFrom: null,
            createdDateTo: null,
            //createdDateFrom: moment().date(1).hour(0).minute(0).second(0).millisecond(0).format('YYYY-MM-DD HH:mm'),
            //createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            status: '1,2',
            gtErrorDays: setting.abnormalOverdueSetting.diffDayQuality,
            current: 1,
            pageSize: 10,
          });
        }
        setIsModalOpen(true);
      });
    }
  }, [setting]);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '质量');
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'质量异常明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <QualityAbnormal values={criteria} />
      </Modal>
    </>
  );
};
const DeviceBar: React.FC<{ data: any; setting: ErrorDetailSetting }> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [criteria, setCriteria] = useState<ErrorDetailCriteria>();
  const closeModal = () => setIsModalOpen(false);

  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(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '设备');
      chart?.setOption(option);
      chart?.off('click');
      chart?.on('click', (params) => {
        if (params.seriesName == '当月异常') {
          setCriteria({
            status: '2,3,5',
            workshopName: setting.workshopName,
            createdDateFrom: moment()
              .date(1)
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .format('YYYY-MM-DD HH:mm'),
            createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '未关闭') {
          setCriteria({
            workshopName: setting.workshopName,
            createdDateFrom: null,
            createdDateTo: null,
            //createdDateFrom: moment().date(1).hour(0).minute(0).second(0).millisecond(0).format('YYYY-MM-DD HH:mm'),
            //createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            status: '2,3',
            current: 1,
            pageSize: 10,
          });
        } else if (params.seriesName == '超期') {
          setCriteria({
            workshopName: setting.workshopName,
            createdDateFrom: null,
            createdDateTo: null,
            //createdDateFrom: moment().date(1).hour(0).minute(0).second(0).millisecond(0).format('YYYY-MM-DD HH:mm'),
            //createdDateTo: moment(params.to).format('YYYY-MM-DD HH:mm'),
            status: '2,3',
            gtErrorDays: setting.abnormalOverdueSetting.diffDayEquipment,
            current: 1,
            pageSize: 10,
          });
        }
        setIsModalOpen(true);
      });
    }
  }, [setting]);
  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = formatOptions(data, '设备', true);
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'设备异常明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <DeviceAbnormal values={criteria} />
      </Modal>
    </>
  );
};
const Main: React.FC<{ device: any; quality: any; prod: any; setting: ErrorDetailSetting }> = ({
  device,
  quality,
  prod,
  setting,
}) => {
  return (
    <div className="abnormal-container">
      <div className="title">
        <h2>异常分布</h2>
      </div>
      <div className="item-container">
        <div className="item">
          <p>生产</p>
          <div className="chart-container">
            <ProductBar data={prod} setting={setting} />
          </div>
        </div>
        <div className="item">
          <p>质量</p>
          <div className="chart-container">
            <QualitytBar data={quality} setting={setting} />
          </div>
        </div>
        <div className="item">
          <p>设备</p>
          <div className="chart-container">
            <DeviceBar data={device} setting={setting} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Main;
