import React, { useEffect, useRef, useState } from 'react';
import KanbanStyle from '../components/FHD1080P/Style2';
import styles from './index.less';
import './index.less';
import Abnormal from './components/Abnormal';
import ProcessOutput from './components/ProcessOutput';
import ProcessFail from './components/ProcessFail';
import MonthlyPlan from './components/MonthlyPlan';
import PassingRate from './components/PassingRate';
import type { Setting } from './components/SettingForm';
import SettingForm from './components/SettingForm';
import {
  queryProductionComprehensProcessOutputData,
  queryProcessDefectRatioData,
  queryWorkOrderMonthlyIndexData1,
  queryComprehensiveQualityEcpData,
  queryComprehensiveDeviceEcpData,
  queryComprehensiveProdEcpData,
  queryCountWeldingPassRate,
  findAbnormalOverdueSetting,
  queryDeviceRunTimeEcp,
} from './services/api';

type AbnormalOverdueSetting = KANBAN.QiPingComprehens.AbnormalOverdueSetting;
type ProcessDefectRatioData = KANBAN.QiPingComprehens.ProcessDefectRatioData[];
type ProcessYieldData = KANBAN.QiPingComprehens.ProcessYieldData[];
type ComprehensiveDeviceEcpDataCount = KANBAN.QiPingComprehens.ComprehensiveDeviceEcpDataCount;
type ComprehensiveDataCount = KANBAN.QiPingComprehens.ComprehensiveDataCount;
type CountWeldingPassRate = KANBAN.QiPingComprehens.CountWeldingPassRate;

