/**
 * 首页抽屉菜单
 * @邠心vbe on 2021/03/23
 */
import React, { Component } from 'react';
import {View, Text, StyleSheet, Image, Pressable, BackHandler, Linking, Touchable} from 'react-native';
import { createDrawerNavigator, DrawerContentScrollView } from '@react-navigation/drawer';
import { Styles } from '../../components/Toolbar';
import app from '../../../app.json';
import Maps from './Home';
import { PageList } from '../Router';
import Dialog from '../../components/Dialog';
import { host, setAccessToken } from '../../api/http';
import { getStorageJsonSync, setStorage, setStorageJson } from '../../utils/storage';
import Button from '../../components/Button';
import { AutoLogin } from '../sign/Login';
import apiCharge from '../../api/apiCharge';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { toTopupPage } from '../payment/PaymentConfig';
import utils from '../../utils/utils';

const Drawer = createDrawerNavigator();

const DEBUG = app.debug && !app.product;

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

  componentDidMount() {
    AutoLogin(() => {
      this.setState({
        userInfo: userInfo
      });
    });
    this.props.navigation.addListener('focus', () => {
      //console.log('drawer focus');
      getUserInfo(info => {
        this.setState({
          userInfo: info
        });
      }, true);
    });
    /*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);
      });
    }
  }

  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();
  }

  render () {
    return (
      <Drawer.Navigator
        initialRouteName='maps'
        drawerContent={props => 
          <CustomerDrawerContent 
            {...props}
            isLogin={this.state.isLogin}
            userInfo={this.state.userInfo}
            onLogout={() => this.requestLogout()}
          />
        }
        drawerType={
          global.$width >= 768 ? 'back' : 'front'
        }
        drawerStyle={{
          width: $vw(75) > 320 ? 320 : $vw(75),
          backgroundColor: colorLight
        }}>
        <Drawer.Screen name="maps" component={Maps} />
      </Drawer.Navigator>
    );
  }
};

const CustomerDrawerContent = (props) => {
  return (
    <DrawerContentScrollView 
      {...props}
      canCancelContentTouches={true}>
      <DrawerContent {...props}/>
    </DrawerContentScrollView>
  );
}

const DrawerContent = ({isLogin, userInfo, onLogout, navigation}) => {
  const getCharging = () => {
    Dialog.showProgressDialog();
    apiCharge.getUserCharging().then(res => {
      Dialog.dismissLoading();
      if (res.data.sitePk) {
        startPage(PageList.chargeDetailPage, {stationInfo: {id: res.data.sitePk}, action: 'view', from: PageList.home});
        //startPage(PageList.chargeDetail, { stationInfo: {id: res.data.sitePk}, action: 'view'});
      } else if (res.msg) {
        toastShort(res.msg);
      } else {
        toastShort($t("drawer.noChargingSession"));
      }
    }).catch((err) => {
      if (app.debug)
        console.log(err);
      Dialog.dismissLoading();
      toastShort($t("drawer.noChargingSession"));
    })
  }

  const logout = () => {
    Dialog.showDialog({
      title: 'Sign out',
      message: 'Are you sure you want to sign out?',
      callback: btn => {
        if (btn == 'ok') {
          Dialog.showProgressDialog();
          setTimeout(() => {
            onLogout();
          }, 500);
        }
      }
    })
  }

  return (
    <View style={styles.drawerView}>
      <View style={styles.loginView}>
        { (isLogin && userInfo.photoUrl)
        ? <TouchableWithoutFeedback onPress={() => startPage(PageList.profile)}>
            <Image
              style={styles.avatar}
              source={{uri: host + userInfo.photoUrl}}/>
          </TouchableWithoutFeedback>
        : <TouchableWithoutFeedback onPress={() => startPage(PageList.login)}>
            <Image
              style={styles.avatar}
              source={require('../../images/user/ic-avatar-default.png')}/>
          </TouchableWithoutFeedback>
        }
        <Pressable
          style={styles.nickView}
          android_ripple={ripple}
          onPress={() => startPage(isLogin ? PageList.profile : PageList.login)}>
          <Text
            style={styles.nickname}
            ellipsizeMode='tail'
            numberOfLines={1}>
            { isLogin
              ? userInfo.nickName 
                ? userInfo.nickName
                : $t('drawer.logging')
              : $t('drawer.sign')
            }
          </Text>
          <FontAwesome
            size={24}
            color='#999'
            name='angle-right'/>
        </Pressable>
      </View> 
      <View style={styles.divideLogin}></View>
      {/* isLogin
        ? <Button
            style={styles.itemButton}
            viewStyle={styles.itemView}
            onClick={() => {
              startPage(PageList.profile)
            }}>
            <Image
              style={styles.icon}
              source={require('../../images/icon/draw-user.png')}/>
            <Text style={styles.label}>Profile Settings</Text>
          </Button>
        : <Button
            style={styles.itemButton}
            viewStyle={styles.itemView}
            onClick={() => {
              startPage(PageList.login); 
            }}>
            <Image
              style={styles.icon}
              source={require('../../images/icon/draw-user.png')}/>
            <Text style={styles.label}>Sign In</Text>
          </Button>
      */}

      {/* <Button
        style={styles.itemButton}
        viewStyle={styles.itemView}
        onClick={() => {
          navigation.toggleDrawer();
        }}>
        <Image
          style={styles.icon}
          source={require('../../images/icon/draw-home.png')}/>
        <Text style={styles.label}>Home</Text>
      </Button> */}

      { isLogin
        ? <Button
            style={styles.itemButton}
            viewStyle={styles.itemView}
            onClick={() => getCharging()}>
            <MaterialCommunityIcons
              style={styles.icon}
              name="car-electric-outline"
              color="#333"
              size={26}
            />
            {/* <Image
              style={styles.icon}
              source={require('../../images/icon/draw-charge.png')}/> */}
            <Text style={styles.label}>{$t('drawer.charging')}</Text>
          </Button>
        : <View
            style={styles.disableItem}>
            <MaterialCommunityIcons
              style={styles.icon}
              name="car-electric-outline"
              color="#999"
              size={26}
            />
            {/* <Image
              style={styles.icon}
              source={require('../../images/icon/draw-charge-no.png')}/> */}
            <Text style={styles.disable}>{$t('drawer.charging')}</Text>
          </View>
      }
      {/* isLogin
        ? <Button
            style={styles.itemButton}
            viewStyle={styles.itemView}
            onClick={() => {
              startPage(PageList.wallet);
            }}>
            <Image
              style={styles.icon}
              source={require('../../images/icon/draw-transaction.png')}/>
            <Text style={styles.label}>{$t('drawer.wallet')}</Text>
          </Button>
        : <View
            style={styles.disableItem}>
            <Image
              style={styles.icon}
              source={require('../../images/icon/draw-transaction-no.png')}/>
            <Text style={styles.disable}>{$t('drawer.wallet')}</Text>
          </View>
      */}
      {
        isLogin && <>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.wallet);
          }}>
          <Image
            style={styles.icon}
            source={require('../../images/icon/draw-transaction.png')}/>
          <Text style={styles.label}>{$t('drawer.wallet')}</Text>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => toTopupPage()}>
          <MaterialCommunityIcons
            style={styles.icon}
            size={26}
            name={"wallet-outline"}
            color={colorDark}/>
          <Text style={styles.label}>{$t('drawer.topup')}</Text>
          <Text style={styles.balanceText2}>{currency}{userInfo.credit}</Text>
        </Button></>
      }

      {/*附加功能-开始*/}
      { (app.modules.notifications && isLogin) &&
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.bookmarks);
          }}>
          <MaterialIcons
            style={styles.icon}
            name="stars"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('route.bookmarks')}</Text>
        </Button>
      }
      { (app.modules.bookmarks && isLogin) &&
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.bookmarks);
          }}>
          <MaterialIcons
            style={styles.icon}
            name="stars"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('route.bookmarks')}</Text>
        </Button>
      }
      {/*附加功能-结束*/}
      { isLogin &&
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.membersList);
          }}>
          <MaterialIcons
            style={styles.icon}
            name="card-membership"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('drawer.members')}</Text>
        </Button>
      }
      <Button
        style={styles.itemButton}
        viewStyle={styles.itemView}
        onClick={() => {
          startPage(PageList.feedback);
        }}>
        <MaterialCommunityIcons
          style={styles.icon2}
          name="message-alert-outline"
          color="#222"
          size={24}/>
        <Text style={styles.label}>{$t('drawer.feedback')}</Text>
      </Button>

      {/* <Button
        style={styles.itemButton}
        viewStyle={styles.itemView}
        onClick={() => {
          Linking.openURL(host+"juicePicture/pdf/FAQ.v1.0.pdf")
        }}>
        <Feather
          style={styles.icon2}
          name="download"
          color={colorDark}
          size={24}
        />
        <Text style={styles.label}>FAQs</Text>
      </Button> */}
      <Button
        style={styles.itemButton}
        viewStyle={styles.itemView}
        onClick={() => {
          startPage(PageList.settings);
        }}>
        <Ionicons
          style={styles.icon}
          name="md-settings-outline"
          color="#222"
          size={25}
        />
        <Text style={styles.label}>{$t('drawer.settings')}</Text>
      </Button>
      { app.modules.support &&
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.supportContact);
          }}>
          <MaterialCommunityIcons
            style={styles.icon}
            name="face-agent"
            color="#333"
            size={26}
          />
          <Text style={styles.label}>{$t('drawer.contactSupport')}</Text>
        </Button>
      }
      <Button
        style={styles.itemButton}
        viewStyle={styles.itemView}
        onClick={() => {
          startPage(PageList.about);
        }}>
        <MaterialCommunityIcons
          style={styles.icon}
          name="information-outline"
          color="#333"
          size={26}
        />
        <Text style={styles.label}>{$t('drawer.about')}</Text>
      </Button>

      {/* <View style={styles.divided}></View> */}
      { DEBUG &&
      <>
        <View style={styles.divideLogin}></View>
        <Text style={{color: "#ccc", paddingLeft: 16, paddingBottom: 8, fontSize: 12}}>{$t('drawer.debugOnly')}</Text>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.privacy);
          }}>
          <MaterialCommunityIcons
            style={styles.icon}
            name="file-eye-outline"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('drawer.privacyPolicy')}</Text>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.condition);
          }}>
          <MaterialCommunityIcons
            style={styles.icon}
            name="file-eye-outline"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('drawer.termsOfUse')}</Text>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(PageList.notify);
          }}>
          {/* <Image
            style={styles.icon2}
            source={require('../../images/icon/draw-terms.png')}/> */}
          <MaterialIcons
            style={styles.icon}
            name="notifications-none"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('route.notificationTest')}</Text>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => {
            startPage(isIOS ? PageList.notify : PageList.mapTest);
          }}>
          <MaterialCommunityIcons
            style={styles.icon}
            name="map-legend"
            color="#222"
            size={26}/>
          <Text style={styles.label}>{$t('drawer.mapsTest')}</Text>
        </Button>
      </>}

      {/* isLogin
        ? <View style={styles.walletView}>
            <Pressable
              style={styles.balanceView}
              android_ripple={ripple}
              onPress={() => toTopupPage()}>
              <Image
                style={styles.icon}
                source={require('../../images/icon/draw-wallet.png')}/>
              <Text style={styles.balanceText}>{currency}{userInfo.credit}</Text>
            </Pressable>
            {/* <Pressable
              style={styles.balanceView}
              android_ripple={ripple}
              onPress={() => {
                startPage(PageList.referral);
              }}>
              <Image
                style={styles.icon}
                source={require('../../images/icon/draw-gift.png')}/>
              <Text style={styles.referText}>Refer your friends to get $5 credit!</Text>
            </Pressable> *}
          </View>
        : <View style={ui.flex1}></View>s
        */}

      <View style={styles.bottomView}>
        <Image
          style={Styles.logo}
          resizeMode='contain'
          source={require('../../images/app-logo.png')}
        />
        <Text style={styles.versionText}>{app.displayName + '  ' + app.versionName}</Text>
      </View>
      {/* isLogin &&
        <Button
          style={styles.logoutView}
          text='Logout'
          textColor={textButton}
          borderRadius={0}
          onClick={() => logout()}/>
      */}
    </View>
  );
}

