import { config } from "../config/config";
import { book_item_data, chapter_item_data, user_data } from "../data/data";
import { BookshelfManager } from "../stores/bookshelfManager";
import { ReadHistoryManager } from "../stores/readHistoryManager";
import { ReadSetting } from "../stores/readSetting";
import { ReadRecord } from "../stores/readRecordManager";
import { UserData } from "../stores/userDataManager";
import { UserStatus } from "../stores/userStatusManager";
import { http } from "./http";
import { log } from "./log";
import { sdkUtil } from "./sdkUtil";
import { util } from "./util";

export class tools {
	public static platform:string = config.Platform.H5
	public static initPlatform(){
		// #ifdef  MP-WEIXIN
			config.applet_id = config.applet_id_config.wx
			tools.platform = config.Platform.WEIXIN
		// #endif
		
		// #ifdef  MP-TOUTIAO
			config.applet_id = config.applet_id_config.dy
			tools.platform = config.Platform.TOUTIAO
		// #endif
				
		log.Debug("当前运行平台：",tools.platform)
	}
	// 获取当前平台
	public static getCurPlatform(){
		return tools.platform
	}
	// 获取平台标识
	public static getPlatformID():string {
		let id = 'browser'
		switch (tools.getCurPlatform()){
			case config.Platform.WEIXIN:
			    id = 'wx'
				break;
			case config.Platform.TOUTIAO:
			    id = 'douyin'
				break;
			default:
				break;
		}
		return id
	}
	
	// 请求获取用户open_id
	private static requestGetUserOpenId(cb:Function) {
		sdkUtil.login((res:any)=>{
			if(res!=null) {
				let url = ''
				switch (tools.getCurPlatform()){
					case config.Platform.TOUTIAO:
					    url = config.url_confg.Dynamic.user_get_douyin_openid
						break;
					case config.Platform.WEIXIN:
					    url = config.url_confg.Dynamic.user_get_wx_open_id
						break;
					default:
						break;
				}
				http.DynamicRequest(url,res,(err,data)=>{
					if(!err) {
						if(data.code==config.url_confg.StatesCode.SUCCESS){
							cb && cb(data.content.openid)
						}
					}
				})
			} else {
				cb && cb('browser_123')
			}
		})
	}
	
	// 登录
	public static requestLogin(cb:Function=null) {
		tools.requestGetUserOpenId((open_id:string)=>{
			let opt = {'open_id':open_id, 'platform':tools.getPlatformID()}
			http.DynamicRequest(config.url_confg.Dynamic.user_login,opt, (err,data)=>{
				if(!err) {
					if(data.code==config.url_confg.StatesCode.SUCCESS){
						console.log('登录成功=',data)
						UserData().updateUserData(data.content)
						uni.$emit(config.EVENT_TYPE.USER_LOGIN_SUCCESS)
						cb && cb()
					} else{
						console.log('登录失败=',data)
					}
				} else {
					log.Error(err)
				}
			})
		})
	}
		
	// 进入书详情
	public static value_gotoBookdetails_data = null
	public static gotoBookdetails(book_id:number, cb:Function=null) {
		if(book_id) {
			tools.value_gotoBookdetails_data = {'book_id':book_id}
			uni.navigateTo({
				url:'/pagesA/bookdetails/bookdetails',
				success: (res) => {
					// res.eventChannel.emit('data',{'book_id':book_id}) 废弃
					cb && cb()					
				}
			})
		} else {
			log.Error('书详情id错误')
		}
	}
	
	// 进入查看更多
	public static value_gotoSeeMore_data = null
	public static gotoSeeMore(id:number) {
		if(id) {
			tools.value_gotoSeeMore_data = {'id':id}
			uni.navigateTo({
				url:'/pagesA/seeMore/seeMore'
			})
		} else {
			log.Error('查看更多id错误')
		}
	}
	
	// 进入webview
	public static value_gotoWebview = null
	public static gotoWebview(title:string, html:string) {
		if(html) {
			tools.value_gotoWebview = {'title':title,'html':html}
			uni.navigateTo({
				url:'/pagesA/webview/webview'
			})
		} else {
			log.Error('进入webview链接错误')
		}
	}
	