const Main: React.FC = () => {
  const [setting, setSetting] = useState<Setting>({
    autoResize: true,
    intervalTime: 600,
    rowMovingTime: 5,
    productionComprehensKanbanSetting: undefined,
    productionComprehensKanbanSettingId: undefined,
    dataRange: 1,
    planSource: 1,
  });

  // 月度计划指标
  const [monthData, setMonthData] = useState<KANBAN.QiPingComprehens.WorkOrderMonthlyIndexData>({
    startOnTimeRatio: 0, //上线准时率
    endOnTimeRatio: 0, //下线准时率
    stockInOnTimeRatio: 0, //入库准时率
    periodicAccordRatio: 0, //周期符合
    hisPendingQuantity: 0, //历史月待完工
    monthPlanQuantity: 0, //月计划
    accuDailyPlanQuantity: 0, //累计日计划量
    actualFinishQuantity: 0, //实际完工
    monthPlanConcludeRatio: 0, //月计划达成率
  });
  const [deviceStatus, setDeviceStatus] = useState<
    {
      device: string;
      isEcp: string;
      beyondHours: any;
    }[]
  >([]);
  const deviceRef = useRef<HTMLDivElement>(null);
  const [abnormalOverdueSetting, setAbnormalOverdueSetting] = useState<AbnormalOverdueSetting>({
    diffDayProduction: 0,
    diffDayEquipment: 0,
    diffDayQuality: 0,
  });
  // 工序产量
  const [processYieldData, setProcessYieldData] = useState<ProcessYieldData>([]);
  // 工序未通过率
  const [processDefectRatioData, setProcessDefectRatioData] = useState<ProcessDefectRatioData>([]);
  // 焊接通过率
  const [countWeldingPassRate, setCountWeldingPassRate] = useState<CountWeldingPassRate>({
    wholeSetPassRate: 0,
    longitudinalJointRate: 0,
    transverseJointRate: 0,
    piecePassRate: 0,
    selectionRate: 0,
    longitudinalJointBasicRate: 0,
    selectionBasicRate: 0,
    transverseJointBasicRate: 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, //当月异常
  });

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

  let intervalTimer: NodeJS.Timer;
  let timeoutTimer: NodeJS.Timer;

  const autoScrollDevice = () => {
    if (timeoutTimer) {
      clearInterval(timeoutTimer);
    }

    timeoutTimer = setTimeout(() => {
      const scrollH = deviceRef.current?.scrollHeight || 0;
      const clientH = deviceRef.current?.clientHeight || 0;
      if (intervalTimer) {
        clearInterval(intervalTimer);
      }
      if (scrollH == clientH) return;
      intervalTimer = setInterval(() => {
        if (deviceRef.current) {
          const scrollTop = deviceRef.current.scrollTop;
          const distance = scrollH - clientH;
          console.log(clientH, scrollTop, distance);

          if (scrollTop >= distance) {
            deviceRef.current.scrollTop = 0;

            clearInterval(intervalTimer);
            autoScrollDevice();
            return;
          }
          deviceRef.current.scrollTop = scrollTop + 90;
        }
      }, setting.rowMovingTime * 1000);
    }, 0);
  };

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

    if (!productionComprehensKanbanSettingId) {
      // 清除定时器
      if (t !== null) {
        clearInterval(t);
      }
      // 重制图标
      setProcessYieldData([]);
      setProcessDefectRatioData([]);
      setMonthData({
        startOnTimeRatio: 0, //上线准时率
        endOnTimeRatio: 0, //下线准时率
        stockInOnTimeRatio: 0, //入库准时率
        periodicAccordRatio: 0, //周期符合
        hisPendingQuantity: 0, //历史月待完工
        monthPlanQuantity: 0, //月计划
        accuDailyPlanQuantity: 0, //累计日计划量
        actualFinishQuantity: 0, //实际完工
        monthPlanConcludeRatio: 0, //月计划达成率
      });
      setCountWeldingPassRate({
        wholeSetPassRate: 0,
        longitudinalJointRate: 0,
        transverseJointRate: 0,
        piecePassRate: 0,
        selectionRate: 0,
        longitudinalJointBasicRate: 0,
        selectionBasicRate: 0,
        transverseJointBasicRate: 0,
      });
      const tmp = {
        createIssueNumber: 0, //未关闭
        beyondNumber: 0, //超期
        currentMonthNumber: 0,
      };
      setAbnormalQualityData(tmp);
      setAbnormalProdData(tmp);
      setAbnormalDeviceData({ ...tmp, deviceEcpNumber: 0, deviceNorNumber: 0 });
      return;
    }
    const queryDeviceInfo = async () => {
      const { data } = await queryDeviceRunTimeEcp({
        settingId: productionComprehensKanbanSettingId,
      });
      setDeviceStatus(data);

      if (deviceRef.current) {
        deviceRef.current.scrollTop = 0;
        autoScrollDevice();

        // deviceRef.current.onmouseenter = () => {
        //   window.clearInterval(intervalTimer)
        //   window.clearTimeout(timeoutTimer)
        // }

        // deviceRef.current.onmouseleave = () => {
        //   autoScrollDevice()
        // }
      }
    };
    // 查询工序产量
    const queryProcessYieldData1 = async () => {
      const body = {
        kanbanSettingId: productionComprehensKanbanSettingId as string,
        dataRange: dataRange,
        planSource: planSource,
      };
      const { data } = await queryProductionComprehensProcessOutputData(body);
      setProcessYieldData(data);
    };
    // 查询工序未通过率
    const requestProcessDefectRatioData = async (kanbanSettingId: string) => {
      const { data } = await queryProcessDefectRatioData({ kanbanSettingId });
      setProcessDefectRatioData(data);
    };
    // 月度计划指标
    const requestWorkOrderMonthlyIndexData1 = async (kanbanSettingId: string) => {
      const { data } = await queryWorkOrderMonthlyIndexData1({ kanbanSettingId });
      //相关准时率留整数
      data.endOnTimeRatio = Math.round(data.endOnTimeRatio);
      data.monthPlanConcludeRatio = Math.round(data.monthPlanConcludeRatio);
      data.periodicAccordRatio = Math.round(data.periodicAccordRatio);
      data.startOnTimeRatio = Math.round(data.startOnTimeRatio);
      data.stockInOnTimeRatio = Math.round(data.stockInOnTimeRatio);
      setMonthData(data);
    };
    // 异常分布
    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.productionComprehensKanbanSetting?.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 queryPassRate = async (settingId: string) => {
      const { data } = await queryCountWeldingPassRate({ settingId });
      setCountWeldingPassRate(data);
    };

    const refresh = () => {
      queryProcessYieldData1();
      queryDeviceInfo();
      requestWorkOrderMonthlyIndexData1(productionComprehensKanbanSettingId);
      requestProcessDefectRatioData(productionComprehensKanbanSettingId);
      requestAbnormal(productionComprehensKanbanSettingId);
      //queryPassRate(productionComprehensKanbanSettingId);
    };

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

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

  return (
    <>
      <KanbanStyle
        headerText="气瓶综合看板"
        subTitle={setting.productionComprehensKanbanSetting?.kanbTitle}
        autoResize={setting.autoResize}
        onHeaderClick={() => {
          setSettingFormVisible(true);
        }}
      >
        <div className={styles.main}>
          {/* 左边部分：异常分布 */}
          <div className={styles.leftContainer}>
            <div className={styles.topContainer}>异常分布</div>
            <Abnormal
              abnormalDeviceData={abnormalDeviceData}
              abnormalQualityData={abnormalQualityData}
              abnormalProdData={abnormalProdData}
              setting={{
                fevors:
                  setting.productionComprehensKanbanSetting?.processPMProgressStepList
                    ?.filter((s) => s.pmTypeId == 1)
                    .map((s) => s.fevor)
                    .join(',') || '',
                werks: setting.productionComprehensKanbanSetting?.werks || '',
                abnormalOverdueSetting: abnormalOverdueSetting,
                workshopName: setting.productionComprehensKanbanSetting?.productDeviceException,
              }}
            />
          </div>

          {/* 中间部分：月度计划&otd指标、工序产量 */}
          <div className={styles.centerContainer}>
            <div className={styles.centerTopContainer}>
              <MonthlyPlan
                data={monthData}
                kanbanId={setting.productionComprehensKanbanSettingId}
              />
            </div>
            <div className={styles.centerBottomContainer}>
              <div className={styles.centerBottomBg}>
                <div className={styles.centerBottomTitle}>工序产量</div>
                <div style={{ height: '260px', padding: '0px 20px' }}>
                  <ProcessOutput data={processYieldData} setting={setting} />
                </div>
              </div>
            </div>
          </div>

          {/* 右边部分：焊接一次通过率、工序当月一次未通过率 */}
          <div className={styles.rightContainer}>
            {/* 焊接一次通过率 */}
            <div className={styles.rightTopContainer}>
              <div className={styles.rightTopTitle}>
                <span>设备运行状态</span>
                <div className="device-tip">
                  <span className="normal">正常</span>
                  <span className="error">异常</span>
                </div>
              </div>
              <div
                ref={deviceRef}
                className="rigthTopItemContainer"
                style={{
                  gridTemplateRows: `repeat(${Math.ceil(deviceStatus.length / 2)}, 80px)`,
                }}
              >
                {deviceStatus.map((item) => {
                  return (
                    <div
                      className={['item', item.isEcp == '1' ? 'error' : ''].join(' ')}
                      key={item.device}
                    >
                      <div className="code">{item.device}</div>
                      <div>
                        {item.isEcp == '1' ? '停工时长：' : ''}
                        {item.beyondHours}
                        {item.isEcp == '1' ? '小时' : ''}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            {/* 工序当月一次未通过率 */}
            <div className={styles.rightBottomContainer}>
              <div className={styles.rightBottomContent}>
                <div className={styles.rightBottomTitle}>工序当月一次未通过率</div>
                <div style={{ padding: '0 20px', height: '376px' }}>
                  <ProcessFail data={processDefectRatioData} setting={setting} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </KanbanStyle>

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

export default Main;