const styles = StyleSheet.create({
  drawerTop: {
    top: 0,
    left: 0,
    right: 0,
    height: statusHeight,
    position: 'absolute',
    fontSize: 10,
    backgroundColor: pageBackground
  },
  drawerView: {
    paddingTop: 16,
    paddingBottom: 8,
    minHeight: $vhs(101)
  },
  guessView: {
    padding: 16
  },
  loginView: {
    paddingTop: 16,
    paddingBottom: 8
  },
  avatar: {
    width: 66,
    height: 66,
    marginLeft: 24,
    borderWidth: 2,
    borderRadius: 80,
    borderColor: colorLight,
  },
  nickView: {
    marginTop: 4,
    flexDirection: 'row',
    ...$padding(12, 16)
  },
  nickname: {
    flex: 1,
    color: textPrimary,
    fontSize: 20,
    fontWeight: 'bold',
    paddingLeft: 16,
  },
  divideLogin: {
    height: 1,
    marginTop: 4,
    marginRight: 32,
    marginBottom: 12,
    backgroundColor: '#E5E5E5'
  },
  itemButton: {
    borderRadius: 0,
    backgroundColor: colorLight
  },
  itemView: {
    flex: 1,
    height: 56,
    paddingLeft: 16,
    marginBottom: 6,
    alignItems: 'center',
    flexDirection: 'row'
  },
  disableItem: {
    height: 56,
    paddingLeft: 16,
    marginBottom: 6,
    alignItems: 'center',
    flexDirection: 'row'
  },
  icon: {
    width: 26,
    height: 26,
    marginRight: 16
  },
  icon2: {
    width: 24,
    height: 24,
    marginLeft: 1,
    marginRight: 17
  },
  label: {
    flex: 1,
    color: textPrimary,
    fontSize: 16.5
  },
  disable: {
    color: '#999',
    fontSize: 18
  },
  divided: {
    height: 1,
    marginTop: 24,
    marginLeft: 16,
    backgroundColor: colorAccent
  },
  walletView: {
    paddingTop: 16,
    paddingLeft: 48,
    paddingRight: 48
  },
  balanceView: {
    marginTop: 16,
    borderRadius: 8,
    ...$padding(13, 22),
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: 'rgba(0, 20, 137, 0.2)'
  },
  balanceText: {
    color: textPrimary,
    fontSize: 22,
    fontWeight: 'bold'
  },
  referText: {
    flex: 1,
    color: textPrimary,
    fontSize: 13
  },
  bottomView: {
    flex: 1,
    paddingTop: 48,
    paddingBottom: 0,
    alignItems: 'center',
    justifyContent: 'flex-end'
  },
  versionText: {
    color: textPrimary,
    fontSize: 10,
    paddingTop: 16
  },
  logoutView: {
    backgroundColor: colorPrimary
  },
  balanceText2: {
    color: textCancel,
    fontSize: 14,
    marginRight: 32
  }
});