	// 进入阅读
	public static gotoRead(book_data:book_item_data, chapter_id:number=-1) {
		// console.log('book_data=',book_data)
		// 获取上次开始阅读章节id
		if(chapter_id==-1) {
			let read_record_data = ReadRecord().getReadRecordData(book_data.book_id)
			if(read_record_data) {
				book_data.start_read_chapter_id = read_record_data.chapter_id
			} else {
				book_data.start_read_chapter_id = 1
			}
			console.log('开始阅读-获取上次章节id=',book_data.start_read_chapter_id)
		} else {
			book_data.start_read_chapter_id = chapter_id
			console.log('开始阅读-指定章节id=',chapter_id)
		}
				
		// 更新用户选择书
		UserStatus().updateUserSelectBook(book_data)
		// 更新阅读历史
		tools.updateReadHistory(book_data)
		// 跳转
		uni.navigateTo({
			url:'/pagesA/readbook/read'
		})
	}
	
	// 退出阅读
	public static exitRead() {
		let book_data = UserStatus().getUserSelectBook()
		// 更新:书架,读到当前章节数据
		uni.$emit(config.EVENT_TYPE.UPDATE_BOOKSHELF_CURRENT_READ_CHAPTER,book_data)
	}
	
	// 获取用户信息
	public static getUserData():user_data {
		return UserData().getData()
	}
	
	// 获取用户是否VIP
	public static getUserIsVIP():boolean {
		return tools.getUserData().is_vip
	}
	
	// 获取请求书架参数
	public static getRequestBookshelfParameter(book_data:book_item_data) {
		let book_opt = {
			'book_id':book_data.book_id,
			'start_read_chapter_id':book_data.start_read_chapter_id}
		return book_opt
	}
	
	/*
	 * 请求书架
	 * books_shelf: json
	 * stype: int  类型 1:获取 2:同步书架
	 */
	public static requestBookShelf(book_list:book_item_data[], stype:number, successs_cb:Function, falil_cb:Function) {
		let books_shelf_string = ''
		if(book_list.length>0) {
			books_shelf_string = JSON.stringify(book_list)
		}
		let opt = {'books_shelf':books_shelf_string, 'stype':stype}
		http.DynamicRequest(config.url_confg.Dynamic.books_shelf, opt, (err,data)=>{
			// console.log('err=',err,'data=',data)
			if(!err) {
				if(data.code==config.url_confg.StatesCode.SUCCESS){
					successs_cb && successs_cb(data.content)
				} else {
					falil_cb && falil_cb()
				}
			} else {
				log.Error(err)
				falil_cb && falil_cb()
			}
		})
	}
	
	// 获取本地书架列表
	public static getLocalBookshelfList():book_item_data[] {
		return BookshelfManager.getBookList()
	}
		
	// 保存本地书架列表
	public static saveLocalBookshelfList() {
		BookshelfManager.saveLocalBookList()
	}
	
	// 检查在书架(异步)
	public static checkBookOnBookshelf(book_id:number, cb:Function) {
		BookshelfManager.checkBookOnBookshelf(book_id, (is_on:boolean)=>{
			cb && cb(is_on)
		})
	}
	
	// 检查在书架(同步)
	public static syncCheckBookOnBookshelf(book_id:number):boolean {
		return BookshelfManager.syncCheckBookOnBookshelf(book_id)
	}
	
	// 添加书架
	public static addBookshelf(book_data:book_item_data, cb:Function=null) {
		util.showLoading('加载中...', true)
		// 获取阅读记录
		let record_data = ReadRecord().getReadRecordData(book_data.book_id)
		if(record_data) {
			book_data.start_read_chapter_id = record_data.chapter_id
		} else {
			if(!book_data.start_read_chapter_id) {
				book_data.start_read_chapter_id = 1
			}
		}
		// 本地添加书
		BookshelfManager.addBook(book_data)
		// 请求
		let data_list = []
		for (let i = 0; i < BookshelfManager.getBookList().length; i++) {
			let element = BookshelfManager.getBookList()[i]
			data_list.push(tools.getRequestBookshelfParameter(element))
		}
		tools.requestBookShelf(data_list,2,()=>{
			console.log('同步书架(加入)-成功')
			util.hideLoading()
			uni.$emit(config.EVENT_TYPE.UPDATE_BOOKSHELF)
			cb && cb()
		},()=>{
			util.hideLoading()
		})
	}
	
