<template>
	<scroll-view class="scroll-container" :scroll-y="showRecharge==false" bounces="false"  :show-scrollbar="false" :refresher-enabled="false" :style="{'background-color': read_setting_data.readMode==config.read_config.readMode.Bright?config.read_config.colorList[read_setting_data.colorBgIndex]:DarkBg,'height':'100%' }">
		<readPage  ref="readPages" @onTouchstart="onStartClickView"
		@clickCatalog="onClickCatalog"
		@clickPreChapter="onClickPreChapter"
		@clickNextChapter="onClickNextChapter" 
		@onTouchend="onEndClickView" @onTouchmove="hideSetting" v-for="(book_read_data_item,index) in book_text_list_view" :key="book_read_data_item.book_chapter_id" 
		:text_content="book_read_data_item.book_content" :book_title="book_read_data_item.book_title"
		:coin="getChapterNeedCoin()"@onClickBuy="onClickBuy" @BuyChapter="onBuyChapter">
		</readPage>
	</scroll-view>
	<settingMenu ref="Menu" v-if="menuShow" :book_id="book_data.book_id" @clickCatalog="onClickCatalog"
	@clickPreChapter="onClickPreChapter" @clickNextChapter="onClickNextChapter" 
	@clickMode="onClickMode" @clickOpenSetting="onClickOpenSetting"
	@Close="closeMenu" @changeFontSize="onChangeFontSize" @changeBgColor="onChangeBgColor"
	@selectAutoBuy="onSelectAutoBuy" @clickKeep="onClickKeep">
	</settingMenu>
	<chapterCatalog v-if="showChapterList" :items="directoryList" :size="40" :remain="16"
	 :scrollHeight="windowHeight*0.7" @clickChar="goToChapter" @Close="showChapterList=false"
	 :unLockChapterList="unLockChapterList" :active="getCurChapterId()">
	</chapterCatalog>
	<!-- <recharge v-if="showRecharge" :coin="getChapterNeedCoin()" @Close="showRecharge=false" @onClickBuy="onClickBuy" @BuyChapter="onBuyChapter"></recharge> -->
</template>

