import { useEffect, useRef, useState } from 'react'
import Taro, { useDidShow, useShareAppMessage } from '@tarojs/taro'
import { ScrollView, View, Text } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import './index.less'
import { getReadLog, setReadLog } from '@src/utils/loginSto'
import { cashBuy, virtualBuy } from '@src/server/wx/pay'
import useApi from '@src/Hook/useApi'
import { Store } from '@src/app'
import { setClipboardData, setNavigationBarColor, showToast } from '@src/utils/compatibility'
import TopNavBar from '@src/components/TopNavBar'
import BookConfigPuP from '@src/components/bookConfigPup'
import GlobalModal from '@src/components/bottomModal'
import IosShowPay from '@src/components/pay/IosShowPay'
import { share } from '@src/utils'

interface Config {
    size: 'pre_15' | 'pre_17' | 'pre_19' | 'pre_21' | 'pre_23' | 'pre_25' | 'pre_27' | 'pre_29' | any;
    off_on: boolean;
    bg: 'bg_b' | 'bg_h' | 'bg_l' | 'bg_hh';
    lh: 'lh_72' | 'lh_84' | 'lh_96';
}

type PageStateProps = {
    store: Store
};

interface BookArticleProps extends PageStateProps { }

const BookArticle: React.FC<BookArticleProps> = ({ store }) => {
    const [isLoad, setIsLoad] = useState(false)
    const { bookStore, indexStore, modalStore, userInfoStore } = store
    const [showPay, setShowPay] = useState(false)//需要付费展示
    const [showVip, setShowVip] = useState(false)//是否展示vip支付
    const [payBook, setPayBook] = useState<any>(null)//要支付的内容包含了费用
    const { openBookData } = bookStore
    const [bookConfig, setBookConfig] = useState<Config>({ size: 'pre_21', off_on: true, bg: 'bg_b', lh: 'lh_72' });
    const [pup, setPup] = useState(false);
    const { getBookContent, readingBook } = useApi()
    const [currentScrollId, setCurrentScrollId] = useState('');
    const newReadLogIdRef = useRef("");
    const readLogInterval = useRef<NodeJS.Timeout>()
    const [payType, setPayType] = useState<"shubi" | "vip">("shubi")
    //分享进入
    useDidShow(() => {
        let params = Taro.getCurrentInstance()?.router?.params
        console.log("params",params)
        // 获取书籍详情
        if (params?.bookId || params?.sBookId || params?.lBookId) {
            let bookId = params?.bookId || params?.sBookId || params?.lBookId
            bookStore.setData({ openBookData: { bookId } })
            log(bookId)
        }
    });
    // 页面显示的操作请求
    useEffect(() => {
        // ComponentDidMount
        if (openBookData?.bookId) {
            try {
                Taro.getStorage({
                    key: 'bookConfig',
                    success: (res) => {
                        setBookConfig(JSON.parse(res.data));
                    },
                    fail: () => {
                        setConfig({ size: 'pre_21', off_on: true, bg: 'bg_b', lh: 'lh_72' });
                    }
                });
            } catch (e) {
                console.error('Error loading book config:', e);
            }
            onReport()
            //假如存在阅读记录获取对应章节的条数
            let readLogId = getReadLog(openBookData?.bookId)
            getBookContent({ pageNum: 1, pageSize: readLogId ? Number(readLogId?.split('-')[1]) : 2 }).then((res: any) => {
                if (res?.data) {
                    // 只有当数据确实发生变化时才更新状态
                    const newRecords = res?.data?.data?.records;
                    const hasUnpaidContent = newRecords.some(item => {
                        let needPay = item.needPay //是否付费解锁
                        let isPay = item.isPay //是否已付费
                        let vipFree = userInfoStore?.isVip && item?.vipFree
                        // 不是VIP 并且 没有显示支付 并且 本段落需要支付 并且 本段落没有支付解锁
                        return !vipFree && !showPay && needPay && !isPay;
                    });

                    if (hasUnpaidContent) {
                        for (let item of newRecords) {
                            let needPay = item.needPay //是否付费解锁
                            let isPay = item.isPay //是否已付费
                            let vipFree = userInfoStore?.isVip && item?.vipFree
                            // 不是VIP 并且 没有显示支付 并且 本段落需要支付 并且 本段落没有支付解锁
                            if (!vipFree && !showPay && needPay && !isPay) {
                                setShowPay(true)
                                setShowVip(item.vipFree)
                                setPayBook(item)
                                break
                            }
                        }
                    }

                    // 更新书籍内容数据
                    bookStore.setData({ openBookData: { ...openBookData, contentData: res?.data?.data } });
                }
                //继续阅读时跳转到上次阅读的段落
                console.log("上次阅读到readLogId", readLogId)
                setCurrentScrollId(readLogId)
            })
        }
    }, []);//openBookData?.bookId, userInfoStore?.isVip
    // 上报阅读
    const onReport = () => {
        let scene = indexStore.scene
        let { startReadBook } = useApi()
        startReadBook({ bookId: bookStore.openBookData?.bookId, readCondition: scene })
    }
    // 页面卸载的操作
    useEffect(() => {
        reportRead()
        return () => {
            console.log("卸载", newReadLogIdRef.current);
            openBookData && setReadLog({ [openBookData.bookId]: newReadLogIdRef.current })//离开时存放当前位置
            clearInterval(readLogInterval.current)//清除上报心跳
            readingBook({ readId: bookStore.readId, readLogId: newReadLogIdRef.current, updateReadLog: true })
        };
    }, [])
    // 这里可以填写上报逻辑
    const reportRead = () => {
        console.log("上报", newReadLogIdRef.current)
        openBookData && setReadLog({ [openBookData.bookId]: newReadLogIdRef.current })
        if (readLogInterval.current) {
            clearInterval(readLogInterval.current)
        }
        // 定时上报心跳
        readLogInterval.current = setInterval(() => {
            readingBook({ readId: bookStore.readId, readLogId: newReadLogIdRef.current })
            console.log("上报阅读心跳", newReadLogIdRef.current, bookStore.readId)
        }, 3000);
    };
    //设置配置
    const setConfig = (data: Config) => {
        if (data) {
            setBookConfig(data);
            Taro.setStorage({
                key: 'bookConfig',
                data: JSON.stringify(data),
                success: (res: any) => {
                    console.log('添加bookConfig===>成功！', res);
                },
                fail: (err) => {
                    console.log('添加bookConfig===>失败', err);
                }
            });

            // 控制自义定头部背景
            store.bookStore.setData({ bookConfig: data });
        }
    };
    /**计算字体 */
    const setSize = (parms: number) => {
        let num = bookConfig.size.split('_');
        if (num[1] && parms) {
            setConfig({ ...bookConfig, size: num[0] + '_' + (Number(num[1]) + 2) });
        } else {
            setConfig({ ...bookConfig, size: num[0] + '_' + (Number(num[1]) - 2) });
        }
    };
    /**设置背景 */
    const setBg = (bg: 'bg_b' | 'bg_h' | 'bg_l' | 'bg_hh') => {
        setConfig({ ...bookConfig, bg });
        if (!bookConfig.off_on) {
            setOff(bg);
        }
    };
    /**设置行高*/
    const setLh = (lh: 'lh_72' | 'lh_84' | 'lh_96') => {
        setConfig({ ...bookConfig, lh });
    };
    /**关灯 */
    const setOff = (bg?: 'bg_b' | 'bg_h' | 'bg_l' | 'bg_hh') => {
        const newOffOn = !bookConfig.off_on;
        const newConfig = bg ? { ...bookConfig, bg, off_on: newOffOn } : { ...bookConfig, off_on: newOffOn };
        setConfig(newConfig);
        setNavigationBarColor({
            frontColor: newOffOn ? '#000000' : '#ffffff',
            backgroundColor: newOffOn ? '#fff' : '#111111'
        });
    };
    /**菜单 */
    const togglePup = () => {
        setPup(!pup);
    };
    //设置setNavigationBarColor
    useEffect(() => {
        setNavigationBarColor({
            frontColor: bookConfig.off_on ? '#000000' : '#ffffff',
            backgroundColor: bookConfig.off_on ? '#fff' : '#111'
        });
    }, [bookConfig.off_on]);
    // 下拉加载
    const onLoad = async (reload?: boolean) => {
        console.log("下拉加载")
        if (openBookData?.contentData) {
            console.log(openBookData?.contentData)
            let { size, current, total, records } = openBookData.contentData
            if (records.length < total || reload) {
                console.log("加载")
                setIsLoad(true)
                await getBookContent({ pageNum: 1, pageSize: reload ? size : size + 1 }).then((res: any) => {
                    if (res?.data) {
                        const newRecords = res?.data?.data?.records;
                        const hasUnpaidContent = newRecords.some(item => {
                            let needPay = item.needPay //是否付费解锁
                            let isPay = item.isPay //是否已付费
                            let vipFree = userInfoStore?.isVip && item?.vipFree
                            // 不是VIP 并且 没有显示支付 并且 本段落需要支付 并且 本段落没有支付解锁
                            return !vipFree && !showPay && needPay && !isPay;
                        });
                        
                        // 只有当付费状态确实发生变化时才更新状态
                        if (hasUnpaidContent && !showPay) {
                            for (let item of newRecords) {
                                let needPay = item.needPay //是否付费解锁
                                let isPay = item.isPay //是否已付费
                                let vipFree = userInfoStore?.isVip && item?.vipFree
                                // 不是VIP 并且 没有显示支付 并且 本段落需要支付 并且 本段落没有支付解锁
                                if (!vipFree && !showPay && needPay && !isPay) {
                                    setShowPay(true)
                                    setShowVip(item.vipFree)
                                    setPayBook(item)
                                    break
                                }
                                // 假如开通了vip但showPay没有关闭
                                if (showPay && vipFree) {
                                    setShowPay(false)
                                    break
                                }
                            }
                        } else if (!hasUnpaidContent && showPay) {
                            // 如果不再有需要付费的内容，隐藏付费弹窗
                            setShowPay(false);
                        }
                        
                        // 更新书籍内容数据
                        bookStore.setData({ openBookData: { ...openBookData, contentData: res?.data?.data } });
                    }
                    setIsLoad(false)
                })
            } else {
                showToast({
                    title: '没有更多了~~',
                    duration: 1000,
                    icon: 'none'
                })
            }
        }
    }
    // 计算阅读的位置,存放以备下次阅读的时候跳转到对应位置
    const handleScroll = () => {
        const query = Taro.createSelectorQuery();
        query.selectAll('.shrot-text').boundingClientRect(); // 选择所有子元素
        query.selectViewport().scrollOffset(); // 获取视口的滚动位置
        query.exec(res => {
            const items = res[0]; // 子元素的位置信息
            const scrollTop = res[1].scrollTop + indexStore.navHeight; // 视口的滚动距离
            // 遍历所有子元素，判断哪个子元素在可视区域
            for (let item of items) {
                if (item.top <= scrollTop && item.bottom >= scrollTop) {
                    if (openBookData?.bookId) {
                        newReadLogIdRef.current = item.id//存放当前可视的段落ID
                    }
                    break;
                }
            }
        });
    };
    //支付弹窗
    const payBtn = (e, type) => {
        e.stopPropagation()
        setPayType(type)
        modalStore.showModal()
    }
    // 全本购买
    const allBuy = async (e) => {
        e.stopPropagation();
        let { paragraphInfo } = payBook
        if (payBook) {
            let params = {
                bookId: paragraphInfo.bookId,
                bookParagraphId: paragraphInfo.paragraphNo,
                orderCondition: "阅读中"
            }
            let res = await cashBuy(params, onLoad)
            if (res) {
                console.log("全本购买:", res)
                setTimeout(() => {
                    setShowPay(false)
                    setShowVip(false)
                    setPayBook(null)
                }, 100)
            }

        }
    }
    // 书币购买
    const shubiBuy = async (e) => {
        e.stopPropagation()
        let { paragraphInfo } = payBook
        if (payBook) {
            let params = {
                bookId: paragraphInfo.bookId,
                bookParagraphId: paragraphInfo.id,
                orderCondition: "阅读中"
            }
            let res = await virtualBuy(params, onLoad)
            if (res) {
                console.log("书币购买章节:", res)
                setTimeout(() => {
                    setShowPay(false)
                    setShowVip(false)
                    setPayBook(null)
                    modalStore.hideModal()
                }, 100)
            }
        }

    }
    const { size, bg, off_on, lh } = bookConfig;
    // 分享
    useShareAppMessage(async () => {
        // 获取当前页面栈
        const pages = Taro.getCurrentPages()
        // 获取栈顶的页面，即当前页面
        const currentPage = pages[pages.length - 1]
        // 获取页面的路径和参数
        const route = currentPage.route // 页面路径
        if (route) {
            let shareInfo: any = await share({ pagePath: route, bookId: openBookData?.bookId })
            let { sharePicUrl, shareTitles, pageName, pagePath } = shareInfo
            return {
                title: shareTitles || app.appInfo?.appName + '-' + pageName,
                path: pagePath || undefined,
                imageUrl: sharePicUrl || undefined
            }
        }
        return {}
    })
    return (
        <ScrollView
            lowerThreshold={indexStore.navHeight}
            // refresherTriggered={isLoad}//加载状态
            onScrollToLower={() => { onLoad() }}
            style={{ height: `calc(100vh - ${indexStore.navHeight}px)` }}
            scrollY={true}
            refresherDefaultStyle='black'
            scrollWithAnimation={false}
            scrollIntoView={currentScrollId}
            onScroll={handleScroll}
        >
            <View className={`book_article ${off_on ? bg : 'bg_hh'} ${off_on ? 'cl_h' : 'cl_b'}`} >
                {/* 顶部设置 */}
                <View className='header'>
                    <View className='btns'>
                        <View className='left'>
                            <Text
                                onClick={() => { size !== 'pre_15' && setSize(0) }}
                                className={!off_on ? size === 'pre_15' ? 'cl_e5' : '' : size === 'pre_15' ? 'cl_d6' : ''}
                            >字小</Text>
                            <Text
                                onClick={() => { size !== 'pre_29' && setSize(1) }}
                                className={!off_on ? size === 'pre_29' ? 'cl_e5' : '' : size === 'pre_29' ? 'cl_d6' : ''}
                            >字大</Text>
                        </View>
                        <View className='right'>
                            <Text onClick={() => { setOff() }}>{off_on ? '关灯' : '开灯'}</Text>
                            {isLoad && <Text onClick={togglePup}>菜单</Text>}
                        </View>
                    </View>
                </View>
                {/* 正文内容 */}
                <View onClick={togglePup}>
                    {
                        openBookData?.contentData?.records?.map(item => {
                            let needPay = item.needPay //是否付费解锁
                            let isPay = item.isPay //是否已付费
                            let showText = true //是否显示内容
                            let arr = item.paragraphInfo.content?.match(/[^\n]*\n?/g);
                            // 是否需要付费
                            let vipFree = userInfoStore?.isVip && item?.vipFree
                            // 不是VIP 并且 没有显示支付 并且 本段落需要支付 并且 本段落没有支付解锁
                            if (!vipFree && !showPay && needPay && !isPay) {
                                showText = false
                            }
                            return showText ? <View
                                id={'paragraphNo-' + item.paragraphInfo.paragraphNo}
                                key={item.paragraphInfo.paragraphNo}
                                className={`pre ${size} ${lh}`}
                            >
                                {
                                    arr?.map((str, index) => {
                                        // let strArr = str?.match(/[^。]*。/g)
                                        return <Text className='shrot-text' id={'paragraphNo-' + item.paragraphInfo.paragraphNo + '-' + index} key={index}>{
                                            str
                                        }</Text>
                                    })
                                }
                            </View> : null
                        })
                    }

                    {showPay && <View className='pay_btns'>
                        <IosShowPay>
                            <View className='text-with-lines' >剩余内容需付费解锁</View>
                            {/* 存在vip免费字段 并且配置了vip模板 展示购买vip */}
                            {showVip && !!indexStore?.rechargeTemplate?.find(item => item.templateType === 2) && <View className='vip_btn' onClick={(e) => { payBtn(e, "vip") }}>开通会员，本书免费读</View>}
                            {/* 存在章节书币价格 并且配置了充值模板 显示购买书币 */}
                            {payBook?.payCoin && !!indexStore?.rechargeTemplate?.find(item => item.templateType === 1) && <View className='shubi_btn' onClick={(e) => {
                                // 余额
                                let coinNum = userInfoStore?.userInfo?.coinNum || 0
                                // 余额大于等于所需书币
                                if (coinNum >= payBook?.payCoin) {
                                    shubiBuy(e)
                                } else {
                                    payBtn(e, "shubi")
                                }
                            }}>购买本章 {payBook?.payCoin}书币</View>}
                            {/* 存在全本购买价格展示全本购买按钮*/}
                            {payBook?.payAmount && <View className='shubi_btn' onClick={(e) => { allBuy(e) }}>支付{payBook?.payAmount}元购买本书</View>}
                        </IosShowPay>
                    </View>}

                </View>
                {/* 设置弹窗 */}
                {pup && <BookConfigPuP {...bookConfig} off_on={off_on} setOff={setOff} setSize={setSize} setBg={setBg} setLh={setLh} />}
                {/* 支付弹窗 */}
                <GlobalModal
                    type={payType}
                    callBackFn={onLoad}
                    shubiData={{
                        coinNum: userInfoStore?.userInfo?.coinNum || 0,
                        payCoin: payBook?.payCoin || 0,
                    }}
                    payBookInfo={{
                        bookId: payBook?.paragraphInfo?.bookId,
                        bookParagraphId: payBook?.paragraphInfo?.paragraphNo,
                        orderCondition: "阅读中"
                    }}
                />
            </View>
            {/* 底部下来加载 */}
            {/* {
                isLoad && <UpLoading />
            } */}
        </ScrollView>
    );
};
export default inject('store')(observer(TopNavBar(BookArticle, { isToBack: true, isReloadBook: true })));