import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import TabsContent from '@/components/TabsContent';
import {
  getHistoryRecord,
  queryProjectConfig,
  querySimulationProfit,
} from '@/services/SmartOps';
import { getPatrolPerception } from '@/services/dumu';
import { GetTokenFromUrl, UnityAction } from '@/utils/utils';
import {
  connect,
  useNavigate,
  useParams,
  useRequest,
  useSearchParams,
} from '@umijs/max';
import { Tabs } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import Analysis from './Analysis';
import DeviceAnalysis from './components/DeviceAnalysis';
import VideoAnalysis from './components/VideoAnalysis';
import WorkAnalysis from './components/WorkAnalysis';
import styles from './index.less';

const { TabPane } = Tabs;
const icon06 = require('@/assets/smartOps/icon06.png');
const icon07 = require('@/assets/smartOps/icon07.png');

let timer = '';

function SmartOps(props) {
  const { list, dispatch, loading, loadingDev, autoReport } = props;

  const navigate = useNavigate();
  const { projectId } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const time = searchParams.get('time');
  const idList = searchParams.get('idList');
  const patrolId = searchParams.get('patrolId');

  const [tab, setTab] = useState('1');
  const [videoNum, setVideoNum] = useState(0);

  const signalRef = useRef();

  const {
    data: reportData,
    loading: reportLoading,
    run: getReportData,
  } = useRequest(
    () =>
      getHistoryRecord(
        convertObject2FormData({ project_id: Number(projectId) }),
      ),
    {
      manual: true,
      formatResult: (res) => {
        let data = res.data.list[0];
        data.Num2Length = data.Num2.split(',').length;
        return data;
      },
    },
  );

  const [sTime, eTime] = useMemo(() => {
    let sTime = null,
      eTime = null;
    if (time) {
      eTime = time;
      sTime = dayjs(eTime).subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss');
    } else if (reportData) {
      eTime = reportData.CTime;
      sTime = dayjs(eTime).subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss');
    }
    return [sTime, eTime];
  }, [reportData]);

  const initDate = () => {
    if (idList || reportData?.Num2) {
      //工艺分析
      dispatch({
        type: 'smartOps/queryList',
        payload: {
          project_id: projectId * 1,
          projectId: projectId * 1,
          ids: idList || reportData.Num2,
          page_size: 999,
          isNewRole: [46, 65, 92, 94].includes(projectId * 1),
        },
        callback: (data) => {
          UnityAction.sendMsg('ProcessAnalysis', JSON.stringify(data?.list));
        },
      });
    }

    dispatch({
      type: 'eqSelfInspection/getPatrolDataById',
      payload: {
        routeId: patrolId || reportData.PatrolId,
      },
      callback: (data) => {
        // console.log(data);
        const message = data?.extendWarningAllData?.map((item) => {
          return {
            DeviceCode: item.DeviceCode,
            grade_alarm: item.Status === 2 || item.Status === 1 ? 1 : 2,
          };
        });
        UnityAction.sendMsg('DevAnalysis', JSON.stringify(message));
      },
    });
  };

  const handlerHistoryClick = () => {
    navigate(
      `/smart-ops/history-record/${projectId}?JWT-TOKEN=${GetTokenFromUrl()}`,
    );
  };
  const handlerRecordClick = () => {
    navigate(
      `/smart-ops/operation-record/${projectId}?JWT-TOKEN=${GetTokenFromUrl()}`,
    );
  };

  // 工况分析
  const {
    data: workAnalysisRequest,
    run: runWork,
    loading: loadingWork,
  } = useRequest(
    () =>
      queryProjectConfig({
        project_id: projectId,
        s_time: sTime,
        e_time: eTime,
      }),
    {
      manual: true,
      onSuccess(res) {
        if (!res) return;
        UnityAction.sendMsg(
          'WorkAnalysis',
          JSON.stringify(res.project_categorys),
        );
      },
    },
  );

  const optimizationNumber = workAnalysisRequest?.optimizationNumber || 0;

  //感知分析
  const {
    data: videoData,
    loading: loadingVideo,
    run: runVideo,
  } = useRequest(
    () =>
      getPatrolPerception({
        project_id: projectId * 1,
        patrol_id: patrolId || reportData.PatrolId,
        s_time: sTime,
        e_time: eTime,
      }),
    {
      manual: true,
      onSuccess: (data) => {
        const count1 = data.dumu_list?.length || 0;
        const count2 =
          data.environment_list?.filter((item) => item.status)?.length || 0;
        // const count3 =
        //   data.fluid_level_list?.filter((item) => item.status)?.length || 0;
        setVideoNum(count1 + count2 + count3);
        const Cam =
          data.dumu_list?.map((item) => {
            item.key = `dumu_${item.id}`;
            return item.device_name;
          }) || [];
        const Dev =
          data.environment_list?.map((item, index) => {
            item.key = `environment_${index}_${item.device_code}`;
            return { DeviceCode: item.device_code, grade_alarm: item.status };
          }) || [];
        // const Dev2 =
        //   data.fluid_level_list?.map((item, index) => {
        //     item.key = `fluid_${index}_${item.device_code}`;
        //     return { DeviceCode: item.device_code, grade_alarm: item.status };
        //   }) || [];
        const params = { Cam, Dev };
        UnityAction.sendMsg('SensorAnalysis', JSON.stringify(params));
      },
    },
  );

  const AnalysisNumber = list?.pagenation?.total || 0;

  const deviceNumber = autoReport?.extendWarningData?.length || 0;

  // 利润
  const { data: profitData, run: getProfit } = useRequest(
    () =>
      querySimulationProfit({
        project_id: projectId,
        s_time: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:00:00'),
        e_time: dayjs().format('YYYY-MM-DD HH:00:00'),
      }),
    {
      formatResult(data) {
        if (!data?.info) return '-';

        return Object.values(data.info).reduce(
          (total, currentValue) => total + currentValue,
          0,
        );
      },
      manual: true,
    },
  );

  const showTime = useMemo(() => {
    if (!eTime) return '';
    return dayjs(eTime).format('MM-DD HH:mm');
  }, [eTime]);

  const onChangeTab = (type) => {
    setTab(type);
    UnityAction.sendMsg('SmartAnalysisTab', type);
  };

  useEffect(() => {
    if (!eTime) return;
    initDate();
    runWork();
    runVideo();
    getProfit();
  }, [eTime]);

  useEffect(() => {
    if (!time) {
      getReportData();
      console.log('--------10分钟刷新数据--------', eTime);
      timer = setInterval(() => {
        getReportData();
      }, 60000);
    }

    dispatch({
      type: 'smartOps/queryProcessSection',
      payload: projectId,
    });

    // 通知unity当前处于工况分析
    UnityAction.sendMsg('SmartAnalysisTab', 1);

    const controller = new AbortController();
    signalRef.current = controller;

    return () => {
      signalRef.current.abort();
      clearInterval(timer);
    };
  }, []);

  return (
    <PageContent>
      <PageTitle returnable={time}>智慧运营</PageTitle>
      <div className={`card-box ${styles.topContent}`}>
        <div className={styles.titleContent}>
          <span className={styles.time}>{showTime}</span>
          {!time && (
            <div style={{ display: 'flex' }}>
              <div className={styles.iconLeft} onClick={handlerHistoryClick} />
              <div className={styles.iconRight} onClick={handlerRecordClick} />
            </div>
          )}
        </div>
        <div className={styles.middle}>
          <div className={styles.left}>
            <div className={styles.in} />
            <div className={styles.out} />
          </div>
          <div className={styles.right}>
            <div className={styles.item1}>
              工况分析：
              {optimizationNumber > 0
                ? `${optimizationNumber}项可优化`
                : '暂无优化'}
            </div>
            <div className={styles.item2}>
              设备分析：
              {autoReport?.extendWarningData?.length > 0
                ? `${autoReport?.extendWarningData?.length}项可优化`
                : '暂无优化'}
            </div>
            <div className={styles.item3}>
              工艺分析：
              {list?.pagenation?.total > 0
                ? `${list?.pagenation?.total}项可优化`
                : '暂无优化'}
            </div>
            <div className={styles.item4}>
              感知分析：{videoNum > 0 ? `${videoNum}项可优化` : '暂无优化'}
            </div>
          </div>
        </div>
        <div className={styles.text}>通过智慧分析预计可省{profitData}元</div>
      </div>
      <div className={styles.tabContent}>
        <TabsContent
          defaultActiveKey="1"
          small
          items={[
            {
              label: `工况分析(${loadingWork ? '-' : optimizationNumber})`,
              key: '1',
              children: (
                <WorkAnalysis
                  workAnalysisRequest={workAnalysisRequest}
                  projectId={projectId}
                  loading={loadingWork}
                  eTime={eTime}
                />
              ),
            },
            {
              label: `设备分析(${
                loadingDev ? '-' : autoReport?.extendWarningData?.length
              })`,
              key: '4',
              children: <DeviceAnalysis />,
            },
            {
              label: `工艺分析(${loading ? '-' : AnalysisNumber})`,
              key: '2',
              children: <Analysis />,
            },
            {
              label: `感知分析(${loadingVideo ? '-' : videoNum})`,
              key: '3',
              children: (
                <VideoAnalysis
                  videoNum={videoNum}
                  videoData={videoData}
                  loading={loadingVideo}
                />
              ),
            },
          ]}
          onChange={onChangeTab}
        />
      </div>
    </PageContent>
  );
}

const convertObject2FormData = (params) => {
  const formData = new FormData();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== null && value !== undefined && value !== NaN) {
      formData.append(key, value);
    }
  });
  return formData;
};

export default connect(({ smartOps, eqSelfInspection, loading }) => ({
  list: smartOps.list,
  loading: loading.models.smartOps,
  processList: smartOps.processList,
  autoReport: eqSelfInspection.autoReport,
  loadingDev: loading.effects['eqSelfInspection/getPatrolDataById'],
}))(SmartOps);