<script setup lang="ts">
	import { onUnload } from '@dcloudio/uni-app'
	import { nextTick, onMounted, ref, watch } from 'vue';
	import { book_item_data, book_read_data, chapter_item_data, order_data, order_info_data } from '../../data/data';
	import { tools } from '../../framework/tools';
	import { UserStatus } from '../../stores/userStatusManager';
	import { log } from '../../framework/log';
	import readPage from '../../components/read/readPage.vue'
	import settingMenu from '../../components/read/settingMenu.vue'
	import chapterCatalog from '../../components/read/chapterCatalog.vue'
	// import {onPullDownRefresh,onReachBottom} from '@dcloudio/uni-app'
	import { ReadSetting } from '../../stores/readSetting';
	import { config } from '../../config/config';
	import { ReadRecord } from '../../stores/readRecordManager';
	// import recharge from '../../components/read/recharge.vue';
	import { http } from '../../framework/http';
	import { UserData } from '../../stores/userDataManager';
	
	const {windowHeight,windowWidth} = uni.getSystemInfoSync()
	const readPages = ref(null)
	const Menu = ref(null)
	let book_data:book_item_data = UserStatus().getUserSelectBook()
	let directoryList:chapter_item_data[] = []
	let cur_read_chapter_index =ref(0)
	let start_read_chapter_id = book_data.start_read_chapter_id
	//设置属性 
	let read_setting_data = ReadSetting().getReadSetting()
	let fontSize = config.read_config.fontSizeList[read_setting_data.fontSizeIndex]
	let bgColor = config.read_config.colorList[read_setting_data.colorBgIndex]
	
	// 页面销毁
	onUnload(()=>{
		tools.exitRead()
	})
	onMounted(()=>{
	})
	//设置属性end
	updateNavigation()
	if(book_data!=null&&start_read_chapter_id!=-1){
		initView()
	}
	let book_text_list_view = ref<Array<book_read_data>>([])
	let book_text_list_cache = ref<Map<number,book_read_data>>(new Map<number,book_read_data>())
	function initView(){
		tools.getChapterList(book_data.chapter_path,(chapter_ls)=>{
			directoryList = chapter_ls
			cur_read_chapter_index.value = tools.getCurChapterIndex(start_read_chapter_id,directoryList)
			draw(null)
		})
	}
	function draw(cb:Function,dir_is_down:boolean=true){
		let loading_view = (d:book_read_data)=>{
			book_data.start_read_chapter_id = d.book_chapter_id //记录开始阅读章节id
			ReadRecord().addData(book_data,d)
			cb && cb()
			nextTick(()=>{
				if(d!=null){
					if(dir_is_down){
						book_text_list_view.value.push(d)
					}else{
						book_text_list_view.value.unshift(d)
					}
					check_buy_status()
				}
			})
		}
		if(cur_read_chapter_index.value<=directoryList.length&&cur_read_chapter_index.value>=0){
			let data = tools.getCurChapterData(cur_read_chapter_index.value,directoryList)
			if(data!=null){
				let cache_data = book_text_list_cache.value.get(data.id)
				if(cache_data!=null){
					loading_view(cache_data)
				}else{
					tools.getCurChapterTxt(book_data.base_path,data.id,fontSize*2,(text:string)=>{
						cache_data = new book_read_data()
						cache_data.book_content = text
						cache_data.book_chapter_id = data.id
						cache_data.book_chapter_name = data.name
						cache_data.book_title = tools.autoParagraphTitle(data.name,fontSize*4) 
						book_text_list_cache.value.set(data.id,cache_data)
						loading_view(cache_data)
					})
				}
			}
		
		}else{
			log.Error("暂无可读取内容！")
		}
	}
	
	
	function check_buy_status(){
		
		let chapter = tools.getCurChapterData(cur_read_chapter_index.value,directoryList);
		if(chapter.pay_type == config.chapter_pay_type.SHOU_FEI){
			if(!tools.getUserIsVIP()){ //判断是否是vip
				if(ReadSetting().getReadSetting().autoBuyNextChpater){ //判断是否是自动购买
					if(UserData().getData().coin>=chapter.coin){ //用户书币足够支付
						check_book_chapter_is_buy(chapter.id,(isBuy)=>{
							if(!isBuy){
								BuyBookChapter(chapter.id,chapter.coin)
							}
						})
					}else{
						check_book_chapter_is_buy(chapter.id)
					}
				}else{
					check_book_chapter_is_buy(chapter.id)
				}
			}else{
				UnLockChapter()
			}
		}else{
			showRecharge.value = false
		}
		
		
	}
	
	function getCurChapterId(){
		let data = tools.getCurChapterData(cur_read_chapter_index.value,directoryList)
		return data.id
	}
	
	let showCode = ref(false)
	function check_book_chapter_is_buy(chapter_id:number,cb:Function=null){
		tools.check_book_chapter_is_buy(book_data.book_id,chapter_id,(isBuy)=>{
			if(!isBuy){
				console.log("check_book_chapter_is_buy1",isBuy)
				showRecharge.value = true
				showCode.value = true
				LockChapter()
			}else{
				UnLockChapter()
			}
			if(cb!=null){
				cb(isBuy)
			}
		})
	}
	function down_dir_load(){
		cur_read_chapter_index.value+=1;
		draw(null)
	}	
		
	function up_dir_load(){
		cur_read_chapter_index.value-=1;
		draw(null,false)
	}
	
	// onPullDownRefresh( async () => {
	// 	showTopLoadingStatus()
	// 	uni.stopPullDownRefresh();
	// })
	
	// onReachBottom(async ()=>{
	// 	showBottomLoadingStatus()
	// })
	
	function LockChapter(){
		readPages.value.find((child,index)=>{
			child.LockChapter()
		})
	}
	
	function UnLockChapter(){
		showRecharge.value = false
		if(readPages.value!=null){
			readPages.value.find((child,index)=>{
				child.UnLockChapter()
			})
		}
	
	}
	
	function showBottomLoadingStatus(){
		readPages.value.find((child,index)=>{
			if( index == (book_text_list_view.value.length-1) ){
				child.showBottomLoading()
				down_dir_load()
			}
		})
	}
	
	function showTopLoadingStatus(){
		readPages.value.find((child,index)=>{
			if( index == 0 ){
				child.showTopLoading()
				up_dir_load()
			}
		})
	}
	
	//设置相关
	let menuShow = ref(false)
	
	let startTouchY = ref(-1)
	
	let endTouchY = ref(-1)
	
	function onClickCatalog(){
		closeMenu()
		onShowChapterList()
	}
	
	function hideChapterList(){
		showChapterList.value = false
	}
	
	function onClickOpenSetting(){
		console.log("点了设置")
		showSetting()
	}
	
	function onClickPreChapter(){
		goToChapter(tools.getPreChapterData(cur_read_chapter_index.value,directoryList))
		hideSetting()
	}
	
	function onClickNextChapter(){
		goToChapter(tools.getNextChapterData(cur_read_chapter_index.value,directoryList))
		hideSetting()
	}
	
	function onStartClickView(e){
		startTouchY.value = e.changedTouches[0].pageY
	}
	
	function onEndClickView(e){
		endTouchY.value = e.changedTouches[0].pageY
		
		if(Math.abs(endTouchY.value-startTouchY.value)<=5){
			startTouchY.value = -1
			showMenuView()
		}
	}
	
	function showMenuView(){
		menuShow.value = true
	}
	
	function hideAllTop(){
		
	}
	
	function showSetting(){
		if(Menu.value.getSetttingStatus()){
			Menu.value.showSettingOther()
		}else{
			Menu.value.showSettingFont()
		}
	
	}
	
	function hideSetting(){
		startTouchY.value = -1
		menuShow.value = false
		hideChapterList()
	}
	
	function closeMenu(){
		hideSetting()
	}
	
	function onChangeFontSize(index:number){
		let new_index = -1;
		if(index>0){
			new_index = ReadSetting().data.fontSizeIndex + 1
			if(new_index>=config.read_config.fontSizeList.length){
				
			}else{
				ReadSetting().changeFontSize(new_index)
			}
		}else{
			new_index = ReadSetting().data.fontSizeIndex - 1
			if(new_index<0){
				
			}else{
				ReadSetting().changeFontSize(new_index)
			}
		}
	}
	
	function onChangeBgColor(index:number){
		ReadSetting().changeReadMode(config.read_config.readMode.Bright)
		ReadSetting().changeBgColor(index)
	}
	
	function onSelectAutoBuy(isAuto:boolean){
		ReadSetting().changeAutoBuyNextChapter(isAuto)
	}
	
	function onClickKeep(book_id:number){
		tools.checkBookOnBookshelf(book_id,(is_on)=>{
			if(is_on){
				// uni.showToast({
				// 	title:'当前书已在书架中了！',
				// 	icon:'none'
				// })
				tools.deleteBookshelf([book_data.book_id],()=>{
					Menu.value.updateBookshelfStatus()
					uni.showToast({
						title:'已移除书架！',
						icon:'none'
					})
				})
			}else{
				tools.addBookshelf(book_data,()=>{
					Menu.value.updateBookshelfStatus()
					uni.showToast({
						title:'成功添加书架！',
						icon:'none'
					})
				})
			}
		})
		log.Debug("收藏",book_data.book_name)
	}
	
	let DarkBg = ref(tools.getDbColorByMode(read_setting_data.readMode))
	
	function onClickMode(mode:number){
		ReadSetting().changeReadMode(mode)
	}

	watch(async () => ReadSetting().data.readMode, // 监听的数据源
		(newVal, oldVal) => {
			DarkBg.value = tools.getDbColorByMode(read_setting_data.readMode)
			updateNavigation()
		}
	);
	
	//设置end
	
	//章节列表 start
	let showChapterList = ref(false)
	function goToChapter(chapter_list_item_data:chapter_item_data){
		// console.log("想看",chapter_list_item_data)
		if(chapter_list_item_data!=null){
			cur_read_chapter_index.value = tools.getCurChapterIndex(chapter_list_item_data.id,directoryList)
			draw(()=>{
				book_text_list_view.value = []
			})
			hideChapterList()
		}else{
			uni.showToast({
				title:'没有此章节哦！',
				icon:'none'
			})
			log.Error('goToChapter error!',cur_read_chapter_index.value)
		}
	
	}
	
	watch(async () => ReadSetting().data.colorBgIndex, // 监听的数据源
		(newVal, oldVal) => {
			bgColor = config.read_config.colorList[read_setting_data.colorBgIndex]
			updateNavigation()
		}
	);
	
	function updateNavigation(){
		let showbgColor  = bgColor
		if(read_setting_data.readMode==config.read_config.readMode.Dark){
			showbgColor = tools.getDbColorByMode(read_setting_data.readMode)
		}
		uni.setNavigationBarColor({
		    frontColor: '#ffffff',
		    backgroundColor: showbgColor,
		    animation: {
		        duration: 0,
		        timingFunc: 'easeIn'
		    }
		})
	}
	
	//充值start
	let showRecharge = ref(false)
	
	// function getCurChapterId(){
	// 	return tools.getCurChapterData(cur_read_chapter_index.value,directoryList).id
	// }
	
	function getChapterNeedCoin(){
		let chapter = tools.getCurChapterData(cur_read_chapter_index.value,directoryList)
		if(chapter!=null){
			return chapter.coin
		}
		return 0
	}
	
	function onBuyChapter(){
		let chapter = tools.getCurChapterData(cur_read_chapter_index.value,directoryList)
		BuyBookChapter(chapter.id,chapter.coin)
	}
	
	function onClickBuy(goods_id:number,isVip:boolean = true){
		uni.showLoading({
			title:'跳转支付...',
			mask:true
		})
		http.DynamicRequest(config.url_confg.Dynamic.recharge.order_buy,{'pay_type':tools.getCurBuyType(),'goods_id':goods_id},(err,d)=>{
			if(!err){
				if(d.code == config.url_confg.StatesCode.SUCCESS){
					let data:order_data = d.content
					SchedulingOrder(data.order_id,()=>{
						UserData().update_user_info(()=>{
							uni.hideLoading()
							if(isVip){
								UnLockChapter()
								showRecharge.value = false
							}
							uni.showToast({
								title:'购买成功'
							})
						})
						
					})
				}
			}
		})
	}
	
	function BuyBookChapter(chapter_id:number,coin:number){
		if(tools.getUserIsVIP()){
			UnLockChapter()
			return
		}
		if(UserData().getData().coin>=coin){
			uni.showLoading({
				title:'正在购买...',
				mask:true
			})
			http.DynamicRequest(config.url_confg.Dynamic.buy_chapter,{'book_id':book_data.book_id,'chapter_id':chapter_id},(err,d)=>{
				if(!err){
					log.Debug(d)
					if(d.code==config.url_confg.StatesCode.SUCCESS){
						// d.content.includes(chapter_id)
						UserData().update_user_info(()=>{
							uni.hideLoading()
							uni.showToast({
								title:'购买成功！'
							})
							UnLockChapter()
							showRecharge.value = false
						})
					}else{
					
					}
				}else{
					log.Error(err)
				}
			
			})
		}else{
			uni.showToast({
				title:'书币不足！'
			})
		}
	
	}
	
	function SchedulingOrder(order_id:string,cb:Function){
		let temp = setInterval(()=>{
			http.DynamicRequest(config.url_confg.Dynamic.recharge.order_info,{'order_id':order_id},(err,d)=>{
				if(!err){
					if(d.code == config.url_confg.StatesCode.SUCCESS){
						let data:order_info_data = d.content
						if(data.status==config.order_status.YI_JING_ZHI_FU){
							clearInterval(temp)
							cb()
						}
					}
				}
			})
		},500)
	}
	let unLockChapterList = ref(null)
	function onShowChapterList(){
		uni.showLoading({
			title:'...',
		})
		unLockChapterList.value =[]
		tools.get_book_un_lock_list(book_data.book_id,(list)=>{
			if(list!=null){
				unLockChapterList.value = list
				showChapterList.value = true
			}else{
				uni.showToast({
					title:'加载错误',
					icon:'none'
				})
			}
			uni.hideLoading()
		})
	}
