import { View,  Image } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { getPage, report } from "@src/server/index/index";
import { useEffect, useState } from "react";

function LdPage() {
    let systemInfo = Taro.getSystemInfoSync();
    let [data, setDate] = useState<any>(null)
    let [pageId, setPageId] = useState<any>(null)
    let [randomId, setRandomId] = useState<any>(null)
    const router = useRouter()
    useEffect(() => {
        let params = router.params
        if (params.pageId && params.openRead) {
            setPageId(params.pageId)
            Taro.showLoading({
                title: '加载中',
            })
            getPage(params.pageId).then((res: any) => {
                if (res.data.code === 200) {
                    let content = res.data.data.content
                    try {
                        content = JSON.parse(content)
                    } catch (error) {
                        console.log("error", error)
                    }
                    let obj = {
                    }
                    content?.elementsSpecList?.map((item, index) => {
                        if (item.elementType === "QR_CODE") {
                            let url = res.data.data.qrCodeList.find(q => q.siteId == item.id)?.urlList[0]
                            obj[item.elementType] = obj[item.elementType] ? [...obj[item.elementType], { ...item, url, eq: index }] : [{ ...item, url, eq: index }]
                        } else if (item.elementType === "FLOAT_BUTTON") {
                            let url = res.data.data.qrCodeFloatList.find(q => q.siteId == item.id)?.urlList[0]
                            obj[item.elementType] = { ...item, url, eq: index }
                        } else if (item.elementType === "TEXT") {
                            obj[item.elementType] = obj[item.elementType] ? [...obj[item.elementType], { ...item, eq: index }] : [{ ...item, eq: index }]
                        } else if (item.elementType === "IMAGE") {
                            obj[item.elementType] = obj[item.elementType] ? [...obj[item.elementType], { ...item, eq: index }] : [{ ...item, eq: index }]
                        } else {
                            obj[item.elementType] = { ...item, eq: index }
                        }
                        obj["bgColor"] = content["bgColor"]
                        obj["pageName"] = content["pageName"]
                    })
                    let randomId = Math.random().toString(36).substr(2) + "_" + params.pageId + "_" + Math.random().toString(36).substr(2);
                    setRandomId(randomId)
                    submitReport({ event: "pageLoad", pageId:params.pageId, randomId })
                    setDate({ ...res.data.data, ...obj })
                }
                Taro.hideLoading()
            })
        }
    }, [])
    const onLongPress = (str) => {
        console.log("用户长按了二维码:", str)
        submitReport({ event: "longPress", elementType: str, pageId, randomId })
    }
    const submitReport = (extra: any) => {
        let userInfo = Taro.getStorageSync("userInfo")
        let data = {
            "eventName": extra.event,
            "ts": Date.now(),
            "userId": userInfo.userInfo.openId,
            "extra": { ...extra }
        }
        report(data).then(() => {
            console.log("上报成功")
        }).catch(() => {
            console.log("上报失败")
        })
    }
    console.log("randomId", randomId)
    return <View >
        {data && <>
            <View style={{ marginTop: (systemInfo.statusBarHeight as any) + 10 }}></View>
            {/* 标题 */}
            <View style={{ textAlign: 'center', paddingBottom: 10 }}>{data ? data["pageName"] : data["name"] || ""}&nbsp;</View>
            {/* 内容 */}
            {data["bgColor"] ? <View style={{ height: `calc(100vh - ${(systemInfo.statusBarHeight || 0) + 32}px)`, backgroundColor: data ? data["bgColor"] : "#d5e8d6", overflowY: "auto" }}>
                <View style={{ display: 'flex', flexFlow: 'column', paddingBottom: 100 }}>
                    {/* 顶图 */}
                    {data["TOP_IMAGE"] && <Image src={data["TOP_IMAGE"].url} mode="widthFix" style={{ height: "auto", width: "100vw", order: data["TOP_IMAGE"].eq }} />}
                    {/* 文本 */}
                    {data["TEXT"] && data["TEXT"].map((textObj) => {
                        let { text, eq, elementType, comptActive, ...styles } = textObj
                        return <View dangerouslySetInnerHTML={{ __html: text }} style={{ paddingLeft: 24, paddingRight: 24, whiteSpace: "pre-wrap", order: eq, ...styles }}></View>
                    })}
                    {/* 图 */}
                    {data["IMAGE"] && data["IMAGE"].map((imgObj) => {
                        let { eq, elementType, comptActive, url, ...styles } = imgObj
                        return <Image src={url} mode="widthFix" style={{ height: "auto", width: "100vw", order: imgObj.eq, ...styles }} />
                    })}
                    {/* 二维码 */}
                    {data["QR_CODE"] && data["QR_CODE"].map((qrObj) => {
                        let { eq, elementType, comptActive, url, id, imageList, ...styles } = qrObj
                        return <Image src={url} mode="widthFix" onLongPress={() => { onLongPress("QR_CODE") }} showMenuByLongpress style={{ height: "auto", width: "100vw", order: eq, boxSizing: "border-box", ...styles }} />
                    })}
                    {/* 底部浮选图 */}
                    {data["FLOAT_BUTTON"] && <Image src={data["FLOAT_BUTTON"].url} mode="widthFix" onLongPress={() => { onLongPress("FLOAT_BUTTON") }} showMenuByLongpress style={{ height: "auto", width: "100vw", position: 'fixed', bottom: 0, left: 0, zIndex: 999, order: data["FLOAT_BUTTON"].eq }} />}
                </View>
            </View> : <View style={{ display: 'flex', flexFlow: 'column', paddingBottom: 100 }}>
                {/* 顶图 */}
                {data["TOP_IMAGE"] && <Image src={data["TOP_IMAGE"].url} mode="widthFix" style={{ height: "auto", width: "100vw", order: data["TOP_IMAGE"].eq }} />}
                {/* 文本 */}
                {data["TEXT"] && data["TEXT"].map((textObj, index) => {
                    return index === 0 ? <View style={{ fontSize: 24, fontWeight: "bold", color: "", padding: "10px 20px", display: 'grid', gap: 10, order: textObj.eq }}>{textObj?.text?.split(/\s/ig)?.map((item, index) => {
                        return <View style={index === 0 ? { color: "#D0021B", marginBottom: -10 } : {}}>{item}</View>
                    })}</View> : <View style={{ fontSize: 24, fontWeight: "bold", color: "", padding: "10px 20px", display: 'grid', gap: 10, order: textObj.eq }}>{textObj?.text?.split(/\s/ig)?.map((item, index) => {
                        return <View>{item}</View>
                    })}</View>
                })}
                {/* 图 */}
                {data["IMAGE"] && data["IMAGE"].map((imgObj) => {
                    return <Image src={imgObj.url} mode="widthFix" style={{ height: "auto", width: "100vw", order: imgObj.eq }} />
                })}
                {/* 二维码 */}
                {data["QR_CODE"] && data["QR_CODE"].map((qrObj) => {
                    return <Image src={qrObj.url} onLongPress={() => { onLongPress("QR_CODE") }} mode="widthFix" showMenuByLongpress style={{ height: "auto", width: "70vw", display: 'block', margin: '0 auto', order: qrObj.eq }} />
                })}
                {/* 底部浮选图 */}
                {data["FLOAT_BUTTON"] && <Image src={data["FLOAT_BUTTON"].url} mode="widthFix" onLongPress={() => { onLongPress("FLOAT_BUTTON") }} showMenuByLongpress style={{ height: "auto", width: "100vw", position: 'fixed', bottom: 0, left: 0, zIndex: 999, order: data["FLOAT_BUTTON"].eq }} />}
            </View>
            }
        </>}
    </View>
}


export default LdPage;