/**
 * 首页抽屉菜单
 * @邠心vbe on 2021/03/23
 */
import React, { Component } from 'react';
import {View, Text, StyleSheet, Image} from 'react-native';
import { createDrawerNavigator, DrawerContentScrollView } from '@react-navigation/drawer';
import app from '../../../app.json';
import Maps from './Home';
import Dialog from '../../components/Dialog';
import { setAccessToken } from '../../api/http';
import { getStorageJsonSync, setStorage, setStorageJson } from '../../utils/storage';
import { AutoLogin } from '../sign/Login';
import utils from '../../utils/utils';
import apiNotification from '../../api/apiNotification';
import DrawerView from './Drawer.js';
import DrawerViewV2 from './DrawerV2.js';

const Drawer = createDrawerNavigator();

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLogin: false,
      userInfo: {},
      notificationCount: 0,
      sideCountInfo: {}
    }
  }

  componentDidMount() {
    AutoLogin(() => {
      this.setState({
        userInfo: userInfo
      });
    });
    this.props.navigation.addListener('focus', () => {
      //console.log('drawer focus');
      getUserInfo(info => {
        this.setState({
          userInfo: info
        });
      }, true);
      if (app.notifications.enable && this.state.isLogin) {
        this.getNotificationTotal();
      }
    });
    /*BackHandler.addEventListener('hardwareBackPress', (e) => {
      if (global.dialogId !== 0) {
        Dialog.dismissLoading();
        return true;
      }
      return false;
    })*/
  }

  componentDidUpdate() {
    const status = isLogin();
    if (this.state.isLogin != status) {
      this.setState({
        isLogin: status
      }, () => {
        getUserInfo(info => {
          this.setState({
            userInfo: info
          });
          if (info.firebaseToken) {
            let token = isIOS ? info.firebaseToken?.ios : info.firebaseToken?.android
            if (notifyToken.token) {
              utils.registerFirebaseToken(token ?? "");
            }
          }
        }, true);
        if (app.notifications.enable && status) {
          this.getNotificationTotal();
        }
      });
    }
  }

  async requestLogout() {
    const data = await getStorageJsonSync('loginData');
    if (data && data.email) {
      delete data.password
      setStorageJson('loginData', data);
      setStorage('RegisterTokenDate', "");
    }
    global.userInfo = {}
    this.setState({
      isLogin: false,
      userInfo: {}
    });
    setAccessToken('');
    Dialog.dismissLoading();
  }

  getNotificationTotal() {
    apiNotification.getUnreadTotal().then(res => {
      if (res.data) {
        this.setState({
          sideCountInfo: res.data,
          notificationCount: res.data?.toBeReadCount ?? 0
        })
      } else {
        this.setState({
          sideCountInfo: {},
          notificationCount: 0
        })
      }
    }).catch(err => {
      this.setState({
        sideCountInfo: {},
        notificationCount: 0
      })
    })
  }

  render () {
    return (
      <Drawer.Navigator
        initialRouteName='maps'
        drawerContent={props => 
          <CustomerDrawerContent 
            {...props}
            isLogin={this.state.isLogin}
            userInfo={this.state.userInfo}
            onLogout={() => this.requestLogout()}
            sideCountInfo={this.state.sideCountInfo}
            notificationCount={this.state.notificationCount}
          />
        }
        screenOptions={{
          headerShown: false,
          drawerType: global.$width >= 768 ? 'back' : 'front',
          drawerStyle: {
            width: app.v3.drawer ? $vw(100) : ($vw(75) > 320 ? 320 : $vw(75)),
            backgroundColor: app.v3.drawer ? 'rgba(0,0,0,0.1)' : colorLight
          },
          swipeEnabled: !app.v3.drawer, //启用侧滑打开抽屉
        }}>
        <Drawer.Screen name="maps" component={Maps} />
      </Drawer.Navigator>
    );
  }
};

const CustomerDrawerContent = (props) => {
  return (
    <DrawerContentScrollView 
      {...props}
      canCancelContentTouches={true}
      style={app.v3.drawer ? styles.contentV2 : {}}>
      { app.v3.drawer
      ? <DrawerViewV2 {...props}/>
      : <DrawerView {...props}/>
      }
    </DrawerContentScrollView>
  );
}

const styles = StyleSheet.create({
  contentV2: {
    width: $vw(75) > 320 ? 320 : $vw(75),
    backgroundColor: colorLight
  }
})