import React, { useCallback, useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { MainStack } from '@app/routes/MainStack.tsx';
import useUpdateRef from '@app/hooks/useUpdateRef.ts';
import { useAuth } from '@common/contexts/useAuth.ts';
import { useAccountInfo } from '@app/routes/api';
import { showErrorMessage } from '@common/ToastHelper.ts';
import { Image, StyleSheet, View } from 'react-native';
import { LoginStack } from '@app/routes/login/LoginStack.tsx';

export default function Container() {
  const {
    state: { loading: authLoading, token, userInfo },
    actions: { update },
  } = useAuth();
  const userInfoRef = useUpdateRef(userInfo);

  const { fetchAsync: accountInfoFetch } = useAccountInfo(); // 获取用户信息

  // 获取用户信息接口调用的处理
  const handleAccountInfoFetch = useCallback(() => {
    if (token === undefined) {
      return;
    }
    accountInfoFetch()
      .then(r => {
        if (userInfoRef.current) {
          update({
            ...userInfoRef.current,
            nickname: r.nickname,
            phone: r.phoneNum,
            moduleList: r.advertisementModuleList,
            realNameStatus: r.realNameStatus,
            picUrl: r.picUrl,
            userIdCardNum: r.userIdCardNum,
            faceDetectFirms: r.faceDetectFirms,
            enableCert: r.enableCert,
            gxLeader: r.gxLeader,
            hasBindFirm: r.hasBindFirm,
            hasFaceDetect: r.hasFaceDetect,
          });
        }
      })
      .catch(e => {
        showErrorMessage(e.message);
      });
  }, [accountInfoFetch, token, update, userInfoRef]);

  // 已经登录状态获取一次用户信息
  useEffect(() => {
    if (token === undefined) {
      return;
    }
    handleAccountInfoFetch();
  }, [handleAccountInfoFetch, token]);

  // 启动加载界面
  if (authLoading) {
    return (
      <View style={styles.loading}>
        <Image
          style={styles.icon}
          source={require('@common/assets/images/common_appicon.png')}
        />
      </View>
    );
  }

  return (
    <NavigationContainer>
      {token === undefined ? (
        <LoginStack />
      ) : userInfo?.currentUserType === 'guanxin' ? (
        <View>冠心</View>
      ) : (
        <MainStack />
      )}
    </NavigationContainer>
  );
}
const styles = StyleSheet.create({
  loading: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  icon: {
    width: 90,
    height: 90,
  },
});
