import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts/lib/echarts';
import { ECharts, getInstanceByDom } from 'echarts';
import { Modal } from 'antd';
import ProductAbnormal from '../../../materialSynthesis/components/abnormal/productAbnormal';
import { getIntl } from 'umi';

type ErrorDetailCriteria = KANBAN.ProductionComprehens.ErrorDetailCriteria;
type ErrorDetailSetting = KANBAN.ProductionComprehens.ErrorDetailSetting;

const formatOptions = (data: any) => {
  const intl = getIntl();
  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: {
      selectedMode: false,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
    },
    grid: {
      bottom: 10,
      containLabel: true,
      left: 10,
      top: 20,
    },
    xAxis: {
      type: 'value',
      show: false,
    },
    yAxis: {
      type: 'category',
      data: [intl.formatMessage({id:'生产'})],
      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: intl.formatMessage({id:'当月异常'}), data: [data.totalCt] });
  option.series.push({ ...temp, name: intl.formatMessage({id:'未关闭'}), data: [data.unCloseCt] });
  option.series.push({ ...temp, name: intl.formatMessage({id:'超期'}), data: [data.expireUnClose] });
  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({
      //       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: 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',
      //       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>
    </>
  );
};

export default Main;
