import React, { useEffect, useState } from 'react';
import KanbanStyle from '../components/FHD1080P/Style2';
import styles from './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 { useIntl } from 'umi';
import {
  queryProductionComprehensProcessOutputData,
  currentMonthStat,
  findAbnormalOverdueSetting,
} from './services/api';

type AbnormalOverdueSetting = KANBAN.ProductionComprehens.AbnormalOverdueSetting;
type ProcessDefectRatioData = KANBAN.ProductionComprehens.ProcessDefectRatioData[];
type ProcessYieldData = KANBAN.ProductionComprehens.ProcessYieldData[];
type ComprehensiveDeviceEcpDataCount = KANBAN.ProductionComprehens.ComprehensiveDeviceEcpDataCount;
type ComprehensiveDataCount = KANBAN.ProductionComprehens.ComprehensiveDataCount;
type CountWeldingPassRate = KANBAN.ProductionComprehens.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.ProductionComprehens.WorkOrderMonthlyIndexData>(
    {
      startOnTimeRatio: 0, //上线准时率
      endOnTimeRatio: 0, //下线准时率
      qualifiedRatio: 0, //产品合格率
      hisPendingQuantity: 0, //历史月待完工
      monthPlanQuantity: 0, //月计划
      expireFinishQuantity: 0, //超期完工
      actualFinishQuantity: 0, //实际完工
      monthPlanConcludeRatio: 0, //月计划达成率
    },
  );

  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<Array<any>>([]);
  // 设备异常
  const [abnormalDeviceData, setAbnormalDeviceData] = useState<ComprehensiveDeviceEcpDataCount>({
    unCloseCt: 0,
    expireUnClose: 0,
    totalCt: 0,
    equipErrorCt: 0,
    equipCt: 0,
  });
  // 生产异常
  const [abnormalProdData, setAbnormalProdData] = useState<ComprehensiveDataCount>({
    unCloseCt: 0, //未关闭
    expireUnClose: 0, //超期
    totalCt: 0, //当月异常
  });
  // 质量异常
  const [abnormalQualityData, setAbnormalQualityData] = useState<Array<Number>>([]);

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

  useEffect(() => {
    // console.log('sadas执行' )
    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, //下线准时率
    //     qualifiedRatio: 0, //产品合格率
    //     hisPendingQuantity: 0, //历史月待完工
    //     monthPlanQuantity: 0, //月计划
    //     expireFinishQuantity: 0, //超期完工
    //     actualFinishQuantity: 0, //实际完工
    //     monthPlanConcludeRatio: 0, //月计划达成率
    //   });
    //   setCountWeldingPassRate({
    //     wholeSetPassRate: 0,
    //     longitudinalJointRate: 0,
    //     transverseJointRate: 0,
    //     piecePassRate: 0,
    //     selectionRate: 0,
    //     longitudinalJointBasicRate: 0,
    //     selectionBasicRate: 0,
    //     transverseJointBasicRate: 0,
    //   });
    //   const tmp = {
    //     unCloseCt: 0, //未关闭
    //     expireUnClose: 0, //超期
    //     totalCt: 0,
    //   };
    //   setAbnormalQualityData(tmp);
    //   setAbnormalProdData(tmp);
    //   setAbnormalDeviceData({ ...tmp, equipErrorCt: 0, equipCt: 0 });
    //   return;
    // }
    // 查询工序产量
    const queryProcessYieldData1 = async () => {
      const body = {
        kanbanSettingId: productionComprehensKanbanSettingId as string,
        dataRange: dataRange,
        planSource: planSource,
      };
      const { data: { outputList, processMonthlyIndexDto, qualifiedRateList, abnormalCauseData } } = await queryProductionComprehensProcessOutputData(body);
      setProcessYieldData(outputList);
      setProcessDefectRatioData(qualifiedRateList);
      setCountWeldingPassRate(abnormalCauseData);
      //相关准时率留整数
      processMonthlyIndexDto.endOnTimeRatio = Math.round(processMonthlyIndexDto.endOnTimeRatio);
      processMonthlyIndexDto.monthPlanConcludeRatio = Math.round(processMonthlyIndexDto.monthPlanConcludeRatio);
      processMonthlyIndexDto.startOnTimeRatio = Math.round(processMonthlyIndexDto.startOnTimeRatio);
      processMonthlyIndexDto.qualifiedRatio = Math.round(processMonthlyIndexDto.qualifiedRatio);
      setMonthData(processMonthlyIndexDto);
    };
    // 异常分布
    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: {equipAbnormal, productAbnormal, equipErrorArr, equipCt, equipErrorCt} } = await currentMonthStat({ settingId });
      setAbnormalDeviceData({
        equipCt,
        equipErrorCt,
        ...equipAbnormal
      });
      setAbnormalProdData(productAbnormal);
      setAbnormalQualityData(equipErrorArr);
      
    };


    const refresh = () => {
      queryProcessYieldData1();
      requestAbnormal(productionComprehensKanbanSettingId);
    };

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

    return () => {
      if (t !== null) {
        clearInterval(t);
      }
    };
  }, [setting]);
  const intl = useIntl();
  return (
    <>
      <KanbanStyle
        headerText={intl.formatMessage({
          id: '生产综合看板'
        })}
        subTitle={setting.productionComprehensKanbanSetting?.kanbTitle}
        autoResize={setting.autoResize}
        onHeaderClick={() => {
          setSettingFormVisible(true);
        }}
      >
        <div className={styles.main}>
          {/* 左边部分：异常分布 */}
          <div className={styles.leftContainer}>
            <div className={styles.topContainer}>{intl.formatMessage({id: '异常分布'})}</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}>{intl.formatMessage({id: '工序产量'})}</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}>{intl.formatMessage({id: '不合格分布'})}</div>
              <div className={styles.rightTopBottomContainer}>
                <PassingRate
                  data={countWeldingPassRate}
                  setting={setting}
                />
              </div>
            </div>
            {/* 当月工序合格率 */}
            <div className={styles.rightBottomContainer}>
              <div className={styles.rightBottomContent}>
                <div className={styles.rightBottomTitle}>{intl.formatMessage({id: '当月工序合格率'})}</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;
