import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import TabsContent from '@/components/TabsContent';
import {
  getHistoryRecord,
  queryProjectConfig,
  querySimulationProfit,
} from '@/services/SmartOps';
import { getCameraList, getDetail } 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 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 } = props;

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

  // const [eTime, setETime] = useState(time ? time : dayjs().format('YYYY-MM-DD HH:mm:ss'));
  // const [sTime, setSTime] = useState(
  //   time
  //     ? dayjs(time)
  //         .subtract(10, 'minute')
  //         .format('YYYY-MM-DD HH:mm:ss')
  //     : s_time
  // );
  // if (ruleList?.indexOf(projectId * 1) != -1) {
  //   isNewRole = true;
  // }

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

  const [tableData, setTableData] = useState([]);
  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 = () => {
    //工艺分析
    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));
      },
    });
  };

  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 { run: detailRun } = useRequest(getDetail, {
    manual: true,
    fetchKey: (id) => id,
    cacheKey: (id) => id,
    onSuccess: (data) => {
      var item = tableData?.list?.find((child) => child.id === data.id);
      if (item) {
        item.url = base64ToImageUrl(data.event_bg);
        item.data = data;
      }
      var data = {
        list: [...tableData?.list],
        pagination: tableData?.pagination,
      };
      setTableData(data);
    },
  });
  const { run, loading: loadingVideo } = useRequest(
    () =>
      getCameraList(projectId, {
        s_time: sTime,
        e_time: eTime,
        pageSize: 999,
      }),
    {
      manual: true,
      onSuccess: (data) => {
        setTableData(data);
        sendUnityMsg(data?.list);
        // data?.list?.forEach(item => {
        //   detailRun(item.id, { signal: signalRef.current.signal });
        // });
      },
    },
  );

  const videoAnalysisNumber = tableData?.pagination?.total || 0;
  const AnalysisNumber = list?.pagenation?.total || 0;

  function base64ToImageUrl(base64String) {
    const byteCharacters = atob(base64String);
    const byteArrays = [];

    for (let i = 0; i < byteCharacters.length; i++) {
      byteArrays.push(byteCharacters.charCodeAt(i));
    }

    const byteArray = new Uint8Array(byteArrays);
    const blob = new Blob([byteArray], { type: 'image/png' });
    const imageUrl = URL.createObjectURL(blob);

    return imageUrl;
  }
  // 利润
  const { data: profitData, run: getProfit } = useRequest(
    () =>
      querySimulationProfit({
        project_id: projectId,
        s_time: dayjs(eTime).subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
        e_time: eTime,
      }),
    {
      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 sendUnityMsg = (list) => {
    if (!list || list?.length == 0) return;
    const names = list.map((item) => item.device_name);
    UnityAction.sendMsg('SensorAnalysis', names.join(','));
  };

  const onChangeTab = (type) => {
    UnityAction.sendMsg('SmartAnalysisTab', type);
    if (type == '3') {
      tableData?.list?.forEach((item) => {
        detailRun(item.id, { signal: signalRef.current.signal });
      });
    }
  };

  useEffect(() => {
    if (!eTime) return;
    initDate();
    runWork();
    run();
    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>
      {/* {time && (
        <Button
          type="primary"
          style={{ marginBottom: 20 }}
          onClick={() => navigate(-1)}
        >
          返回
        </Button>
      )} */}
      <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}>
              工艺分析：
              {list?.pagenation?.total > 0
                ? `${list?.pagenation?.total}项可优化`
                : '暂无优化'}
            </div>
            <div className={styles.item3}>
              感知分析：
              {videoAnalysisNumber > 0
                ? `${videoAnalysisNumber}项可优化`
                : '暂无优化'}
            </div>
          </div>
        </div>
        <div className={styles.text}>通过智慧分析预计可省{profitData}元</div>
      </div>
      <div className={styles.tabContent}>
        <TabsContent
          defaultActiveKey="1"
          items={[
            {
              label: `工况分析(${loadingWork ? '-' : optimizationNumber})`,
              key: '1',
              children: (
                <WorkAnalysis
                  workAnalysisRequest={workAnalysisRequest}
                  projectId={projectId}
                  loading={loadingWork}
                  eTime={eTime}
                />
              ),
            },
            {
              label: `工艺分析(${loading ? '-' : AnalysisNumber})`,
              key: '2',
              children: <Analysis />,
            },
            {
              label: `感知分析(${loadingVideo ? '-' : videoAnalysisNumber})`,
              key: '3',
              children: (
                <VideoAnalysis data={tableData} 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, loading }) => ({
  list: smartOps.list,
  loading: loading.models.smartOps,
  processList: smartOps.processList,
}))(SmartOps);