	// 删除书架
	public static deleteBookshelf(book_id_list:number[], cb:Function=null) {
		util.showModal('删除?', `从书架删除这${book_id_list.length}本书?`, ()=>{
			util.showLoading('移除书架...', true)
			// 本地删除书
			BookshelfManager.deleteBook(book_id_list)
			// 请求
			let data_list = []
			for (let i = 0; i < book_id_list.length; i++) {
				let book_id = book_id_list[i]
				let book_data = new book_item_data()
				book_data.book_id = book_id
				book_data.start_read_chapter_id = 1
				data_list.push(tools.getRequestBookshelfParameter(book_data))
			}
			// 本地阅读记录删除
			ReadRecord().deleteReadRecordData(book_id_list)
			// 请求
			tools.requestBookShelf(data_list,2,()=>{
				console.log('同步书架(删除)-成功')
				util.hideLoading()
				uni.$emit(config.EVENT_TYPE.UPDATE_BOOKSHELF)
				cb && cb()
			},()=>{
				util.hideLoading()
			})
		})
	}
	
	// 重置排序书架
	public static resetSortBookshelf(book_list:book_item_data[]) {
		BookshelfManager.resetData(book_list)
	}
	
	// 获取本地阅读历史列表
	public static getLocalReadHistoryList():book_item_data[] {
		return ReadHistoryManager.getBookList()
	}
	
	// 更新阅读历史
	public static updateReadHistory(book_data:book_item_data) {
		ReadHistoryManager.addBook(book_data, ()=>{
			uni.$emit(config.EVENT_TYPE.UPDATE_READHISTORY)
		})
	}
	
	// 删除阅读历史
	public static deleteReadHistory(book_id_list:number[]) {
		ReadHistoryManager.deleteBook(book_id_list)
	}
    
	// 重置排序阅读历史
	public static resetSortReadHistory(book_list:book_item_data[]) {
		ReadHistoryManager.resetData(book_list)
	}
	
	public static getChapterList(chapter_path:string,cb:Function){
		let url = `${config.url_addr.Static}${chapter_path}`
		http.StaticRequest(url,(err,data)=>{
			if(err){
				return
			}
			cb(data)
		})
	}
	
	public static getCurChapterTxt(base_path:string,chapter_id:number,emspWidth:number,cb:Function){
		if(chapter_id){
			let url = `${config.url_addr.Static}${base_path}${chapter_id}.txt`
			http.getStaticText(url,(err,data)=>{
				if(err){
					log.Error(err)
					return
				}
				// log.Debug("getCurChapterTxt",data)
				cb(tools.autoParagraph(data,emspWidth))
				// cb(data)
			})	
		}

	}
	
	
	public static autoParagraph(text:string,emspWidth:number) {
		const emspStyle = `style="margin-left: ${emspWidth}px;"`; 
		const emsp_html = `<span ${emspStyle}></span>`;
		const character =  `<br><br>${emsp_html}`;
		return  emsp_html+text.replace(/\n\s*/g,character)
	}
	
	public static autoParagraphTitle(text:string,emspWidth:number) {
		const emspStyle = `style="margin-left: ${emspWidth}px;"`; 
		const emsp_html = `<span ${emspStyle}></span>`;
		return  `<br><br>`+emsp_html+text
	}
	
	public static getChapter(cur_chapter_id:number,list:chapter_item_data[]){
		return list.find(chapter_data=>cur_chapter_id==chapter_data.id)
	}
	
	public static getPreChapterData(index:number,list:chapter_item_data[]){
		let new_index = index -1 
		if( new_index <0 ){
			return null
		}
		return list[new_index]
	}
	