</script>

<style scoped lang="scss">
	.color-bg{
	  // position: relative; /* 或者使用 fixed/absolute，根据需要调整 */
	  width: 100vw;
	  // height: 100vh; /* 视口高度 */
	  // overflow: hidden; /* 隐藏超出容器的内容，如果需要的话 */
	  // height: 100%;
	  overflow-y: auto;
	}
	.content {
	  /* 内容组件的样式 */
	  position: relative; /* 相对于 page-container 定位 */
	  z-index: 1; /* 确保内容在背景之上 */
	  /* 其他样式... */
	}
	
	.scroll-container {
		// position: relative; /* 或者使用 fixed/absolute，根据需要调整 */
		width: 100vw;
		// height: 100vh; /* 视口高度 */
		// overflow: hidden; /* 隐藏超出容器的内容，如果需要的话 */
		// height: 100%;
		overflow-y: auto;
	    scrollbar-width: none; /* Firefox */
	    -ms-overflow-style: none; /* IE 10+ */
	}
	
	/* 针对Chrome, Safari和Opera等Webkit浏览器 */
	.scroll-container::-webkit-scrollbar {
	    width: 0;
	    height: 0;
	}
	
	/* 隐藏水平滚动条 */
	.scroll-container::-webkit-scrollbar {
	    width: 0;
	    height: 0;
	}
	 
	/* 隐藏垂直滚动条 */
	.scroll-container::-webkit-scrollbar {
	    width: 0;
	    height: 0;
	}
	 
	/* 同时隐藏水平和垂直滚动条 */
	.scroll-container::-webkit-scrollbar {
	    width: 0;
	    height: 0;
	}
</style>