//@ts-nocheck
import React, { Component } from 'react'
import { View, Text, StyleSheet, DeviceEventEmitter, TouchableOpacity, Linking, Animated, Easing, Image } from 'react-native'
import { px2dp, onePx, colors, toast, version, isIos } from './../../../utils/base';
import HttpUtils from '../../../utils/http';
import { checkVersion, versionConfig, versionSwitch } from '../../../utils/api';
import redux from './../../../redux/store';
import { comErrorMsg } from '../../../utils/com';
import EVENT_KEY from '../../../utils/event-key';

export default class UpdateToast extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            opacity: new Animated.Value(0),
        };
        this.active = false;
        this.delayTimer = null;
    }

    componentDidMount() {
        this.taskListner = DeviceEventEmitter.addListener('check-version', (a) => this.checkNewVersionExist());
        let params1 = {
            version_platform: version.platform,
            version_no: version.version_counter,
        };
        console.log(params1)
        HttpUtils.getRequest(versionSwitch, params1)
            .then(res => {
                console.log("当前开关信息", res)
                if (res.code === 10000) {
                    if (res.data && res.data.info && res.data.info.switch && res.data.info.switch === 1) {
                        console.log('kaiguan', 'kaiqi')
                        redux.dispatch({ type: 'SET_SWITCH', data: { loaded: true, value: 1 } });
                    } else {
                        console.log('kaiguan', 'guanbi');
                        DeviceEventEmitter.emit(EVENT_KEY.useHotUpdate);
                        redux.dispatch({ type: 'SET_SWITCH', data: { loaded: true, value: 0 } });
                    }
                }
            })
            .catch(err => {
            })
        this.delayTimer = setTimeout(() => {
            this.checkNewVersionExist();
        }, 1000)
    }

    checkNewVersionExist() {
        let params = {
            version_platform: version.platform,
        };
        console.log('参数', params)
        HttpUtils.getRequest(versionConfig, params)    //查询新版本
            .then(res => {
                console.log('版本信息', res);
                if (res.code === 10000) {
                    if (res.data && Number(res.data.info.version_no) > version.version_counter) {
                        this.show(res.data.info);
                    } else {
                        // alert("已是最新版")
                    }
                    // if (res.data && res.data.info && res.data.info.switch && res.data.info.switch === 1) {
                    //     redux.dispatch({ type: 'SET_SWITCH', switch: 1 });
                    // }
                } else {

                }
            })
            .catch(err => {
                toast(comErrorMsg)
            })
    }

    componentWillUnmount() {
        this.delayHide && clearTimeout(this.delayHide);
        this.delayTimer && clearTimeout(this.delayTimer);
        this.taskListner && this.taskListner.remove();
    }

    show = (data) => {
        console.log(data)
        this.setState({ data: data })
        this.toast.setNativeProps({
            style: {
                zIndex: 98
            }
        })
        Animated.timing(
            this.state.opacity,
            {
                toValue: 0.32,
                duration: 250,
                easing: Easing.in(),
                useNativeDriver: true
            }
        ).start();
    }

    hide = () => {
        this.active = false;
        Animated.timing(
            this.state.opacity,
            {
                toValue: 0,
                duration: 200,
                easing: Easing.in(),
                useNativeDriver: true
            }
        ).start();
        this.delayHide = setTimeout(() => {
            this.toast.setNativeProps({
                style: {
                    zIndex: -1
                }
            })
        }, 200);
    }

    jumpToMarket() {
        try {
            const { data } = this.state;
            if (isIos()) {
                let testAppleUrl = data.adopt_address;
                console.log(testAppleUrl);
                Linking.canOpenURL(testAppleUrl).then(supported => {
                    if (supported) {
                        Linking.openURL(testAppleUrl);
                    } else {
                        toast("打开AppleStore失败，请您自动前往更新");
                    }
                })
            } else {
                //安卓应用处理逻辑
                // let androidPackageUrl = data.adopt_address;
                // Linking.canOpenURL(androidPackageUrl).then(supported => {
                //     if (supported) {
                //         Linking.openURL(androidPackageUrl);
                //     } else {
                //         toast("打开应用市场失败,请您手动去应用市场搜索海囤生活App下载更新");
                //     }
                // })
                let uri = "market://details?id=com.haitunapp"
                Linking.canOpenURL(uri)
                    .then(res => {
                        Linking.openURL(uri);
                    })
                    .catch(err => {
                        toastShort("打开应用市场失败，请您手动打开")
                    })
            }
        } catch (e) {
            toast("打开应用市场失败,请您手动去应用市场搜索海囤生活App下载更新");
        }
    }

    render_text(text, index) {
        return (
            <Text style={styles.dec} key={index + ''}>{index + 1}、{text}</Text>
        )
    };

    render() {
        const { data } = this.state;
        console.log(data)
        return (
            <View ref={(c) => this.toast = c} style={styles.toastContainer}>
                <Animated.View style={[styles.toastOverlay, { opacity: this.state.opacity }]}></Animated.View>
                <View style={styles.toastContent}>
                    <Image style={styles.updatebg} source={require('./../../../assets/update-bg.png')} />
                    <View style={styles.innerBox}>
                        <Text style={styles.title}>新版本发布了～</Text>
                        {
                            data && data.content && data.content.split('，').map((text, index) => this.render_text(text, index))
                        }
                        <TouchableOpacity onPress={() => this.jumpToMarket()} style={styles.btn}>
                            <Text style={{ fontSize: 14, color: '#fff' }}>立即更新</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                {
                    data && data.type !== 1 ?
                        <TouchableOpacity onPress={() => this.hide()} style={styles.closeBtn}>
                            <Image style={styles.closeIcon} source={require('./../../../assets/close-icon.png')} />
                        </TouchableOpacity>
                        :
                        <View style={styles.closeBtn}>
                        </View>
                }
            </View>
        )
    }
}


