import React, { useEffect, useState } from 'react';
import KanbanStyle from '../components/FHD1080P/Style2';
import './index.less';
import Efficiency from './components/efficiency';
import MissingMaterial from './components/missingMaterial';
import PartProgress from './components/partProgress';
import Abnormal from './components/abnormal';
import type { Setting } from './components/SettingForm';
import SettingForm from './components/SettingForm';
import {
  queryPartScheduleIndexData,
  queryCountCurrentLackMaterialKanban,
  queryCountCurrentMonthLackMaterialKanban,
  queryCountMaterialDeliveryRate,
  queryCountOrderPunctualRate,
} from './services/api';

import {
  findAbnormalOverdueSetting,
  queryComprehensiveDeviceEcpData,
  queryComprehensiveProdEcpData,
  queryComprehensiveQualityEcpData,
} from '../productionComprehens/services/api';

type AbnormalOverdueSetting = KANBAN.ProductionComprehens.AbnormalOverdueSetting;
type PartScheduleIndexData = KANBAN.MaterialSynthesis.PartScheduleIndexDataDto;
type CountCurrentLackMaterialKanbanDto = KANBAN.MaterialSynthesis.CountCurrentLackMaterialKanbanDto;
type CountCurrentMonthLackMaterialKanbanDto =
  KANBAN.MaterialSynthesis.CountCurrentMonthLackMaterialKanbanDto;
type ComprehensiveDeviceEcpDataCount = KANBAN.ProductionComprehens.ComprehensiveDeviceEcpDataCount;
type ComprehensiveDataCount = KANBAN.ProductionComprehens.ComprehensiveDataCount;

