import React, { Component } from 'react'
import { View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, TouchableHighlight, Keyboard } from 'react-native';
import BottomSheet from 'reanimated-bottom-sheet'
import Animated, { exp } from 'react-native-reanimated';
import { px2dp, height, size, onePx, colors, toast, isIos, isEmpty } from '../../utils/base'
import { layout } from '../../utils/com';
import RNDatePicker from 'react-native-date-picker';
//@ts-ignore
import { Picker } from 'react-native-wheel-pick';

interface State {
    date: any
    yearMap: Array<string>
    monthMap: Array<string>
};

interface Props {
    onDateChange?: Function
    date?: any
    mode?: 'time' | 'datetime' | 'date' | 'YY' | 'MM' | 'YY-MM'
    title?: string
};

export default class JDatePicker extends Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.renderInner = this.renderInner.bind(this)
    };

    public readonly state: Readonly<State> = {
        date: new Date(),
        yearMap: this.getYear(),
        monthMap: this.getMonth(),
    }
    public tempDate = this.props.date;
    public tempYear = new Date().getFullYear().toString();
    public tempMonth = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1).toString() : (new Date().getMonth() + 1).toString();
    public sheetContainerRef = null;
    public sheetRef = null;
    public fall = new Animated.Value(1);
    public delayHideTimer = null;

    componentWillUnmount() {
        this.delayHideTimer && clearTimeout(this.delayHideTimer)
    };

    public getYear() {
        return ['2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030']
    };

    public getMonth() {
        return ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    };

    public show = () => {    //打开下拉框
        Keyboard.dismiss();
        this.delayHideTimer && clearTimeout(this.delayHideTimer);
        this.sheetContainerRef.setNativeProps({
            style: {
                display: 'flex',
                zIndex: 999
            }
        });
        this.sheetRef.snapTo(1);
        this.sheetRef.snapTo(1);
    };

    public _onDateChange = (e) => {
        console.log(e);
        this.tempDate = e;
    };

    public onYearChange = (e) => {
        console.log(e);
        this.tempYear = e;
    };

    public onMonthChange = (e) => {
        this.tempMonth = e;
    };

    public onDone() {
        const { mode, onDateChange } = this.props;
        if (mode === 'YY-MM') {
            if (isEmpty(this.tempYear) || isEmpty(this.tempMonth)) {
                return toast("请选择日期");
            };
            onDateChange && onDateChange({ year: this.tempYear, month: this.tempMonth });
            this.handleHide();
        } else {
            if (isEmpty(this.tempDate)) {
                return toast("请选择日期");
            };
            if (this.tempDate === this.props.date) {
                this.handleHide();
                return false;
            }
            onDateChange && onDateChange(this.tempDate);
            this.handleHide();
        };
    };

    renderInner() {
        const { mode = 'date', title = '日期选择' } = this.props;
        const { date, yearMap, monthMap } = this.state;
        return (
            <View style={{ width: '100%', height: px2dp(320), backgroundColor: '#fff' }}>
                <View style={styles.headerRow}>
                    <TouchableOpacity onPress={this.handleHide.bind(this)} style={styles.headerCancelBtn}>
                        <Text>取消</Text>
                    </TouchableOpacity>
                    <Text style={layout.headerTitle}>{title}</Text>
                    <TouchableOpacity onPress={this.onDone.bind(this)} style={styles.headerBtn}>
                        <Text style={{ color: '#fff' }}>确定</Text>
                    </TouchableOpacity>
                </View>
                {
                    mode === 'MM' || mode === 'YY-MM' ?
                        <View style={styles.datePickerContainer}>
                            {
                                isIos() ?
                                    null
                                    :
                                    <>
                                        <View style={styles.topCheckedLine}></View>
                                        <View style={styles.bottomCheckedLine}></View>
                                    </>
                            }
                            <Picker
                                style={styles.pickerLine}
                                selectedValue={this.tempYear}
                                pickerData={yearMap}
                                onValueChange={this.onYearChange.bind(this)}
                                itemSpace={30} // this only support in android
                            />
                            <Picker
                                style={styles.pickerLine}
                                selectedValue={this.tempMonth}
                                pickerData={monthMap}
                                onValueChange={this.onMonthChange.bind(this)}
                                itemSpace={30} // this only support in android
                            />
                        </View>
                        :
                        <View style={styles.datePickerContainer}>
                            <RNDatePicker
                                date={date}
                                onDateChange={this._onDateChange.bind(this)}
                                //@ts-ignore
                                mode={mode}
                                style={styles.datePcikerContent}
                            />
                        </View>
                }
            </View>
        )
    };

    public _onCloseEnd = () => {
        this.sheetContainerRef.setNativeProps({
            style: {
                display: 'none',
                zIndex: -1
            }
        });
    };

    public handleHide = () => {
        this.sheetRef.snapTo(0);
        this.sheetRef.snapTo(0);
        this.delayHideTimer = setTimeout(() => {
            this._onCloseEnd();
        }, 250)
    };

    render() {
        return (
            <View
                ref={(c) => this.sheetContainerRef = c}
                style={styles.sheetContainer}>
                <Animated.View style={[styles.overlay, {
                    opacity: Animated.sub(0.6, Animated.multiply(this.fall, 0.6)),
                }]}>
                    <TouchableOpacity onPress={() => this.handleHide()} style={styles.touchOverlayContent}></TouchableOpacity>
                </Animated.View>
                <BottomSheet
                    snapPoints={[0, px2dp(320)]}  // 高度
                    renderContent={this.renderInner}  // 内容
                    initialSnap={0}
                    enabledGestureInteraction={true} // 是否可以手势滑动 
                    enabledContentGestureInteraction={true} //内容区域是否可以滚动
                    callbackNode={this.fall}
                    ref={c => { this.sheetRef = c }}
                    borderRadius={px2dp(12)}
                    onCloseEnd={() => this._onCloseEnd()}
                />
            </View>
        )
    }
};

