import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';
import React, { useEffect, useRef, useState } from 'react';
import { Modal } from 'antd';
import HfChangedInfo from '@/pages/kanban/weldingProcessKanban/components/Evaluate/hfChangedInfo';

export const EvaluateNum: React.FC<{ data: KANBAN.WeldingProcessKanban.RateAndNumberDto }> = ({
  data,
}) => {
  return (
    <div className="evaluate-num-container">
      <div className="qualified-container">
        <p className="title">当月合格台数</p>
        <h1>{data.passNumber}</h1>

        <div className="pass-rate">
          <div>合格率</div>
          <div className="rate">{data.passRate}%</div>
        </div>
      </div>
      <div className="noqualified-container">
        <p className="title">当月不合格台数</p>
        <h1 style={{ color: '#ffc000' }}>{data.noPassNumber}</h1>
      </div>
    </div>
  );
};

export const DefectDistribution: React.FC = ({ month, day, settingId }) => {
  const dayChartRef = useRef<HTMLDivElement>(null);
  const monthChartRef = useRef<HTMLDivElement>(null);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const openModal = async () => {
    setBatchInfoParams({ type: 1, kanbanSettingId: settingId });
    setIsModalOpen(true);
  };
  const openModal2 = async () => {
    setBatchInfoParams({ type: 2, kanbanSettingId: settingId });
    setIsModalOpen(true);
  };
  const [batchInfoParams, setBatchInfoParams] = useState({
    type: 1,
    kanbanSettingId: '',
  });

  useEffect(() => {
    // Initialize chart
    let chart: ECharts | undefined;
    let chart2: ECharts | undefined;
    if (dayChartRef.current !== null) {
      chart = echarts.init(dayChartRef.current);
    }
    if (monthChartRef.current !== null) {
      chart2 = echarts.init(monthChartRef.current);
    }

    // Add chart resize listener
    // ResizeObserver is leading to a bit janky UX
    function resizeChart() {
      chart?.resize();
      chart2?.resize();
    }
    window.addEventListener('resize', resizeChart);

    // Return cleanup function
    return () => {
      chart?.dispose();
      chart2?.dispose();
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    if (dayChartRef.current !== null) {
      const chart = getInstanceByDom(dayChartRef.current);
      const options = {
        color: ['#249ab5', '#7f7f7f', '#007ce5'],
        legend: {
          itemWidth: 15,
          itemHeight: 15,
          textStyle: {
            color: '#fff',
          },
          bottom: 0,
        },
        series: [
          {
            height: '94%',
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}%',
            },
            silent: false,
            data: day.map((item) => {
              return { value: item.number, name: item.repairCause };
            }),
          },
        ],
      };
      chart?.setOption(options);
    }
    if (monthChartRef.current !== null) {
      const chart = getInstanceByDom(monthChartRef.current);
      const options = {
        color: ['#249ab5', '#7f7f7f', '#007ce5'],
        legend: {
          itemWidth: 15,
          itemHeight: 15,
          textStyle: {
            color: '#fff',
          },
          bottom: 0,
        },
        series: [
          {
            height: '94%',
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}%',
            },
            silent: false,
            data: month.map((item) => {
              return { value: item.number, name: item.repairCause };
            }),
          },
        ],
      };
      chart?.setOption(options);
    }
  }, [month, day]);
  return (
    <div className="defect-distribution-container">
      <Modal
        title={''}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={() => setIsModalOpen(false)}
      >
        <HfChangedInfo params={batchInfoParams} />
      </Modal>
      <div className="day-defect" onClick={openModal}>
        <p className="title">当日缺陷分布</p>
        <div className="chart" ref={dayChartRef}></div>
      </div>
      <div className="month-defect" onClick={openModal2}>
        <p className="title">当月缺陷分布</p>
        <div className="chart" ref={monthChartRef}></div>
      </div>
    </div>
  );
};

export const EvaluateDistribution: React.FC<{
  data: KANBAN.WeldingProcessKanban.DayAndNumberListDto[];
}> = ({ data }) => {
  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();
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    const sortData = data.sort((a, b) => a.day - b.day);
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        color: ['#004af2', '#7030a0'],
        grid: {
          left: 50,
          right: 50,
          bottom: 30,
        },
        legend: {
          right: 50,
          textStyle: {
            color: '#fff',
          },
          data: ['完工', '合格'],
        },
        xAxis: {
          type: 'category',
          splitLine: false,
          boundaryGap: false,
          data: sortData.map((item) => item.day),
        },
        yAxis: {
          type: 'value',
          splitLine: false,
        },
        series: [
          {
            name: '完工',
            type: 'line',
            //stack: 'Total',
            symbol: 'emptyRect',
            smooth: true,
            symbolSize: 6,
            data: sortData.map((item) => item.finishNumber),
          },
          {
            name: '合格',
            type: 'line',
            //stack: 'Total',
            symbol: 'emptyRect',
            symbolSize: 6,
            smooth: true,
            data: sortData.map((item) => item.passNumber),
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <div className="evalute-distribution-container">
      <p className="title">当月合格数量趋势图</p>
      <div className="chart" ref={chartRef}></div>
    </div>
  );
};
