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.ProductionComprehens.ErrorDetailCriteria;
type ErrorDetailSetting = KANBAN.ProductionComprehens.ErrorDetailSetting;
import { useIntl, getIntl } from 'umi';

const formatOptions = (data: any) => {
  const intl = getIntl();
  const option = {
    tooltip: {},
    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: 20,
      top: 20,
    },
    xAxis: {
      type: 'category',
      show: true,
      axisLabel: {
        color: '#fff',
        fontSize: 16,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      }
    },
    yAxis: {
      type: 'value',
      data: [],
      splitLine: {
        show: false
      },
      axisLabel: {
        color: '#fff',
        fontSize: 16,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    series: [],
  };

  const temp = {
    type: 'line',
    name: '',
    barGap: 0,
    smooth: true,
    label: {
      show: true,
      position: 'right',
      color: '#fff',
    },
    data: [],
  };
  const now = moment();
  
  // 存储最近七天日期的数组
  const lastSevenDays = [];
  
  for (let i = 0; i < 7; i++) {
    lastSevenDays.push(moment(now).subtract(i, 'days').format('MM/DD'));
  }
  console.log('lastSevenDays', lastSevenDays)
  option['xAxis']['data'] = lastSevenDays.reverse()
  // option.series.push({ ...temp, name: '当月异常', data: [data.totalCt] });
  // option.series.push({ ...temp, name: '未关闭', data: [data.unCloseCt] });
  option.series.push({ ...temp, name: intl.formatMessage({id:'设备故障总数'}), data: data.reverse()} );
  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;
