import React from 'react';
import { $http } from 'containers/config/https';
import ErrorView from './Index';

class ErrorBoundary extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			hasError: false,
			error: null,
			errorInfo: null
		};
	}

	componentDidCatch(error, errorInfo) {
		// Display fallback UI
		this.setState({ 
			hasError: true,
			error,
			errorInfo
		}, () => {
			this.handleSaveErrorLog();
		});
		// You can also log the error to an error reporting service
		// logErrorToMyService(error, info);
	}

	// 保存错误日志
	handleSaveErrorLog = () => {
		let {error, errorInfo} = this.state;
		console.log(error, errorInfo)
		let data = {
			params: [{
				errorInfo: errorInfo && errorInfo.componentStack ? errorInfo.componentStack : errorInfo,
				errorMessage: error && error.toString ? error.toString() : ""
			}]
		}
		$http.post('urlS', this, {
			code: "06050019",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					console.log(res)
				}
			}
		})
	}

	render() {
		if (this.state.hasError) {
			// You can render any custom fallback UI
			return <ErrorView />;
		}
		return this.props.children;
	}
}

export default ErrorBoundary;