
import React, { Component } from 'react'
import { View, Text, StyleSheet, TouchableOpacity, Image, FlatList, TouchableHighlight, ActivityIndicator } from 'react-native';
import BottomSheet from 'reanimated-bottom-sheet'
import Animated from 'react-native-reanimated'
import { px2dp, size, statusBarHeight, colors, onePx, toast, height, isEmpty } from './../../utils/base';
// import redux from './../../../redux/store';
import HttpUtils from '../../utils/http';
// import { addressQuery } from '..utils/api';
import { comErrorMsg } from '../../utils/com';

const _province = require('../../addressData/province.json')
const _city = require('../../addressData/city.json')
const _county = require('../../addressData/county.json')
const _town = require('../../addressData/town.json')

interface Props {
    isInTab?: boolean,
    dataReturn: Function
}
interface State {
    city: Array<any>,
    county: Array<any>,
    cityLoading: boolean,
    coutyLoading: boolean,
    checkedProvince: string,
    checkedCity: string,
    defultCityDataList: Array<any>,
    loading: boolean,
    province: Array<any>,
    _height: number,
    checkedCounty: string
}
export default class AddressPicker extends Component<Props> {
    constructor(props: Props) {
        super(props);


    }

    componentDidMount() {
        // HttpUtils.getRequest(addressQuery, {}, true)
        //     .then(res => {
        //         //console.log(res)
        //         // if(res.)
        //     })
        //     .catch(err => {
        //         //console.log(err)
        //     })
        // this.getProvince()
    };

    public readonly state: Readonly<State> = {
        city: _city,
        county: _county,
        cityLoading: false,
        coutyLoading: false,
        checkedProvince: '',
        checkedCity: '',
        defultCityDataList: [],
        loading: false,
        _height: height - px2dp(200),
        province: _province,
        checkedCounty: ""
    }

    componentWillUnmount() {
        this.delayShow && clearTimeout(this.delayShow);
        this.delayInitCheck && clearTimeout(this.delayInitCheck);
    }

    public delayShow = null;
    public delayInitCheck = null;
    sheetContainer: any = null;

    sheet: any = null;

    fall: any = new Animated.Value(1);

    public show = (): void => {
        this.showSheet();
    };

    showSheet = () => {
        let { checkedProvince, checkedCity, city, county, province } = this.state;
        city = JSON.parse(JSON.stringify(_city))
        county = JSON.parse(JSON.stringify(_county))
        province = JSON.parse(JSON.stringify(_province))
        this.setState({
            city, province, county
        })
        this.sheetContainer.setNativeProps({
            style: {
                display: 'flex',
                zIndex: 999
            }
        });
        this.delayShow = setTimeout(() => {
            this.setState({ isOpen: true });
            this.sheet.snapTo(1);
            this.sheet.snapTo(1);
        }, 100);
        city = _city && JSON.parse(JSON.stringify(_city))
        county = _county && JSON.parse(JSON.stringify(_county))
        province = _province && JSON.parse(JSON.stringify(_province))
        this.setState({
            city, county, province
        })
    }

    public hide = (): void => {
        try {
            this.sheetContainer.setNativeProps({
                style: {
                    display: 'none',
                    zIndex: -1
                }
            })
        } catch (e) {
            //console.log(e)
        }
    };

    _onCloseEnd = () => {
        this.hide()
        this.handleHide()
    };

    handleHide = (): void => {
        let { checkedProvince, checkedCity, city, county, province } = this.state;
        city = JSON.parse(JSON.stringify(_city))
        county = JSON.parse(JSON.stringify(_county))
        province = JSON.parse(JSON.stringify(_province))
        this.setState({
            city, province, county
        })
        this.sheet.snapTo(0);
        this.sheet.snapTo(0);
    };

    getProvince = (item, index) => {
        let { province, city, county, checkedProvince } = this.state;
        province = JSON.parse(JSON.stringify(_province))
        province.forEach(item => {
            item.active = false
        });
        province[index].active = true;
        checkedProvince = province[index].name
        city = JSON.parse(JSON.stringify(_city[`${item.id}`]))
        this.setState({ province, city, county, checkedProvince })
    };

    getCity(item, index) {
        if (isEmpty(index)) {
            return
        }
        let { province, city, county, checkedCity } = this.state;
        city.forEach(item => {
            item.active = false
        });
        city[index].active = true;
        checkedCity = city[index].name
        county = JSON.parse(JSON.stringify(_county[`${item.id}`]))
        this.setState({ county, city, checkedCity })
    };

    getAddress(item, index) {
        if (isEmpty(index)) {
            return
        }
        let { dataReturn } = this.props;
        let { checkedProvince, checkedCity, city, county, province, checkedCounty } = this.state;
        let data = {
            province: checkedProvince,
            city: checkedCity,
            county: item.name
        };
        county.forEach(item => {
            item.active = false
        });
        county[index].active = true;
        checkedCounty = county[index].name
        console.log("data", data)

        // this.props.getAddressData && this.props.getAddressData(data);
        dataReturn && dataReturn(data)
        this.handleHide();
    };

    render_province = ({ item, index }) => {
        if (item.active) {
            return (
                <View style={styles.item}>
                    <Text style={{ color: colors.themeColor, fontSize: 15 }}>{item.name}</Text>
                </View>
            )
        }
        return (
            <TouchableHighlight onPress={() => this.getProvince(item, index)} underlayColor={'#f2f2f2'} style={styles.item}>
                <Text style={{ fontSize: 15 }}>{item.name}</Text>
            </TouchableHighlight>
        )
    };

