import './index.less';
import type { PieConfig } from '@ant-design/charts';
import { Pie } from '@ant-design/plots';
import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';
import { useEffect, useRef, useState } from 'react';
import { Modal } from 'antd';
import OrderInfo from './orderInfo';
import MaterialOrderInfo from './MaterialOrderInfo';
import moment from 'moment';

type MaterialReqOrderInfoCriteria = KANBAN.ProductionComprehens.MaterialReqOrderInfoCriteria;
type EfficiencyKanbanSetting = KANBAN.MaterialSynthesis.EfficiencyKanbanSetting;

const PeiSongPie: React.FC<{ data: number; setting: EfficiencyKanbanSetting }> = ({
  data,
  setting,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [criteria, setCriteria] = useState<MaterialReqOrderInfoCriteria>();
  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);
      chart?.off('click');
      if (!setting.werks) {
        return;
      }
      chart?.on('click', () => {
        setIsModalOpen(true);
        setCriteria({
          werks: setting.werks,
          startDateFrom: moment()
            .date(1)
            .hour(0)
            .minute(0)
            .second(0)
            .millisecond(0)
            .format('YYYY-MM-DD HH:mm'),
          startDateTo: moment().format('YYYY-MM-DD HH:mm'),
          current: 1,
          status: 1,
          pageSize: 10,
        });
      });
    }
  }, [setting]);
  const closeModal = () => setIsModalOpen(false);
  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        grid: {
          width: '100%',
        },
        color: ['#004af2', '#213045'],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: data + '%',
              color: '#fff',
              fontSize: '16px',
              fontWeight: 600,
            },
            silent: false,
            data: [
              { value: data, name: '物料配送完成率' },
              { value: 100 - data, name: '物料配送未完成率' },
            ],
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'领料单明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <MaterialOrderInfo values={criteria} />
      </Modal>
    </>
  );
};

const ZhunshiPie: React.FC<{ data: number; setting: EfficiencyKanbanSetting }> = ({
  data,
  setting,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [criteria, setCriteria] = useState<MaterialReqOrderInfoCriteria>();

  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(() => {
    // Initialize chart
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      chart?.off('click');
      if (!setting.werks) {
        return;
      }
      chart?.on('click', () => {
        setIsModalOpen(true);
        setCriteria({
          werks: setting.werks,
          startDateFrom: moment()
            .date(1)
            .hour(0)
            .minute(0)
            .second(0)
            .millisecond(0)
            .format('YYYY-MM-DD HH:mm'),
          startDateTo: moment().format('YYYY-MM-DD HH:mm'),
          onTime: 2,
          current: 1,
          pageSize: 10,
        });
      });
    }
  }, [setting]);

  const closeModal = () => setIsModalOpen(false);
  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        grid: {
          width: '100%',
        },
        color: ['#004af2', '#213045'],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: data + '%',
              color: '#fff',
              fontSize: '16px',
              fontWeight: 600,
            },
            silent: false,
            data: [
              { value: data, name: '物料配送准时率' },
              { value: 100 - data, name: '不准时率' },
            ],
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'领料单明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <MaterialOrderInfo values={criteria} />
      </Modal>
    </>
  );
};

const ShangxianPie: React.FC<{ data: number; setting: EfficiencyKanbanSetting }> = ({
  data,
  setting,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [batchInfoParams, setBatchInfoParams] = useState({
    current: 1,
    pageSize: 10,
    type: 1,
    kanbanSettingId: '',
  });
  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);
      chart?.off('click');
      chart?.on('click', () => {
        if (!setting.kanbanId) return;
        setBatchInfoParams({
          ...batchInfoParams,
          type: 1,
          kanbanSettingId: setting.kanbanId as string,
        });
        setIsModalOpen(true);
      });
    }
  }, [setting]);

  const closeModal = () => setIsModalOpen(false);

  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        grid: {
          width: '100%',
        },
        color: ['#004af2', '#213045'],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: data + '%',
              color: '#fff',
              fontSize: '16px',
              fontWeight: 600,
            },
            silent: false,
            data: [
              { value: data, name: '订单上线准时率' },
              { value: 100 - data, name: '不准时率' },
            ],
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'工单明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <OrderInfo params={batchInfoParams} />
      </Modal>
    </>
  );
};

const XiaxianPie: React.FC<{ data: number; setting: EfficiencyKanbanSetting }> = ({
  data,
  setting,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [batchInfoParams, setBatchInfoParams] = useState({
    current: 1,
    pageSize: 10,
    type: 2,
    kanbanSettingId: '',
  });
  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);
      chart?.off('click');
      chart?.on('click', () => {
        if (!setting.kanbanId) return;
        setBatchInfoParams({
          ...batchInfoParams,
          type: 2,
          kanbanSettingId: setting.kanbanId as string,
        });
        setIsModalOpen(true);
      });
    }
  }, [setting]);
  const closeModal = () => setIsModalOpen(false);
  useEffect(() => {
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        grid: {
          width: '100%',
        },
        color: ['#004af2', '#213045'],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: data + '%',
              color: '#fff',
              fontSize: '16px',
              fontWeight: 600,
            },
            silent: false,
            data: [
              { value: data, name: '订单下线准时率' },
              { value: 100 - data, name: '不准时率' },
            ],
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return (
    <>
      <div ref={chartRef} style={{ height: '210px' }} />
      <Modal
        title={'订单明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <OrderInfo params={batchInfoParams} />
      </Modal>
    </>
  );
};

const Main: React.FC<{ punctual: any; delivery: any; setting: EfficiencyKanbanSetting }> = ({
  punctual,
  delivery,
  setting,
}) => {
  return (
    <div className="efficiency-container">
      <div className="row" style={{ marginBottom: '40px' }}>
        <div className="item" style={{ marginLeft: '0' }}>
          <h2>物料配送完成率</h2>
          <PeiSongPie data={delivery.finishedRate} setting={setting} />
        </div>
        <div className="item">
          <h2>物料准时配送率</h2>
          <ZhunshiPie data={delivery.punctualRate} setting={setting} />
        </div>
      </div>
      <div className="row">
        <div className="item" style={{ marginLeft: '0' }}>
          <h2>订单上线准时率</h2>
          <ShangxianPie data={punctual.orderOnlinePunctualRate} setting={setting} />
        </div>
        <div className="item">
          <h2>订单下线准时率</h2>
          <XiaxianPie data={punctual.orderOfflinePunctualRate} setting={setting} />
        </div>
      </div>
    </div>
  );
};

export default Main;
