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 ComprehensiveDeviceEcpDataCount = KANBAN.ProductionComprehens.ComprehensiveDeviceEcpDataCount;
type ComprehensiveDataCount = KANBAN.ProductionComprehens.ComprehensiveDataCount;
const Main: React.FC = () => {
  const intl = useIntl();
  const [setting, setSetting] = useState<Setting>({
    autoResize: true,
    intervalTime: 600,
    rowMovingTime: 5,
    lineName: intl.formatMessage({
      id: '全厂'
    }),
    dataRange: 1,
    planSource: 1,
  });

  // 月度计划指标
  const [monthData, setMonthData] = useState<any>(
    {
      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<Array<any>>([]);
  // 不合格分布
  const [countWeldingPassRate, setCountWeldingPassRate] = useState<Number>(0);
  // 设备异常
  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 { intervalTime } = setting;
    // 查询工序产量
    const queryProcessYieldData1 = async () => {
      const body = {
        lineName: setting?.lineName === intl.formatMessage({
          id: '全厂'
        }) ? null : setting?.lineName
      };
      const { code: code, data: data } = await queryEquipmentCurrentMonthStat(body);
      if (code !== 200 || !data) {
        setMonthData({
          abnormalNum: null,
          equipNum: null,
          equipAvailability: null,
          qualifiedRatio: null,
          totalOutput: null,
          unProcessNum: null
        });
        setProcessDefectRatioData([])
        setCountWeldingPassRate(0)
        setEquipMap([])
        return
      }
      const { equipMap, equipAvailability, abnormalInfoList, abnormalNum, equipNum, qualifiedRatio, totalOutput, unProcessNum } = data
      const equipList = []
      for (let key in equipMap) {
        equipList.push({
          name: key,
          arr: equipMap[key]
        })
      }
      setMonthData({
        abnormalNum,
        equipAvailability,
        equipNum,
        qualifiedRatio,
        totalOutput,
        unProcessNum
      });
      setProcessDefectRatioData(abnormalInfoList)
      setCountWeldingPassRate(equipAvailability)
      setEquipMap(equipList)
    };


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

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

    return () => {
      if (t !== null) {
        clearInterval(t);
      }
    };
  }, [setting]);
  
  return (
    <>
      <KanbanStyle
        headerText={intl.formatMessage({
          id: '设备综合看板'
        })}
        style={{backgroundColor: '#00094f'}}
        subTitle={setting?.lineName}
        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.rightTopBottomContainer}>
                <PassingRate
                  data={countWeldingPassRate}
                  setting={setting}
                />
              </div>
            </div>
            <div className={styles.rightCenterContainer}>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                    {intl.formatMessage({ id: '总产量' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#00b88f'}}>
                    {monthData.totalOutput || 0}
                  </span>
                </div>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                    {intl.formatMessage({ id: '利用率' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#f0f104'}}>
                    {monthData.equipAvailability ? monthData.equipAvailability + '%' : 0+ '%'}
                  </span>
                </div>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                  {intl.formatMessage({ id: '设备数' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#00b88f'}}>
                    {monthData.equipNum || 0	}
                  </span>
                </div>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                  {intl.formatMessage({ id: '合格率' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#00b88f'}}>
                  {monthData.qualifiedRatio ? monthData.qualifiedRatio + '%' : 0+ '%'}
                  </span>
                </div>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                  {intl.formatMessage({ id: '异常数' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#f0f104'}}>
                    {monthData.abnormalNum || 0}
                  </span>
                </div>
                <div className={styles.rightCenterInner}>
                  <span className={styles.rightLabel}>
                  {intl.formatMessage({ id: '待处理' })}：
                  </span>
                  <span className={styles.rightValue} style={{color: '#f0f104'}}>
                    {monthData.unProcessNum || 0}
                  </span>
                </div>
            </div>
            {/* 当月工序合格率 */}
            <div className={styles.rightBottomContainer}>
              <div className={styles.rightBottomContent}>
                <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;
