import React, { useEffect } from 'react';
import { Outlet } from 'react-router';
import { Toast } from 'antd-mobile';

import Bridge, { bridgeOb, emitBridgeEvent } from './utils/bridge';
import { useAppDispatch, useAppSelector } from './utils/hooks';
import { addNewPoint, updateTaskState } from './store/features/measureSlice';
import {
  refreshStationList,
  updateBleList,
  updateDevice,
  updateSyncProgress,
} from './store/features/contextSlice';
import { createWebSocket, sharedWsUrl } from './services/socket';
import {
  fetchOrgTree,
  fetchRailTypes,
  syncBaseData,
  updateSyncBaseProgress,
} from './store/features/baseData';

function App() {
  const dispatch = useAppDispatch();
  const baseState = useAppSelector((state) => state.baseData);
  const contextState = useAppSelector((state) => state.context);

  // 获取轨型数据
  useEffect(() => {
    if (baseState.railTypes.length === 0) {
      dispatch(fetchRailTypes());
    }
  }, [baseState.railTypes.length, dispatch]);

  // 监听推送消息，更新store
  useEffect(() => {
    const subscription = bridgeOb.subscribe((datagram) => {
      if (datagram.type === 'measure-event') {
        dispatch(updateTaskState(datagram.data));
      } else if (datagram.type === 'measure-point') {
        dispatch(addNewPoint(datagram.data));
      } else if (datagram.type === 'peripheral-status') {
        dispatch(updateDevice(datagram.data));
      } else if (datagram.type === 'ble-list') {
        dispatch(updateBleList(datagram.data));
      } else if (datagram.type === 'sync-progress') {
        dispatch(updateSyncProgress(datagram.data));
      } else if (datagram.type === 'update-base-progress') {
        dispatch(updateSyncBaseProgress(datagram.data));
      }
    });
    return () => subscription.unsubscribe();
  }, [dispatch]);

  // 开启推送
  useEffect(() => {
    // if (appWebview) {
    //   registerBridgeFunc();
    // } else {
    //连接websocket
    const wsClient = createWebSocket(sharedWsUrl);
    const subscription = wsClient.dataOb.subscribe((data) => {
      emitBridgeEvent(data);
    });
    wsClient.connect();
    return () => subscription.unsubscribe();
    // }
  }, []);

  // 初始同步数据
  useEffect(() => {
    Bridge.needSyncBaseData().then((res) => {
      if (!res.success) {
        return Toast.show(res.message);
      }
      if (res.data.needSync) {
        dispatch(syncBaseData());
      } else {
        dispatch(fetchOrgTree());
      }
    });
  }, [dispatch]);

  // 同步完成后，重新获取局/段/线信息
  useEffect(() => {
    if (
      baseState.syncBaseProgress.finish &&
      !baseState.syncBaseProgress.error &&
      baseState.syncBaseProgress.progress === 100
    ) {
      dispatch(fetchOrgTree());
    }
  }, [baseState.syncBaseProgress, dispatch]);

  // 预获取车站信息
  useEffect(() => {
    if (contextState.currXMCode) {
      dispatch(
        refreshStationList({
          tljCode: contextState.currOrgCode,
          gwdCode: contextState.currGWDCode,
          xmCode: contextState.currXMCode,
        })
      );
    }
  }, [contextState.currGWDCode, contextState.currOrgCode, contextState.currXMCode, dispatch]);

  return (
    <>
      <Outlet />

      {/* <Mask visible={baseState.syncingBaseData}>
        <div className="flex flex-col items-center gap-4 absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
          <SpinLoading color="white" />
          <p className="text-white text-sm">正在同步，请稍候...</p>
        </div>
      </Mask> */}
    </>
  );
}

export default App;
