/**
 * Route Util
 * @邠心vbe on 2023/02/13
 */
import { CommonActions } from '@react-navigation/routers';
import React, { Component } from 'react';
import { View } from 'react-native';
import { PagerList } from '../pages/chargeV2/ChargeAdapter';
import { PageList } from '../pages/Router';

const routeUtil = {
  /**
   * 重置路由并导航到首页
   * @param {Object} props 页面道具
   */
  resetToHome: (props) => {
    if (props.navigation) {
      props.navigation.reset({
        index: 0,
        routes: [{
          name: PageList.home
        }]
      });
    }
  },
  /**
   * 重置路由并导航到指定路由
   * @param {Object} props 页面道具
   * @param {Array} routes 指定路由
   */
  resetHome2Page: (props, routes=[]) => {
    if (props.navigation) {
      props.navigation.reset({
        index: routes.length,
        routes: [
          {
            name: PageList.home,
          },
          ...routes
        ]
      })
    }
  },
  /**
   * 跳转到新页面并清除当前页面
   * @param {Object} props 页面道具
   * @param {Object} route 需要导航的路由
   */
  redirectTo: (props, route) => {
    if (props.navigation) {
      props.navigation.dispatch(state => {
        var routes = []
        routes = JSON.parse(JSON.stringify(state.routes))
        routes.pop();
        routes.push(route);
        return CommonActions.reset({
          index: routes.length - 1,
          routes: routes
        })
      });
    }
  },
  /**
   * 导航到中转页面
   * @param {String} route 需要导航的路由名称
   */
  bridge2Page: (route) => {
    startPage(PageList.bridge, {route: route})
  },
  /**
   * 导航到中转页面
   * @param {Array} routes 需要导航的路由
   */
  bridge2Pages: (routes=[]) => {
    startPage(PageList.bridge, {routes: routes})
  }
}

export default routeUtil;

export class BridgePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      params: ""
    };
  }

  componentDidMount() {
    const routes = this.props.route?.params?.routes
    const route = this.props.route?.params?.route
    if (route) {
      startPage(route);
    } else if (routes) {
      console.log('bridge', routes);
      setTimeout(() => {
        routeUtil.resetHome2Page(this.props, routes)
      }, 500);
    }
    this.props.navigation.addListener('focus', e => {
      console.log('bridge.focus', this.props.route?.params)
      if (this.state.params) {
        routeUtil.resetToHome(this.props)
      } else {
        this.setState({
          params: true
        })
      }
    });
  }

  render() {
    return (
      <View style={ui.flex1}>
      </View>
    );
  }
}