import { StackScreenProps } from '@react-navigation/stack';
import * as React from 'react';
import { useNavigation } from '@react-navigation/native';
import { WebView } from 'react-native-webview';

import { useTranslation } from 'react-i18next';
import useModel from 'flooks';
import { useMount } from '@umijs/hooks';

import IM from './model.ts';

export default function TimScreen({ navigation }: StackScreenProps) {
  const { t } = useTranslation();
  const webRef = React.useRef();
  const {
    getChat,
    userID,
    userSig,
    tim,
    setTim,
    initChat,
    updateChatInfo,
  } = useModel(IM, ['userID', 'userSig', 'tim']);
  useMount(() => {
    initChat();
  });

  React.useEffect(() => {
    if (userSig && tim)
      tim.injectJavaScript(
        `window.chatLogin(${JSON.stringify(userID)},${JSON.stringify(userSig)})`
      );
  }, [userSig, tim]);

  return (
    <WebView
      ref={webRef}
      source={{
        uri: `http://dingdong.izouma.com/map/tim`,
      }}
      onMessage={({ nativeEvent }) => {
        console.log(nativeEvent);
        const info =
          nativeEvent.data.indexOf('{') !== -1
            ? JSON.parse(nativeEvent.data)
            : {};
        console.log(info);
        console.log(info.name);
        console.log(info.conversationType);
        switch (info.name) {
          case 'onConversationListUpdated':
            getChat();
            break;

          default:
            break;
        }

        if (Array.isArray(info)) {
          updateChatInfo(info[0]);
        }
      }}
      onLoadEnd={() => {
        setTim(webRef.current);
      }}
    />
  );
}
