import React, { useEffect, useState } from 'react';
import { View, StyleSheet, ActivityIndicator, Text, TouchableOpacity, Image } from 'react-native';
import { WebView } from 'react-native-webview';
import { TopNavigation, TopNavigationAction, Icon, IconElement } from '@ui-kitten/components';
import { useRoute, useNavigation } from '@react-navigation/native';
import { apiService } from '../../utils/api';
import { rpx } from '../../utils/rpx';

import * as WeChat from "@shm-open/react-native-wechat"
// 初始化微信 SDK


const BackIcon = (props): IconElement => (
    <Icon
        {...props}
        name='arrow-back'
        fill='#000000'
    />
);

const FranchisePage = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const [xmlContent, setXmlContent] = useState('');
    const [title, setTitle] = useState('详情');
    const [loading, setLoading] = useState(true);

    const navigateBack = () => {
        navigation.goBack();
    };

    const BackAction = () => (
        <TopNavigationAction
            icon={BackIcon}
            onPress={navigateBack}
        />
    );

    const replaceImgWithImage = (content) => {
        content = content.replace(/&nbsp;/g, '\u00A0');
        content = content.replace(/<img([^>]*)>/g, (match, group1) => {
            let cleanedGroup = group1.replace(/\s*\/$/, '');
            return `<img style="width: 85vw; height: auto;" ${cleanedGroup} />`;
        });
        return content;
    };
    const openWeChatMiniProgram = async () => {
        WeChat.registerApp('wxe51234567890', "");  //注册wechat  

        const flag = await WeChat.isWXAppInstalled()  //判断是否安装微信

        if (!flag) {
            // return Alert.alert('提示', '您还未安装微信客户端');
            
        }

        let MiniProgram = {
            userName: '	wx8a05cf95418a6859',  //不是小程序的AppID 是原始ID
            path: 'pages/pagehome/pagehome',  //要跳转到小程序的那一页
            miniprogramType: 0,  //小程序类型   RELEASE = 0,TEST = 1,PREVIEW = 2
        }

        await WeChat.openMiniprogram(MiniProgram)  //开始跳转至微信小程序

    };
    const fetchArticleById = async () => {
        const response = await apiService.getArticleById(30);
        console.log(response, '1111111111111');
        const modifiedContent = replaceImgWithImage(response.data.content);
        setXmlContent(modifiedContent);
        setTitle(response.data.title || '详情');
        setLoading(false);
    }

    useEffect(() => {
        fetchArticleById();
    }, []);

    return (
        <View style={styles.container}>
            <TopNavigation
                title={title}
                alignment='center'
                accessoryLeft={BackAction}
                style={styles.header}
            />
            {loading ? (
                <ActivityIndicator size="large" color="#0000ff" style={styles.loading} />
            ) : (
                <WebView
                    originWhitelist={['*']}
                    source={{ html: xmlContent }}
                    style={styles.webview}
                    scalesPageToFit={false}
                    injectedJavaScript={`
                        const meta = document.createElement('meta');
                        meta.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1');
                        meta.setAttribute('name', 'viewport');
                        document.getElementsByTagName('head')[0].appendChild(meta);
                    `}
                />
            )}
            <TouchableOpacity
                style={styles.floatingButton}
                onPress={openWeChatMiniProgram}
            >
                <Image
                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uJsh6S6UmCJgnMs5MqPG' }}
                    style={styles.floatingImage}
                />
                <Text style={styles.floatingText}>跳转到小程序</Text>
            </TouchableOpacity>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        backgroundColor: 'transparent',
        elevation: 0,
        shadowOpacity: 0,
    },
    webview: {
        width: rpx(750),
        flex: 1,
    },
    loading: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    floatingButton: {
        position: 'absolute',
        right: rpx(20),
        bottom: rpx(200),
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        borderRadius: rpx(25),
        padding: rpx(10),
        alignItems: 'center',
    },
    floatingImage: {
        width: rpx(50),
        height: rpx(50),
    },
    floatingText: {
        color: '#ffffff',
        marginTop: rpx(5),
    },
});

export default FranchisePage;