	public static getCurChapterData(index:number,list:chapter_item_data[]):chapter_item_data{
		if(index<list.length&&index>=0){
			return list[index]
		}
		log.Error("getCurChapterData error ",index)
		return null
	}
	
	
	public static getNextChapterData(index:number,list:chapter_item_data[]){
		let new_index = index +1
		if( new_index >=list.length ){
			return null
		}
		return list[new_index]
	}
	
	public static getCurChapterIndex(chapter_id:number,list:chapter_item_data[]){
		return list.findIndex(chapter_data=>chapter_id==chapter_data.id)
	}
	
	public static getFontColorByMode(mode:number){
		if(mode==config.read_config.readMode.Bright){
			return config.read_config.BrightFontColor
		}else{
			return config.read_config.DarkFontColor
		}
	}
	
	public static getDbColorByMode(mode:number){
		if(mode==config.read_config.readMode.Bright){
			return config.read_config.BrightDbColor
		}else{
			return config.read_config.DarkDbColor
		}
	}
	
	public static book_status_title(book_data:book_item_data){
		if(book_data.book_is_action==1){
			return `连载至 第${book_data.chapter_count}章`
		}else{
			return `已完结 共${book_data.chapter_count}章`
		}
	}
	
	public static check_book_chapter_is_buy(book_id:number,chapter_id:number,cb:Function){
		http.DynamicRequest(config.url_confg.Dynamic.get_user_chapter_ids,{'book_id':book_id},(err,d)=>{
			if(d.code==config.url_confg.StatesCode.SUCCESS){
				cb(d.content.includes(chapter_id))
			}else{
				cb(false)
			}
		})
	}
	
	public static get_book_un_lock_list(book_id:number,cb:Function){
		http.DynamicRequest(config.url_confg.Dynamic.get_user_chapter_ids,{'book_id':book_id},(err,d)=>{
			if(d.code==config.url_confg.StatesCode.SUCCESS){
				cb(d.content)
			}else{
				cb(null)
			}
		})
	}
	
	public static getCurBuyType(){
		let type = config.pay_type.NEI_BU;
		// switch (tools.getCurPlatform()){
		// 	case config.Platform.WEIXIN:
		// 		type = config.pay_type.WEI_XIN
		// 		break;
		// 	case config.Platform.TOUTIAO:
		// 		type = config.pay_type.DOU_YIN
		// 		break;
		// 	default:
		// 		break;
		// }
		return type
	}
	
	public static getBgResByIndex(index:number,select_index:number){
		if(ReadSetting().getReadSetting().readMode==config.read_config.readMode.Dark){
			return config.read_config.colorBgResList[index].off_res
		}
		if(index==select_index){
			return config.read_config.colorBgResList[index].on_res
		}
		return config.read_config.colorBgResList[index].off_res
	}
	
	// 下单(支付类型 1:抖音支付 2:微信支付 3:内部充值(内部测试))
	public static requestRechargeOrderBuy(pay_type:number, goods_id:number, cb:Function) {
		let opt = {'pay_type':pay_type,'goods_id':goods_id}
		http.DynamicRequest(config.url_confg.Dynamic.recharge.order_buy,opt,(err=null,data=null)=>{
			log.Debug('下单  data=',data,'err=',err)
			if(!err&&data) {
				if(data.code==config.url_confg.StatesCode.SUCCESS){
					let order_id = data.content.order_id
					cb && cb(order_id)
				} else {
					cb && cb('')
				}
			} else {
				cb && cb('')
			}
		})
	}
	
	// 查询订单
	public static requestRechargeOrderInfo(order_id:string, cb:Function) {
		let opt = {'order_id':order_id}
		http.DynamicRequest(config.url_confg.Dynamic.recharge.order_info,opt,(err=null,data=null)=>{
			log.Debug('查询订单  data=',data,'err=',err)
			if(!err&&data) {
				if(data.code==config.url_confg.StatesCode.SUCCESS){
					let status = data.content.status //订单状态 1:支付中 2:已经支付
					cb && cb(status)
				} else {
					cb && cb(-1)
				}
			} else {
				cb && cb(-1)
			}
		})
	}
}