const styles = StyleSheet.create({
    toastContainer: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        overflow: 'hidden',
        zIndex: -1
    },

    toastOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        width: '100%',
        height: '100%',
        backgroundColor: '#000'
    },

    toastContent: {
        width: px2dp(260),
        // height: px2dp(182),
        backgroundColor: '#fff',
        borderRadius: px2dp(18),
        justifyContent: 'space-between',
        alignItems: 'center',
        overflow: 'hidden',
    },

    updatebg: {
        width: '100%',
        height: px2dp(260 * 606 / 1092)
    },

    innerBox: {
        width: '100%',
        paddingVertical: px2dp(12),
        paddingHorizontal: px2dp(12),
        justifyContent: 'flex-start',
        alignItems: 'center'
    },

    btn: {
        width: px2dp(220),
        height: px2dp(36),
        backgroundColor: colors.themeColor,
        borderRadius: px2dp(18),
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: px2dp(18),
        marginBottom: px2dp(6)
    },

    closeBtn: {
        width: px2dp(42),
        height: px2dp(42),
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: px2dp(18)
    },

    closeIcon: {
        width: px2dp(24),
        height: px2dp(24)
    },

    // toastHeader: {
    //     width: '100%',
    //     justifyContent: 'center',
    //     alignItems: 'center',
    //     // backgroundColor: '#999',
    //     paddingTop: px2dp(18)
    // },

    // toastBody: {
    //     width: '100%',
    //     justifyContent: 'flex-start',
    //     alignItems: 'center',
    //     paddingHorizontal: px2dp(24),
    //     paddingTop: px2dp(12),
    //     paddingBottom: px2dp(24)
    // },

    title: {
        width: '100%',
        fontSize: 16,
        color: '#333',
        fontWeight: '600',
        lineHeight: 25,
        textAlign: 'center',
        letterSpacing: 0.8,
        marginBottom: px2dp(12)
    },

    dec: {
        width: '100%',
        fontSize: 15,
        color: '#999',
        marginBottom: px2dp(10)
    },
    // toastFooter: {
    //     width: '100%',
    //     height: px2dp(52),
    //     borderTopColor: '#eee',
    //     borderTopWidth: onePx,
    //     justifyContent: 'center',
    //     alignItems: 'center'
    // }
})