const styles = StyleSheet.create({
    sheetContainer: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        height: '100%',
        width: '100%',
        display: 'none',
        zIndex: -1,
        overflow: 'hidden'
    },

    overlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0,0,0,0.7)',
    },

    touchOverlayContent: {
        width: '100%',
        height: '100%',
    },

    headerTouchArea: {
        height: px2dp(52),
        paddingHorizontal: px2dp(12),
        alignItems: 'center',
        justifyContent: 'center',
    },

    headerRow: {
        width: '100%',
        flexDirection: 'row',
        height: px2dp(52),
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: px2dp(12),
        borderBottomColor: '#eee',
        borderBottomWidth: onePx
    },

    headerCancelBtn: {
        width: px2dp(64),
        height: px2dp(28),
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(4),
        // borderColor: '#eee',
        // borderWidth: onePx
    },

    headerBtn: {
        width: px2dp(64),
        height: px2dp(28),
        backgroundColor: colors.themeColor,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(4),
    },

    datePickerContainer: {
        position: 'relative',
        width: '100%',
        height: px2dp(280),
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'flex-start',
    },

    datePcikerContent: {
        width: px2dp(350),
        height: px2dp(280),
        // backgroundColor: 'red'
    },

    pickerLine: {
        width: px2dp(120),
        flex: 1,
        backgroundColor: '#fff',
        // borderStartColor: 'red'
    },

    topCheckedLine: {
        position: 'absolute',
        left: 0,
        top: px2dp(86),
        width: px2dp(375),
        height: 1,
        zIndex: 999,
        borderBottomColor: '#e9e9e9',
        borderBottomWidth: onePx
    },

    bottomCheckedLine: {
        position: 'absolute',
        left: 0,
        top: px2dp(128),
        width: px2dp(375),
        height: 1,
        zIndex: 999,
        borderBottomColor: '#e9e9e9',
        borderBottomWidth: onePx
    }
});

