import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';
import { Modal } from 'antd';
import QualityAbnormal from '../../../materialSynthesis/components/abnormal/qualityAbnormal';
import moment from 'moment';

type ErrorDetailCriteria = KANBAN.QiPingComprehens.ErrorDetailCriteria;
type ErrorDetailSetting = KANBAN.QiPingComprehens.ErrorDetailSetting;

const formatOptions = (data: any) => {
  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: false,
    },
    grid: {
      bottom: 10,
      top: 20,
    },
    xAxis: {
      type: 'value',
      show: false,
    },
    yAxis: {
      type: 'category',
      data: ['质量'],
      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',
    },
    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 Main: React.FC<{ data: any; setting: ErrorDetailSetting }> = ({ data, setting }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const closeModal = () => setIsModalOpen(false);
  const [criteria, setCriteria] = useState<ErrorDetailCriteria>();
  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);
      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 (
    <>
      <Modal
        title={'质量异常明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <QualityAbnormal values={criteria} />
      </Modal>
      <div ref={chartRef} style={{ height: '210px' }} />
    </>
  );
};

export default Main;
