import React, { useEffect, useState, useRef } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    PanResponder,
    Animated,
    ScrollView,
    TouchableOpacity,
    TouchableWithoutFeedback,
    StatusBar
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import http from '../../utils/http';
import { rpx } from '../../utils/rpx';
import Slider from '../../components/slider';
import MiniMap from './MiniMap';
import { apiService } from '../../utils/api';
import DeviceControl from '../../components/DeviceControl';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 定义导航参数类型
type RootStackParamList = {
    Home: undefined;
    DeviceList: undefined;
    DeviceMap: undefined;
    DeviceSet: undefined;
    DeviceShare: undefined;
    TestBule: undefined;
    // 添加其他页面的路由参数类型
};
type DeviceType = {
    id: number;
    sn: string;
    vehicleNum: string;
    model: string;
    remainingPower: number;
    remainingMileage: number;
    isDefault: number;
    lockStatus: number;
};

// 定义导航类型
type NavigationProp = StackNavigationProp<RootStackParamList>;

const NormaIndex: React.FC = () => {
    const [count, setCount] = useState(0);
    const [data, setData] = useState(null);
    const translateX = useRef(new Animated.Value(0)).current;
    const bgColor = useRef(new Animated.Value(0)).current;
    const navigation = useNavigation<NavigationProp>();
    const [defaultDevice, setDefaultDevice] = useState<DeviceType | null>(null);
    const handlePress = () => {
        navigation.navigate('DeviceList');
    };
    const toSet = () => {
        navigation.navigate('DeviceSet');
    };

    const toMap = () => {
        navigation.navigate('DeviceMap');
    };
    const toShare = () => {
        navigation.navigate('DeviceShare');
    };
    const toTestBule = () => {
        navigation.navigate('TestBule');
    };
    const panResponder = useRef(
        PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onPanResponderMove: Animated.event(
                [null, { dx: translateX }],
                { useNativeDriver: false }
            ),
            onPanResponderRelease: (_, gestureState) => {
                if (gestureState.dx > rpx(268) / 2) {
                    Animated.parallel([
                        Animated.timing(translateX, {
                            toValue: rpx(268),
                            duration: 300,
                            useNativeDriver: false
                        }),
                        Animated.timing(bgColor, {
                            toValue: 1,
                            duration: 300,
                            useNativeDriver: false
                        })
                    ]).start();
                } else {
                    Animated.parallel([
                        Animated.timing(translateX, {
                            toValue: 0,
                            duration: 300,
                            useNativeDriver: false
                        }),
                        Animated.timing(bgColor, {
                            toValue: 0,
                            duration: 300,
                            useNativeDriver: false
                        })
                    ]).start();
                }
            }
        })
    ).current;

    const bgColorInterpolate = bgColor.interpolate({
        inputRange: [0, 1],
        outputRange: ['#EBEBEB', 'blue']
    });

    const opacityInterpolate = translateX.interpolate({
        inputRange: [0, rpx(268)],
        outputRange: [1, 0]
    });

    useEffect(() => {
        fetchDeviceList();
    }, []);
    const getPowerColor = (power: number): string => {
        if (power >= 60) {
            return 'rgba(89, 202, 112, 0.5)'; // 绿色
        } else if (power >= 20) {
            return 'rgba(255, 149, 0, 0.5)'; // 橙色
        } else {
            return 'rgba(255, 69, 58, 0.5)'; // 红色
        }
    };
    const handleDeviceUpdate = async () => {
        console.log('handleDeviceUpdate');

        const response = await apiService.getDeviceList();


        if (response?.code == 200 && response.data) {
            const defaultDev = response.data.find((device: DeviceType) => device.isDefault == 1);
            if (defaultDev) {
                setDefaultDevice(defaultDev);
                // 存储设备 sn 到本地存储


            }
        }
    };
    const fetchDeviceList = async () => {
        try {

            const response = await apiService.getDeviceList();
            console.log(response, 'response');
            if (response?.code === 200 && response.data) {
                const defaultDev = response.data.find((device: DeviceType) => device.isDefault == 1);
                if (defaultDev) {
                    console.log(defaultDev.sn, 'defaultDev.sn');
                    await AsyncStorage.setItem('defaultDeviceSN', defaultDev.sn);
                    // console.log(defaultDev, 'defaultDev');
                    setDefaultDevice(defaultDev);
                }

            }
        } catch (error) {
            console.error('获取设备列表失败:', error);
        } finally {

        }
    };
    return (
        <View style={styles.pageContainer}>
            <StatusBar
                backgroundColor="#F3FCFF"  // 设置为白色
                barStyle="dark-content"    // 状态栏文字为深色
                translucent={false}        // 不透明
            />
            <ScrollView
                contentContainerStyle={styles.scrollContent}
                scrollEventThrottle={16}
                nestedScrollEnabled={true}
            >
                <View style={styles.container}>
                    <TouchableOpacity onPress={handlePress}>
                        <View style={styles.titBox}>
                            <Text
                                style={styles.titTxts}
                                numberOfLines={2}
                                ellipsizeMode="tail"
                            >
                                {defaultDevice?.model || '未选择车辆'}
                            </Text>
                            <Image
                                source={{ uri: 'https://api.ccttiot.com/smartmeter/img/static/uJRIitv0Yn5K7CEVe9qd' }}
                                style={styles.arrowIcon}
                            />
                        </View>
                    </TouchableOpacity>

                    <View style={styles.KmBox}>
                        <View style={styles.KmLi}>
                            <View style={styles.KmLi_top}>
                                <Text style={styles.titTxt}>{defaultDevice?.remainingMileage}</Text>
                                <Text style={styles.KmLi_tits}>km</Text>
                            </View>
                            <View style={styles.KmLi_bot}>
                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uDg93bCzlPFiFBtS71Al' }}
                                    style={{ width: rpx(32), height: rpx(32) }}
                                />
                                <Text style={styles.KmLi_tits1}>剩余里程</Text>
                            </View>
                        </View>
                        <View style={styles.KmLi}>
                            <View style={styles.KmLi_top}>
                                <Text style={styles.titTxt}>110</Text>
                                <Text style={styles.KmLi_tits}>km</Text>
                            </View>
                            <View style={styles.KmLi_bot}>
                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uDg93bCzlPFiFBtS71Al' }}
                                    style={{ width: rpx(32), height: rpx(32) }}
                                />
                                <Text style={styles.KmLi_tits1}>剩余里程</Text>
                            </View>
                        </View>
                    </View>
                    <DeviceControl defaultDevice={defaultDevice} onDeviceUpdate={handleDeviceUpdate} />
                 
                    <TouchableWithoutFeedback>
                        <View style={styles.mapWrapper}>
                            <MiniMap defaultDevice={defaultDevice} />
                        </View>
                    </TouchableWithoutFeedback>
                    {defaultDevice?.type == 1 && (
                        <>


                            <TouchableOpacity onPress={toSet}>
                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/ucYQHQ2Ep4odL8JpbtfT' }}
                                    style={styles.carSet}
                                />
                            </TouchableOpacity>

                            <View style={styles.otherSet}>
                                <TouchableOpacity onPress={toShare}>
                                    <Image
                                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/ulDHhC4MrH3FO0AeTqVg' }}
                                        style={styles.otherImg}
                                    />
                                </TouchableOpacity>

                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u849NsNxdtzxhUkUJnfW' }}
                                    style={styles.otherImg}
                                />
                            </View>
                        </>
                    )}
                </View>
            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
    pageContainer: {
        flex: 1,
        backgroundColor: '#F3FCFF', // 设置整个页面的背景色为白色
    },
    scrollContent: {
        flexGrow: 1,
    },
    mapWrapper: {
        marginVertical: rpx(20),
    },
    stauseText: {
        fontSize: rpx(32),
        color: '#3D3D3D',
        textAlign: 'center',
        marginTop: rpx(24)
    },

    otherSet: {
        marginTop: rpx(30),
        // display:f,\
        flexDirection: 'row', // 保持在一行中
        justifyContent: 'space-between'

    },
    otherImg: {
        width: rpx(328),
        height: rpx(160),
    },
    carSet: {
        marginTop: rpx(30),
        width: rpx(688),
        height: rpx(380),
    },
    car_Opne_box: {
        justifyContent: 'center'
    },
    MiniMap: {
        // marginTop:rpx(44),
        marginBottom: rpx(44),
    },
    car_Opne: {
        width: rpx(268),
        height: rpx(90),
        flexDirection: 'row', // 保持在一行中
        backgroundColor: "#EBEBEB",
        alignItems: 'center',
        paddingRight: rpx(30),
        borderRadius: rpx(45)
    },
    car_stause_li: {
        width: rpx(136),
        justifyContent: 'center'
    },
    car_stause_box: {
        marginTop: rpx(308),
        flexDirection: 'row', // 保持在一行中
        justifyContent: 'space-around'
    },
    infoBox: {

        marginTop: rpx(66),
        flexDirection: 'row', // 保持在一行中
        // alignItems:'center',
        justifyContent: 'space-between'
    },
    carBox: {
        width: rpx(440),
        position: 'absolute',

        top: rpx(20),
        left: rpx(124),
        zIndex: 0,
    },
    Bind_type: {
        flexDirection: 'row', // 保持在一行中

        width: rpx(272),
        height: rpx(60),
        backgroundColor: '#fff',
        borderRadius: rpx(30),
        alignItems: 'center',
    },
    txtbox: {
        width: rpx(440),
        justifyContent: 'center',
        flexDirection: 'row', // 保持在一行中
        alignItems: 'center', // 垂直居中对齐
    },
    txt: {
        marginLeft: rpx(14), // 为了给圆形和文本之间留出一些间距
        fontSize: rpx(28),
        fontWeight: '400',
        color: '#3D3D3D',
    },
    yuan: {
        width: rpx(22),
        height: rpx(22),
        borderRadius: rpx(11),
        backgroundColor: 'rgba(255, 130, 130, 1)',
    },
    eleBox: {
        paddingTop: rpx(14),
        paddingRight: rpx(6),
        paddingBottom: rpx(6),
        paddingLeft: rpx(6),
        width: rpx(86),
        height: rpx(166),
        borderRadius: rpx(16),
        backgroundColor: '#FFFFFF',
        justifyContent: 'flex-end',
        // 添加阴影效果
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 4, // Android 阴影
        // 添加边框使其更加醒目
        borderWidth: 1,
        borderColor: '#E0E0E0',
    },
    eleType: {
        width: '100%',
        minHeight: rpx(30),
        borderRadius: rpx(16),
        position: 'relative',

    },
    eleTypeTxt: {
        position: 'absolute',
        top: rpx(-40),
        width: '100%',
        textAlign: 'center',
        fontSize: rpx(32),
        color: '#3D3D3D',
        // fontWeight: 'bold',
        // 为文字添加阴影效果使其更清晰
        textShadowColor: 'rgba(255, 255, 255, 0.5)',
        textShadowOffset: { width: 0, height: 1 },
        textShadowRadius: 2
    },
    titBox: {
        flexDirection: 'row',
        alignItems: 'center',
        display: 'flex',
        flexWrap: 'nowrap',
        maxWidth: rpx(600), // 增加最大宽度
    },
    titTxts: {
        width: rpx(250),
        fontSize: rpx(48),
        fontWeight: '500',
        color: '#3D3D3D',
        // flex: 2, // 添加 flex 属性
    },
    arrowIcon: {
        width: rpx(24),
        height: rpx(14),
        marginLeft: rpx(8)
    },
    KmLi_bot: {
        marginTop: rpx(4),
        flexDirection: 'row', // 保持在一行中
        alignItems: 'center', // 垂直居中对齐
    },
    KmLi_tits1: {
        marginLeft: rpx(4),
        fontSize: rpx(28),
        color: '#808080',
    },
    container: {
        flex: 1, // Ensure this takes full height of screen
        // width: '100%',
        // height: '100%',

        backgroundColor: '#F3FCFF',
        padding: rpx(32),
        // paddingBottom:rpx(500),
    },
    KmBox: {
        marginTop: rpx(28),
        width: '100%',

        flexDirection: 'row', // 保持在一行中
        alignItems: 'center', // 垂直居中对齐
        justifyContent: 'space-between',
    },
    KmLi: {
        // width: '50%',

    },

    KmLi_tits: {
        paddingBottom: rpx(10),
        fontSize: rpx(24),
        color: '#3D3D3D',
        // fontWeight:'bold'
    },
    KmLi_top: {
        width: '100%',

        flexDirection: 'row',
        flexWrap: 'nowrap',
        verticalAlign: 'bottom',
        alignItems: "flex-end",
    },

    titTxt: {
        fontSize: rpx(48),
        color: '#3D3D3D',
        fontWeight: 'bold'
    }

});


export default NormaIndex;
