import { useEffect, useState } from 'react';
import KanbanStyle from '../components/FHD1080P/Style2';
import SettingForm from './components/SettingForm';
import type { Setting } from './components/SettingForm';
import './index.less';
import TrendChart from './components/TrendChart';
import {
  queryDurationByDMonthDay,
  queryDurationByDYearMonth,
  queryQuantityByMonth,
  queryQuantityByYearMonth,
  queryStatisIndex,
  queryWorkUnitIndex,
} from './services/api';
import { Modal } from 'antd';
import PartModalTable from './components/ModalTable';

const EvacuationProcessKanban: React.FC = () => {
  const [setting, setSetting] = useState<Setting>({
    autoResize: true,
    intervalTime: 600,
    rowMovingTime: 5,
    cKProgressKanbanSetting: undefined,
    kanbanId: '',
  });
  const [workUnit, setWorkUnit] = useState<KANBAN.EvacuationProcessKanban.WorkUnit[]>([]);
  const [statisData, setStatisData] = useState<KANBAN.EvacuationProcessKanban.StatisIndexDto>({
    productionNum: 0,
    prepareProductionNum: 0,
    overdueNum: 0,
  });
  const [quantityByMonthDay, setQuantityByMonthDay] = useState<
    KANBAN.EvacuationProcessKanban.chartDto[]
  >([]);
  const [quantityByYearMonth, setQuantityByYearMonth] = useState<
    KANBAN.EvacuationProcessKanban.chartDto[]
  >([]);
  const [durationByMonthDay, setDurationByMonthDay] = useState<
    KANBAN.EvacuationProcessKanban.chartDto[]
  >([]);
  const [durationByYearMonth, setDurationByYearMonth] = useState<
    KANBAN.EvacuationProcessKanban.chartDto[]
  >([]);

  const [settingFormVisible, setSettingFormVisible] = useState(false);

  useEffect(() => {
    const { kanbanId, intervalTime, cKProgressKanbanSetting } = setting;
    let t: NodeJS.Timer | null = null;

    if (!kanbanId) {
      if (t !== null) {
        clearInterval(t);
      }
      return;
    }
    const params = {
      standardDays: cKProgressKanbanSetting?.standardDays,
      beyondDays: cKProgressKanbanSetting?.beyondDays,
      processConfs: cKProgressKanbanSetting?.chouKongProcessProgressStepList.map((item) => {
        return {
          werks: item.werks,
          fevor: item.fevor,
          operationName: item.extraTypeDes,
        };
      }),
      workUnitConfs: cKProgressKanbanSetting?.chouKongDeviceProgressStepList.map((item) => {
        return {
          ordinal: item.ordinal,
          device: item.device,
          operationUnit: item.operationUnit,
        };
      }),
    };

    const requestWorkUnit = async () => {
      setWorkUnit([]);
      const { data } = await queryWorkUnitIndex(params);
      setWorkUnit(data);
    };
    const requestStatisIndex = async () => {
      const { data } = await queryStatisIndex(params);
      setStatisData(data);
    };
    const requestQByMonthDay = async () => {
      setQuantityByMonthDay([]);
      const { data } = await queryQuantityByMonth(params);
      setQuantityByMonthDay(data);
    };
    const requestQByYearMonth = async () => {
      setQuantityByYearMonth([]);
      const { data } = await queryQuantityByYearMonth(params);
      setQuantityByYearMonth(data);
    };
    const requestDByMonthDay = async () => {
      setDurationByMonthDay([]);
      const { data } = await queryDurationByDMonthDay(params);
      setDurationByMonthDay(data);
    };
    const requestDByYearMonth = async () => {
      const { data } = await queryDurationByDYearMonth(params);
      setDurationByYearMonth(data);
    };

    const refresh = () => {
      requestWorkUnit();
      requestStatisIndex();
      requestQByMonthDay();
      requestQByYearMonth();
      requestDByMonthDay();
      requestDByYearMonth();
    };

    refresh();

    t = setInterval(() => {
      refresh();
    }, intervalTime * 1000);

    return () => {
      if (t !== null) {
        clearInterval(t);
      }
    };
  }, [setting]);

  const handleClass = (status: string) => {
    if (status === '1') {
      return '';
    }
    return 'status' + status;
  };

  const [modalParams, setModalParams] = useState({
    workUnitName: '',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = (name) => {
    setModalParams({ ...modalParams, workUnitName: name });
    setIsModalOpen(true);
  };
  const closeModal = () => setIsModalOpen(false);

  return (
    <>
      <KanbanStyle
        headerText="工序看板"
        subTitle={setting.cKProgressKanbanSetting?.kanbTitle}
        autoResize={setting.autoResize}
        onHeaderClick={() => {
          setSettingFormVisible(true);
        }}
      >
        <div className="page-container">
          <div className="top-container">
            <div className="count-container">
              <div className="left">
                <span>在制：{statisData.productionNum || 0}</span>
                <span>待产：{statisData.prepareProductionNum || 0}</span>
                <span>超期数量：{statisData.overdueNum || 0}</span>
              </div>
              <div className="right">
                <span>待作业</span>
                <span>作业中</span>
                <span>超期1-{setting.cKProgressKanbanSetting?.beyondDays || 'N'}天</span>
                <span>超期{setting.cKProgressKanbanSetting?.beyondDays || 'N'}天以上</span>
              </div>
            </div>
            <div className="info-container">
              {workUnit.map((item) => {
                return (
                  <div
                    onClick={() => showModal(item.workUnitName)}
                    className={['item', handleClass(item.status)].join(' ')}
                    key={item.workUnitName}
                  >
                    <p className="code">{item.equipmentName}</p>
                    <div className="time">{item.actualStartDate || ''}</div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="bottom-container">
            <TrendChart title="当月合格数量趋势图" data={quantityByMonthDay} />
            <TrendChart title="当年合格数量趋势图" data={quantityByYearMonth} />
            <TrendChart
              title="当月平均时间趋势图（天）"
              data={durationByMonthDay}
              color="#663396"
            />
            <TrendChart
              title="当年平均时间趋势图（天）"
              data={durationByYearMonth}
              color="#663396"
            />
          </div>
        </div>
      </KanbanStyle>

      <Modal
        title={'抽空工序批次信息'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <PartModalTable values={modalParams} />
      </Modal>
      <SettingForm
        values={{ ...setting }}
        visible={settingFormVisible}
        onVisibleChange={setSettingFormVisible}
        onSubmitting={async (settingParams) => {
          setSetting({ ...settingParams });
        }}
      />
    </>
  );
};

export default EvacuationProcessKanban;
