import * as React from "react";
import {RefreshControl, ScrollView, StyleProp, TextStyle, TouchableHighlight, View, ViewStyle} from "react-native";
import {countTools} from '@yoronsoft/js-utils';
import {IProps} from "./slide";
import {loggerConfig} from "../config";
import app from "../../app";

const BasicSlide: React.FC<IProps> = (props) => {
    //  是否是debug
    const isDebug = typeof props.isDebug === 'boolean' ? props.isDebug : false;
    //  logger
    const logger = loggerConfig('Slide', isDebug);

    const ref = React.useRef(null);
    const viewRef = React.useRef(null);

    //  滑动内容高度
    const slideContentHeight = React.useRef(0);
    //  滑动高度
    const slideHeight = React.useRef(0);
    //  是否滑动到底部
    const isSlideEnd = React.useRef(false);
    //  滑动安全时间
    const slideTimer = React.useRef(0);

    const [height, setHeight] = React.useState<number>(0);
    React.useEffect(() => {
        //  是否滚动到底部
        if (props.hasScrollToEnd) {
            const params = {animated: false, duration: 0};
            if (props.scrollToEndParams) {
                if (props.scrollToEndParams.animated) params.animated = props.scrollToEndParams.animated;
                if (props.scrollToEndParams.duration) params.duration = props.scrollToEndParams.duration;
            }
            isSlideEnd.current = true;
            ref.current.scrollToEnd(params);
        }
    }, [])

    React.useEffect(() => {
        if (ref.current && props.refName) {
            app.refs.set(props.refName, ref.current);
        }
    }, [ref.current]);

    //  垂直滚动条
    const hasBarVertical = typeof props.hasBarVertical === 'boolean' ? props.hasBarVertical : true;
    //  水平滚动条
    const hasBarHorizontal = typeof props.hasBarHorizontal === 'boolean' ? props.hasBarHorizontal : false;
    //  水平滚动
    const hasHorizontal = typeof props.hasHorizontal === 'boolean' ? props.hasHorizontal : false;
    //  是否显示下拉刷新loading
    const hasRefreshing = typeof props.hasRefreshing === 'boolean' ? props.hasRefreshing : false;

    //  操作样式
    const style: StyleProp<ViewStyle> = {};
    if (props.t) style.marginTop = props.t;
    if (props.b) style.marginBottom = props.b;
    if (props.l) style.marginLeft = props.l;
    if (props.r) style.marginRight = props.r;
    if (props.m) style.margin = props.m;
    if (props.mv) style.marginVertical = props.mv;
    if (props.mh) style.marginHorizontal = props.mh;
    if (props.mt) style.marginTop = props.mt;
    if (props.mb) style.marginBottom = props.mb;
    if (props.ml) style.marginLeft = props.ml;
    if (props.mr) style.marginRight = props.mr;
    if (!hasHorizontal) {
        style.flex = 1;
        style.height = height;
    }
    const styleInner: StyleProp<TextStyle> = {};
    if (props.p) styleInner.padding = props.p;
    if (props.pv) styleInner.paddingVertical = props.pv;
    if (props.ph) styleInner.paddingHorizontal = props.ph;
    if (props.pt) styleInner.paddingTop = props.pt;
    if (props.pb) styleInner.paddingBottom = props.pb;
    if (props.pl) styleInner.paddingLeft = props.pl;
    if (props.pr) styleInner.paddingRight = props.pr;

    logger.log('props', props);
    logger.log('style', style);
    logger.log('styleInner', styleInner);
    logger.log('height', height);

    return <View style={{flex: 1}} ref={viewRef} onLayout={event => {
        if (!hasHorizontal) setHeight(event.nativeEvent.layout.height)
    }}>
        <ScrollView
            style={[style]}
            ref={ref}
            onScroll={(event) => {
                //  总高度
                const totalHeight = event.nativeEvent.contentSize.height;
                //  scrollView 高度
                const scrollViewHeight = event.nativeEvent.layoutMeasurement.height;
                //  滚动距离
                const offsetY = event.nativeEvent.contentOffset.y;
                slideContentHeight.current = totalHeight;
                slideHeight.current = countTools.plus(scrollViewHeight, offsetY);
                if (typeof props.onScroll === "function") props.onScroll(event);
            }}
            contentOffset={props.contentOffset}
            //  双指缩放操作(IOS)
            pinchGestureEnabled={false}
            showsVerticalScrollIndicator={hasBarVertical}
            showsHorizontalScrollIndicator={hasBarHorizontal}
            horizontal={hasHorizontal}
            onTouchStart={() => {
                if (hasHorizontal && props.navigation) props.navigation.setOptions({gestureEnabled: false});
            }}
            onTouchEnd={() => {
                if (hasHorizontal && props.navigation) props.navigation.setOptions({gestureEnabled: true});
            }}
            onTouchMove={() => {
                if (hasHorizontal && props.navigation) props.navigation.setOptions({gestureEnabled: true});
            }}
            //  滚动动画结束调用函数
            onMomentumScrollEnd={(event) => {
                //  翻页
                const timer = new Date().getTime();
                if (slideTimer.current > timer) return;
                slideTimer.current = timer + 1000;
                if ((slideHeight.current + 1) >= slideContentHeight.current) {
                    if (typeof props.onPaging === "function") props.onPaging();
                }
            }}
            // //  当用户开始拖动此视图时调用此函数
            // onScrollBeginDrag={event => {
            // }}
            //  当用户停止拖动此视图时调用此函数
            onScrollEndDrag={() => {
                isSlideEnd.current = (slideHeight.current + 1) >= slideContentHeight.current
            }}
            //  内容发生变动时，调用此函数
            onContentSizeChange={(w, h) => {
                //  更新滑动内容高度
                slideContentHeight.current = h;
                //  自动底部对齐
                if (props.hasScrollToEnd && props.hasAutoScrollToEnd && isSlideEnd.current) {
                    //  更新滑动高度
                    slideHeight.current = h;
                    //  到最底部
                    ref.current.scrollToEnd();
                }
            }}
            //  刷新加载中
            refreshControl={
                typeof props.onRefresh === "function" ?
                    <RefreshControl refreshing={hasRefreshing} onRefresh={() => {
                        if (typeof props.onRefresh === "function") props.onRefresh();
                    }}/>
                    : undefined
            }
        >
            <TouchableHighlight activeOpacity={1} style={{flex: 1}}>
                <View style={[{flex: 1}, props.style, styleInner]}>
                    {props.children}
                </View>
            </TouchableHighlight>
        </ScrollView>
    </View>
}

export default BasicSlide
