import { jumpToLogin, asyncCallNetworkApiGet, getSpriteFrimeByUrl, playAudioByUrl } from "./util";
const { ccclass, property } = cc._decorator;

const levels = {
	pdtd: [],
	qwqd: [],
	ydjyz: [],
};

let reportType = "pdtd";
const reportObj = {
	"pdtd": "拼读天地",
	"qwqd": "趣问趣答",
	"ydjyz": "阅读加油站",
};

@ccclass
export default class NewClass extends cc.Component {

	orgId = 507;

	start() {

	} 
	async loadSyllabusTree() {
		const middleLayer = cc.find('middleLayer');
    if (middleLayer) {
      this.orgId = middleLayer.getComponent('middleLayer').ORG_ID || 507;
    }
		const res: any = await asyncCallNetworkApiGet("/api/syllabus/v1/list", { orgid: this.orgId });
		const rows = JSON.parse(res).rows;
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];
			if (row.name === "拼读天地") {
				levels.pdtd = await this.loadData(row.id);
			}
			if (row.name === "趣问趣答") {
				levels.qwqd = await this.loadData(row.id);
			}
			if (row.name === "阅读加油站") {
				levels.ydjyz = await this.loadData(row.id);
			}
		}
	}

	async loadData(pid) {
		const res: any = await asyncCallNetworkApiGet("/api/syllabus/v1/list", { pid });
		const rows = JSON.parse(res).rows;
		return rows;
	}

	
	userInfo = null;
	// 查看拼读天地详情
	async onClickView(evt, type) {
		const userInfo = cc.sys.localStorage.getItem("userInfo");
		if (!userInfo) {
			this.showTips("用户登录过期");
			this.jumpTo("NJ_login");
			return;
		}
		this.userInfo = JSON.parse(userInfo);
		reportType = type;
		this.showLoading();
		cc.find("Canvas/learnreport").active = true;
		cc.find("Canvas/usercenter").active = false;
		cc.find("Canvas/learnreport/avatar").getComponent(cc.Sprite).spriteFrame = cc.find(`Canvas/avatars/${this.userInfo.avatar_url||1}`).getComponent(cc.Sprite).spriteFrame;
		
		await this.loadSyllabusTree();
		if(reportType === 'pdtd') {
			await this.drawPagePdtd();
		}
		if(reportType === 'qwqd') {
			await this.drawPageQwqd();
		}
		if(reportType === 'ydjyz') {
			await this.drawPageYdjyz();
		}
		this.hideLoading();
	}

	showLoading() {
		const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
			middleLayer.showMask();
		}
	}
	hideLoading() {
		const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
			middleLayer.hideMask();
		}
	}

	async drawPagePdtd() {
		const node = cc.find("Canvas/learnreport");
		cc.find("typeLabel", node).getComponent(cc.Label).string = reportObj[reportType];
		
		// 设置每个级别激活状态（是否显示锁头）
		const levelIds = levels[reportType].map(item => item.id);
		const unLocks = this.getUnlockSyllabuses();
		for (let i = 1; i < 5; i++) {
			const id = levelIds[i];
			if (id && unLocks.includes(id+"")) {
				cc.find(`level${i+1}/lock_1`, node).active = false;
			} else {
				cc.find(`level${i+1}/lock_1`, node).active = true;
			}
		}
		// 激活索引为0的Level
		await this.drawPageItems(0);
	}

	async drawPageYdjyz() {
		const node = cc.find("Canvas/learnreport");
		cc.find("typeLabel", node).getComponent(cc.Label).string = reportObj[reportType];
		
		// 设置每个级别激活状态（是否显示锁头）
		for (let i = 1; i < 5; i++) {
			cc.find(`level${i+1}/lock_1`, node).active = false;
		}
		// 激活索引为0的Level
		await this.drawPageItems(0);
	}
	
	async drawPageQwqd() {
		const node = cc.find("Canvas/learnreport");
		cc.find("typeLabel", node).getComponent(cc.Label).string = reportObj[reportType];
		
		// 设置每个级别激活状态（是否显示锁头）
		for (let i = 1; i < 5; i++) {
			cc.find(`level${i+1}/lock_1`, node).active = false;
		}
		// 激活索引为0的Level
		await this.drawPageItems(0);
	}

	clearnContent() {
		const node = cc.find("Canvas/learnreport");
		const contentNode = cc.find("cardArea/pages/view/content", node);
		const item = cc.find("Canvas/learnreport/cardArea/pages/view/content/item");

		// 清理原来的数据
		item.parent = node;
		contentNode.removeAllChildren();
		item.parent = contentNode;
	}
	async drawPageItems(index) {
		const node = cc.find("Canvas/learnreport");
		this.activeLevelIndex(index);
		let rows = [];
		if (levels[reportType][index]) {
			rows = await this.loadData(levels[reportType][index].id);
			rows = rows.filter(item => item.name.trim() !=='more games');
		}
		let unLocks = [];
		if (reportType === 'pdtd') {
			unLocks = this.getUnlockSyllabuses();
		}
		if (reportType === 'ydjyz') {
			// 全都解锁（没有解锁逻辑）
			unLocks = rows.map(item => `${item.id}`);
		}
		if (reportType === 'qwqd') {
			unLocks = this.getUnlockSyllabuses();
		}


		const contentNode = cc.find("cardArea/pages/view/content", node);
		const item = cc.find("Canvas/learnreport/cardArea/pages/view/content/item");

		// 清理原来的数据
		item.parent = node;
		contentNode.removeAllChildren();
		item.parent = contentNode;
		// 绘制
		rows.forEach((row, i) => {
			const itemClone = cc.instantiate(item);
			itemClone.parent = contentNode;
			itemClone.active = true;
			itemClone.attr({folder_id: row.id, locked: true, kidid: this.userInfo.id});
			cc.find(`number`, itemClone).getComponent(cc.Label).string = (i+1)+"";
			if (unLocks.includes(row.id+"") || (index==0 && i==0)) {
				itemClone.attr({folder_id: row.id, locked: false});
				cc.find(`lock`, itemClone).active = false;
				cc.find(`unlock`, itemClone).active = true;
				cc.find(`unlock/text`, itemClone).getComponent(cc.Label).string = row.name;
				getSpriteFrimeByUrl(row.cover, (spriteFrame) => {
					const coverNode = cc.find(`unlock/cover`, itemClone);
					coverNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
					const sx = 70 / coverNode.width;
					const sy = 80 / coverNode.height;
					coverNode.scale = Math.min(sx, sy);
				});
			}
		});
	}

	getUnlockSyllabuses() {
		if(this.userInfo){
			return this.userInfo.unlock_syllabuses?this.userInfo.unlock_syllabuses.split(","):[];
		}
		return [];
	}

	// 激活索引为index的Level
	activeLevelIndex(index) {
		const node = cc.find("Canvas/learnreport");
		for (let i = 0; i < 5; i++) {
			cc.find(`level${i+1}/level_active`, node).active = false;
		}
		cc.find(`level${index+1}/level_active`, node).active = true;
	}

	async onChangeLevel(evt: cc.Event, index) {
		const userInfo = cc.sys.localStorage.getItem("userInfo");
		if (!userInfo) {
			this.showTips("用户登录过期");
			this.jumpTo("NJ_login");
			return;
		}
		this.userInfo = JSON.parse(userInfo);

		const lockedNode = cc.find(`Canvas/learnreport/level${parseInt(index)+1}/lock_1`);
		if (lockedNode && lockedNode.active) {
			return;
		}
		
		this.activeLevelIndex(parseInt(index));
		await this.drawPageItems(parseInt(index));
	}

	clearnDetailItem() {
		const node = cc.find("Canvas/reportdetail");
		const contentNode = cc.find("view/content/userdetail_scollpage/learnresult/itembg", node);
		
		// 清理原来的数据
		// 字母
		const letterRow = cc.find("letter_row", contentNode);
		const letterItem = cc.find("item", letterRow);
		letterItem.parent = node;
		letterRow.removeAllChildren();
		letterItem.parent = letterRow;
		// 单词
		const wordRow = cc.find("word_row", contentNode);
		const wordItem = cc.find("item", wordRow);
		wordItem.parent = node;
		wordRow.removeAllChildren();
		wordItem.parent = wordRow;
		// 句子
		const sentenceRow = cc.find("sentence_row", contentNode);
		const sentenceItem = cc.find("item", sentenceRow);
		sentenceItem.parent = node;
		sentenceRow.removeAllChildren();
		sentenceItem.parent = sentenceRow;

		// 录音
		const tips = cc.find("tips_bg", contentNode);
		const row = cc.find("row", tips);
		row.parent = node;
		tips.removeAllChildren();
		row.parent = tips;
		
		// 趣配音
		const qpyNode = cc.find(`Canvas/reportdetail/view/content/userdetail_scollpage/learnresult/itembg/pyx`);
		for (let i = 0; i < 3; i++) {
			cc.find(`result_bg/star_${i+1}_light`, qpyNode).active = false;
		}
		const label = cc.find(`result_bg/textnode/label`, qpyNode).getComponent(cc.Label);
		label.string = "";

	}

	async onShowLearnDetail(evt: cc.Event) {
		const node = evt.currentTarget;
		if (node.locked) {
			this.showTips("未解锁");
			return;
		}

		// 清除之前渲染的列表
		this.clearnDetailItem();

		cc.find("Canvas/reportdetail").active = true;
		cc.find("Canvas/learnreport").active = false;

		const token = cc.sys.localStorage.getItem("token");
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/learn/forder/report", { kidid: node.kidid, folderid: node.folder_id, token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const {
			learntimes,
			recordcount,
			kn_letters,
			kn_words,
			kn_sentences,
			OP05,
			OP_06_3
		} = resObj.data;

		cc.find("Canvas/reportdetail/view/content/userdetail_scollpage/learnshow/itembg/recordbg/recordcount").getComponent(cc.Label).string = recordcount;
		cc.find("Canvas/reportdetail/view/content/userdetail_scollpage/learnshow/itembg/learnbg/learntime").getComponent(cc.Label).string = learntimes;

		const resultPage = cc.find("Canvas/reportdetail/view/content/userdetail_scollpage/learnresult");
		const resultNode = cc.find("itembg", resultPage);

		if (!kn_letters && !kn_words && !kn_sentences && !OP05 && !OP_06_3) {
			// 没有可以展示的学习成果
			resultPage.active = false;
			return;
		} else {
			resultPage.active = true;
		}
		
		if (kn_letters) {
			cc.find("letter_title", resultNode).active = true;
			cc.find("letter_row", resultNode).active = true;
			cc.find("letter_split_line", resultNode).active = true;

			const letterRow = cc.find("letter_row", resultNode);
			const letterNode = cc.find("item", letterRow);

			const letters = JSON.parse(kn_letters);
			for (let i = 0; i < letters.length; i++) {
				const letter = letters[i];
				const itemClone = cc.instantiate(letterNode);
				itemClone.parent = letterRow;
				itemClone.active = true;
				if (letter.pic_url) {
					itemClone.height = 200;
					getSpriteFrimeByUrl(letter.pic_url, (spriteFrame) => {
						const picNode = cc.find(`pic`, itemClone);
						picNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
						const sx = 400 / picNode.width;
						const sy = 200 / picNode.height;
						picNode.scale = Math.min(sx, sy);
					});
				} else {
					itemClone.height = 45;
					cc.find("pic", itemClone).active = false;
					cc.find("word", itemClone).active = true;
					cc.find("word", itemClone).getComponent(cc.Label).string = letter.text;
				} 
			}
		} else {
			cc.find("letter_title", resultNode).active = false;
			cc.find("letter_row", resultNode).active = false;
			cc.find("letter_split_line", resultNode).active = false;
		}

		if (kn_words) {
			cc.find("word_title", resultNode).active = true;
			cc.find("word_row", resultNode).active = true;
			cc.find("word_split_line", resultNode).active = true;

			const wordRow = cc.find("word_row", resultNode);
			const wordNode = cc.find("item", wordRow);

			const words = JSON.parse(kn_words);
			for (let i = 0; i < words.length; i++) {
				const word = words[i];
				const itemClone = cc.instantiate(wordNode);
				itemClone.parent = wordRow;
				itemClone.active = true;
				if (word.pic_url) {
					itemClone.height = 220;
					getSpriteFrimeByUrl(word.pic_url, (spriteFrame) => {
						const picNode = cc.find(`pic`, itemClone);
						picNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
						const sx = 200 / picNode.width;
						const sy = 179 / picNode.height;
						picNode.scale = Math.min(sx, sy);
					});
					cc.find("word", itemClone).getComponent(cc.Label).string = word.text;
				} else {
					itemClone.height = 45;
					cc.find("pic", itemClone).active = false;
					cc.find("word", itemClone).getComponent(cc.Label).string = word.text;
					cc.find("word", itemClone).y = 0;
				}
			}
		} else {
			cc.find("word_title", resultNode).active = false;
			cc.find("word_row", resultNode).active = false;
			cc.find("word_split_line", resultNode).active = false;
		}

		if (kn_sentences) {
			cc.find("sentence_title", resultNode).active = true;
			cc.find("sentence_row", resultNode).active = true;
			cc.find("sentence_split_line", resultNode).active = true;

			const sentenceRow = cc.find("sentence_row", resultNode);
			const sentenceNode = cc.find("item", sentenceRow);

			const sentences = JSON.parse(kn_sentences);
			for (let i = 0; i < sentences.length; i++) {
				const sentence = sentences[i];
				const itemClone = cc.instantiate(sentenceNode);
				itemClone.parent = sentenceRow;
				itemClone.active = true;
				cc.find("sentence", itemClone).getComponent(cc.Label).string = sentence.text;
			}
		} else {
			cc.find("sentence_title", resultNode).active = false;
			cc.find("sentence_row", resultNode).active = false;
			cc.find("sentence_split_line", resultNode).active = false;
		}

		if (OP05) {
			cc.find("speak_tittle", resultNode).active = true;
			cc.find("tips_bg", resultNode).active = true;
			cc.find("speak_split_line", resultNode).active = true;

			const rowData = JSON.parse(OP05).result;
			const tips = cc.find("tips_bg", resultNode);
			const row = cc.find("row", tips);

			for (let i = 0; i < rowData.length; i++) {
				const {score, audio_url} = rowData[i];
				let word = rowData[i].word;
				if (Array.isArray(word)) {
					word = word.map(item => item.card||"").join("");
				}
				const itemClone = cc.instantiate(row);
				itemClone.parent = tips;
				itemClone.active = true;
				cc.find("item1/word", itemClone).getComponent(cc.Label).string = word;
				cc.find("item3/goodjob", itemClone).active = (score >= 80);
				cc.find("item3/nicetry", itemClone).active = (score < 80);
				cc.find("item2/play_icon", itemClone).attr({audio_url});
			}
		} else {
			cc.find(`Canvas/reportdetail/view/content/userdetail_scollpage/learnresult/itembg/tips_bg/row`).active = false;
			cc.find("speak_tittle", resultNode).active = false;
			cc.find("tips_bg", resultNode).active = false;
			cc.find("speak_split_line", resultNode).active = false;
		}

		const qpyNode = cc.find(`itembg/pyx`, resultPage);
		if (OP_06_3) {
			cc.find(`itembg/pyx_tittle`, resultPage).active = true;
			
			const rowData = JSON.parse(OP_06_3);
			cc.find(`Canvas/videoContainer`).attr({rowData});
			let lightStarCount = 0;
			rowData.item_arr.forEach(row => {
				lightStarCount += row.star_count;
			});
			lightStarCount = Math.floor(lightStarCount / rowData.item_arr.length);
			for (let i = 0; i < lightStarCount; i++) {
				cc.find(`result_bg/star_${i+1}_light`, qpyNode).active = true;
			}
			const label = cc.find(`result_bg/textnode/label`, qpyNode).getComponent(cc.Label);
			if (lightStarCount == 0 || lightStarCount == 1) {
				label.string = `再多听听原声,\n大声录音让我听到,\n争取拿到三颗星！`;
			} else if (lightStarCount == 2) {
				label.string = `宝贝的发音很好哦\n差一点点就完美了~\n多试几次,\n争取拿到三颗星！`;
			} else {
				label.string = `宝贝的发音太好了！\n再接再厉呀！`;
			}
			qpyNode.active = true;	
		} else {
			qpyNode.active = false;			
			cc.find(`itembg/pyx_tittle`, resultPage).active = false;
		}

		// 设置页面高度
		setTimeout(() => {
			const pageHight = cc.find(`itembg`, resultPage).height + Math.abs(resultPage.y);
			cc.find(`Canvas/reportdetail/view/content`).height = pageHight + 100;
			cc.find(`Canvas/reportdetail/view/content/userdetail_scollpage`).height = pageHight + 100;
		}, 1000);
		

	}

	// 播放录音
	async onPlayRecordAudio(evt: cc.Event) {
		const node = evt.currentTarget;
		if (!node.audio_url) {
			this.showTips("录音不存在");
			return;
		}

		const playNode = cc.find("play", node.parent);
		playNode.active = true;
		const animationState = playNode.getComponent(cc.Animation).getAnimationState("play1");
		animationState.wrapMode = cc.WrapMode.Loop;
		animationState.play();
		playAudioByUrl(node.audio_url, () => {
			animationState.stop();
			playNode.active = false;
		})

	}

	showTips(tips) {
		const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
			middleLayer.showTips(tips);
		} else {
			console.log(tips);
		}
	}
	jumpTo(template_name) {
		const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
			middleLayer.loadOnlineBundle(template_name);
		}
	}

	async onClickBackToYouLeChang() {
		this.jumpTo("NJ_YouLeChang");
	}

	// 返回用户中心
	async onClickBackToUserCenter() {
		reportType = null;
		this.clearnContent();
		cc.find("Canvas/usercenter").active = true;
		cc.find("Canvas/learnreport").active = false;
	}

	// 返回报告列表
	async onClickBackToReportPage() {
		cc.find("Canvas/learnreport").active = true;
		cc.find("Canvas/reportdetail").active = false;
	}

	// 播放趣配音视频
	async onClickToPlayVideo() {
		cc.find(`Canvas/videoContainer`).active = true;
		cc.find(`Canvas/bg`).opacity = 0;
		cc.find("Canvas/reportdetail").opacity = 0;
	}


}
