import React, { useEffect, useState } from 'react';
import KanbanStyle from '../components/FHD1080P/Style2';
import styles from './index.less';
import DeviceGroup from './components/DeviceGroup';
import ProcessFail from './components/ProcessFail';
import PassingRate from './components/PassingRate';
import type { Setting } from './components/SettingForm';
import SettingForm from './components/SettingForm';
import { useIntl } from 'umi';
import {
  queryEquipmentCurrentMonthStat,
  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 [equipMap, setEquipMap] = useState<any>([]);
  // 工序未通过率
  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 = {
        lineName: null
      };
      const { data: { equipMap } } = await queryEquipmentCurrentMonthStat(body);
      const equipList = []
      for (let key in equipMap) {
        equipList.push({
          name: key,
          arr: equipMap[key]
        })
      }
      setEquipMap(equipList)
    };
    // 异常分布
    const requestAbnormal = async (settingId: string) => {
      // 异常超期天数获取
      // const abnormalOverdueSettingList = await findAbnormalOverdueSetting();
      const tt: AbnormalOverdueSetting = {
        diffDayEquipment: 0,
        diffDayQuality: 0,
        diffDayProduction: 0,
      };
      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}>
            <DeviceGroup
              abnormalDeviceData={abnormalDeviceData}
              abnormalQualityData={abnormalQualityData}
              abnormalProdData={abnormalProdData}
              factoryLine={equipMap}
              setting={{
                fevors:
                  setting.productionComprehensKanbanSetting?.processPMProgressStepList
                    ?.filter((s) => s.pmTypeId == 1)
                    .map((s) => s.fevor)
                    .join(',') || '',
                rowMovingTime: setting.rowMovingTime,
                werks: setting.productionComprehensKanbanSetting?.werks || '',
                abnormalOverdueSetting: abnormalOverdueSetting,
                workshopName: setting.productionComprehensKanbanSetting?.productDeviceException,
              }}
            />
          </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;