const Main: React.FC = () => {
  const [setting, setSetting] = useState<Setting>({
    autoResize: true,
    intervalTime: 600,
    rowMovingTime: 5,
    productionProgressKanbanSetting: undefined,
    kanbanId: '',
  });
  const [missingMaterialMonthData, setMissingMaterialMonthData] = useState<
    CountCurrentMonthLackMaterialKanbanDto[]
  >([]);
  const [missingMaterialLackData, setMissingMaterialLackData] = useState<
    CountCurrentLackMaterialKanbanDto[]
  >([]);
  const [settingFormVisible, setSettingFormVisible] = useState(false);
  const [partScheduleIndexData, setPartScheduleIndexData] = useState<PartScheduleIndexData[]>([]);
  const [abnormalOverdueSetting, setAbnormalOverdueSetting] = useState<AbnormalOverdueSetting>({
    diffDayProduction: 0,
    diffDayEquipment: 0,
    diffDayQuality: 0,
  });
  const [deliveryRateData, setDeliveryRateData] = useState({
    finishedRate: 0,
    punctualRate: 0,
  });
  const [punctualRateData, setPunctualRateData] = useState({
    orderOnlinePunctualRate: 0,
    orderOfflinePunctualRate: 0,
  });
  // 设备异常
  const [abnormalDeviceData, setAbnormalDeviceData] = useState<ComprehensiveDeviceEcpDataCount>({
    createIssueNumber: 0,
    beyondNumber: 0,
    currentMonthNumber: 0,
    deviceEcpNumber: 0,
    deviceNorNumber: 0,
  });
  // 生产异常
  const [abnormalProdData, setAbnormalProdData] = useState<ComprehensiveDataCount>({
    createIssueNumber: 0, //未关闭
    beyondNumber: 0, //超期
    currentMonthNumber: 0, //当月异常
  });
  // 质量异常
  const [abnormalQualityData, setAbnormalQualityData] = useState<ComprehensiveDataCount>({
    createIssueNumber: 0, //未关闭
    beyondNumber: 0, //超期
    currentMonthNumber: 0, //当月异常
  });

  useEffect(() => {
    const { kanbanId, intervalTime } = setting;
    let t: NodeJS.Timer | null = null;
    if (!kanbanId) {
      setMissingMaterialMonthData([]);
      setMissingMaterialLackData([]);
      setPartScheduleIndexData([]);
      setDeliveryRateData({
        finishedRate: 0,
        punctualRate: 0,
      });
      setPunctualRateData({
        orderOnlinePunctualRate: 0,
        orderOfflinePunctualRate: 0,
      });

      const tmp = {
        createIssueNumber: 0, //未关闭
        beyondNumber: 0, //超期
        currentMonthNumber: 0,
      };
      setAbnormalQualityData(tmp);
      setAbnormalProdData(tmp);
      setAbnormalDeviceData({ ...tmp, deviceEcpNumber: 0, deviceNorNumber: 0 });

      if (t !== null) {
        clearInterval(t);
      }
      return;
    }

    // 零部件
    const requestPartScheduleIndexData = async (kanbanSettingId: string) => {
      const { data } = await queryPartScheduleIndexData({ kanbanSettingId });
      setPartScheduleIndexData(data);
    };
    // 缺料分布 和 趋势图
    const requestMissMaterialData = async () => {
      const { data } = await queryCountCurrentMonthLackMaterialKanban();
      const { data: lack } = await queryCountCurrentLackMaterialKanban();
      setMissingMaterialMonthData(data);
      setMissingMaterialLackData(lack);
    };
    // 获取四个饼图
    const requestRate = async (settingId: string) => {
      const { data: deliveryRate } = await queryCountMaterialDeliveryRate({ settingId });
      const { data: punctualRate } = await queryCountOrderPunctualRate({ settingId });

      setDeliveryRateData(deliveryRate);
      setPunctualRateData(punctualRate);
    };
    // 异常分布
    const requestAbnormal = async (settingId: string) => {
      // 异常超期天数获取
      const abnormalOverdueSettingList = await findAbnormalOverdueSetting();
      const tt: AbnormalOverdueSetting = {
        diffDayEquipment: 0,
        diffDayQuality: 0,
        diffDayProduction: 0,
      };
      abnormalOverdueSettingList.forEach((s) => {
        if (s.werks === setting.productionProgressKanbanSetting?.werks) {
          if (s.type.id == 1) {
            //生产
            tt.diffDayProduction = s.overdueDays;
          } else if (s.type.id == 2) {
            //质量
            tt.diffDayQuality = s.overdueDays;
          } else if (s.type.id == 3) {
            //设备
            tt.diffDayEquipment = s.overdueDays;
          }
        }
      });
      setAbnormalOverdueSetting(tt);
      // 质量异常
      const { data: quality } = await queryComprehensiveQualityEcpData({ settingId });
      // 设备异常
      const { data: device } = await queryComprehensiveDeviceEcpData({ settingId });
      // 生产异常
      const { data: prod } = await queryComprehensiveProdEcpData({ settingId });
      setAbnormalDeviceData(device);
      setAbnormalProdData(prod);
      setAbnormalQualityData(quality);
    };

    const refresh = () => {
      requestPartScheduleIndexData(kanbanId);
      requestMissMaterialData();
      requestRate(kanbanId);
      requestAbnormal(kanbanId);
    };

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

    return () => {
      if (t !== null) {
        clearInterval(t);
      }
    };
  }, [setting]);
  // @ts-ignore
  return (
    <>
      <KanbanStyle
        headerText="物料综合看板"
        subTitle={setting.productionProgressKanbanSetting?.kanbTitle}
        autoResize={setting.autoResize}
        onHeaderClick={() => {
          setSettingFormVisible(true);
        }}
      >
        <div className="material-syncthesis-container">
          <div className="left-container">
            {/* 效率图 */}
            <Efficiency
              punctual={punctualRateData}
              delivery={deliveryRateData}
              setting={{
                werks: setting.productionProgressKanbanSetting?.werks || '',
                kanbanId: setting.kanbanId,
              }}
            />
            {/* 异常分布 */}
            <Abnormal
              quality={abnormalQualityData}
              prod={abnormalProdData}
              device={abnormalDeviceData}
              setting={{
                workshopName: setting.productionProgressKanbanSetting?.productDeviceException,
                werks: setting.productionProgressKanbanSetting?.werks || '',
                fevors:
                  setting.productionProgressKanbanSetting?.productionManagerProgressStepList
                    .map((s) => s.fevor)
                    .join(',') || '',
                abnormalOverdueSetting: abnormalOverdueSetting,
              }}
            />
          </div>
          <div className="right-container">
            {/* 缺料部分 */}
            <MissingMaterial month={missingMaterialMonthData} lack={missingMaterialLackData} />
            <PartProgress
              data={partScheduleIndexData}
              setting={{
                conf: setting.productionProgressKanbanSetting?.progressStepList || [],
                werks: setting.productionProgressKanbanSetting?.werks || '',
              }}
            />
          </div>
        </div>
      </KanbanStyle>

      <SettingForm
        values={{ ...setting }}
        visible={settingFormVisible}
        onVisibleChange={setSettingFormVisible}
        onSubmitting={async (settingParams) => {
          setSetting({ ...settingParams });
        }}
      />
    </>
  );
};

export default Main;