    render_city = ({ item, index }) => {
        if (item.active) {
            return (
                <View style={styles.item}>
                    <Text style={{ color: colors.themeColor }}>{item.name}市</Text>
                </View>
            )
        }
        return (
            <TouchableHighlight onPress={() => this.getCity(item, index)} underlayColor={'#f2f2f2'} style={styles.item}>
                <Text>{item.name}</Text>
            </TouchableHighlight>
        );
    };

    render_couty = ({ item, index }) => {
        if (item.active) {
            return (
                <View style={styles.item}>
                    <Text style={{ color: colors.themeColor }}>{item.name}</Text>
                </View>
            )
        }
        return (
            <TouchableHighlight onPress={() => this.getAddress(item, index)} underlayColor={'#f2f2f2'} style={styles.item}>
                <Text>{item.name}</Text>
            </TouchableHighlight>
        );
    };

    render_city_empty() {
        if (!this.state.cityLoading) {
            return null
        };
        return (
            <View style={styles.item}>
                <ActivityIndicator size={'small'} color={colors.themeColor} />
            </View>
        )
    };

    render_couty_empty() {
        if (!this.state.coutyLoading) {
            return null
        };
        return (
            <View style={styles.item}>
                <ActivityIndicator size={'small'} color={colors.themeColor} />
            </View>
        )
    }

    renderInner = () => {
        const { _height, loading, province, city, county } = this.state;
        const sheetHeight = _height * 0.8;

        return (
            <View style={[styles.dialogContent, { height: sheetHeight, paddingBottom: px2dp(24) }]}>
                <View style={styles.header}>
                    <View style={styles.closeBtn}>
                        <View style={{ opacity: 0 }}>
                            <Image style={styles.closeIcon} source={require('../../assets/close.png')} />
                        </View>
                    </View>
                    <Text style={{ color: '#999' }}>请选择地址</Text>
                    <View style={styles.closeBtn}>
                        <TouchableOpacity onPress={() => this.handleHide()}>
                            <Image style={styles.closeIcon} source={require('../../assets/close.png')} />
                        </TouchableOpacity>
                    </View>
                </View>
                {/* <View style={styles.topArea}>
                    <Text>热门城市</Text>
                    <View style={st}>

                    </View>
                </View> */}
                <View style={styles.bottomArea}>
                    <FlatList
                        data={province && province}
                        style={styles.listContainer}
                        contentContainerStyle={styles.listContentContainer}
                        renderItem={this.render_province}
                        keyExtractor={(item, index) => index + ''}
                    />
                    <FlatList
                        data={city && city}
                        style={styles.listContainer}
                        contentContainerStyle={styles.listContentContainer}
                        renderItem={this.render_city}
                        ListEmptyComponent={this.render_city_empty()}
                        keyExtractor={(item, index) => index + ''}
                    />
                    <FlatList
                        data={county && county}
                        style={styles.listContainer}
                        contentContainerStyle={styles.listContentContainer}
                        renderItem={this.render_couty}
                        ListEmptyComponent={this.render_couty_empty()}
                        keyExtractor={(item, index) => index + ''}
                    />
                </View>
            </View>
        )
    };

    render() {
        const { _height } = this.state;
        const sheetHeight = _height * 0.8;
        return (
            <View
                ref={c => { this.sheetContainer = c }}
                style={styles.container}>
                <Animated.View style={[styles.overlay, {
                    opacity: Animated.sub(0.8, Animated.multiply(this.fall, 0.8)),
                }]}>
                    <TouchableOpacity onPress={() => this.handleHide()} style={styles.tabContent}></TouchableOpacity>
                </Animated.View>
                <BottomSheet
                    snapPoints={[0, sheetHeight]}  // 高度
                    renderContent={this.renderInner}  // 内容
                    initialSnap={0}
                    enabledGestureInteraction={false} // 是否可以手势滑动 
                    enabledContentGestureInteraction={false} //内容区域是否可以滚动
                    callbackNode={this.fall}
                    ref={c => { this.sheet = c }}
                    borderRadius={px2dp(12)}
                    onCloseEnd={() => this._onCloseEnd()}
                />
            </View>
        )
    }
};


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

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

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

    content: {
        width: '100%',
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-end',
        paddingBottom: statusBarHeight
    },

    dialogContent: {
        position: 'relative',
        width: px2dp(375),
        backgroundColor: '#fff',
        zIndex: 9999,
        justifyContent: 'space-between',
        alignItems: 'center'
    },

    topArea: {
        width: '100%',
        borderBottomColor: '#d9d9d9',
        borderBottomWidth: onePx,
        height: px2dp(120),
        justifyContent: 'flex-start',
        alignItems: 'center'
    },

    bottomArea: {
        width: '100%',
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'flex-start'
    },

    header: {
        width: '100%',
        height: px2dp(32),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginTop: px2dp(4),
        paddingHorizontal: px2dp(12)
    },

    closeBtn: {
        width: px2dp(32),
        height: px2dp(32),
        zIndex: 999,
        justifyContent: 'center',
        alignItems: 'center'
    },

    closeIcon: {
        width: px2dp(20),
        height: px2dp(20),
        tintColor: '#999'
    },

    listContainer: {
        width: px2dp(124),
        flex: 1,
        // backgroundColor: 'red'
    },

    listContentContainer: {
        // width: '100%',
        justifyContent: 'space-between',
        alignItems: 'center'
    },

    item: {
        width: px2dp(124),
        height: px2dp(42),
        borderRightColor: '#d9d9d9',
        borderRightWidth: onePx,
        justifyContent: 'center',
        alignItems: 'center'
    }
})