import {
	asyncCallNetworkApiGet,
	jumpToLogin,
} from "../script/util";
import { MyCocosSceneComponent_NJ_usercenter } from "../script/MyCocosSceneComponent_NJ_usercenter";

const { ccclass, property } = cc._decorator;
const AUTH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwicGhvbmUiOiIxNTUwMDAwMDAwMiIsInNpZ24iOiI1ODUxYjVkMS1lYzIwLTQzN2ItOGM3ZS1mYjM3YmExZGI2MWYiLCJ1bmlfc2lnbiI6ImI4MThlODg0LTFkNjgtNGRhYy05NDRjLTQyMjYwMTU1NTc5YyIsImlhdCI6MTY3Mzk0MTM2MSwiZXhwIjoxNjc2NTMzMzYxfQ.eFkRVqof15WOyi_jFgFOg7ym5QMV76t-1ZwupxfX_lg"
@ccclass
export default class SceneComponent extends MyCocosSceneComponent_NJ_usercenter {

	@property(cc.SpriteFrame)
	picture: Array<cc.SpriteFrame> = [];


	addPreloadImage() {
	}

	addPreloadAudio() {
	}

	addPreloadAnima() {

	}

	async onLoadEnd() {
		this.initData();
		await this.initUserInfo();
		await this.initPartInfo();
		await this.initSpeakInfo();
		await this.initKnowledgeInfo();
		await this.drawChart();
		await this.drawLearnProcess();
		this.initBg();
		this.initListener();
	}

	token = null;
	initData() {
		const middleLayer = cc.find('middleLayer');
		if (!middleLayer) {
			cc.sys.localStorage.setItem('token', AUTH_TOKEN);
		}
		this.token = cc.sys.localStorage.getItem("token");
	}


	getFomartDate() {
		const date = new Date();
		date.setDate(date.getDate() - date.getDay() + 1);
		const monday = date["pattern"]("MM.dd");
		date.setDate(date.getDate() + 6);
		const sunday = date["pattern"]("MM.dd");
		return `${monday} - ${sunday}`;
	}

	userInfo = null;
	async initUserInfo() {
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/info", { token: this.token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const userInfo = resObj.data;
		cc.sys.localStorage.setItem('userInfo', JSON.stringify(userInfo));
		this.userInfo = userInfo;
		const avatarIndex = userInfo.avatar_url ? parseInt(userInfo.avatar_url) - 1 : 0;
		const usercenter = cc.find("Canvas/usercenter/view/content/scollpage/user_center");
		// 头像
		cc.find("avatar", usercenter).getComponent(cc.Sprite).spriteFrame = this.picture[avatarIndex];
		cc.find("Canvas/reportdetail/view/content/userdetail_scollpage/learnshow/avatarbg/avatar").getComponent(cc.Sprite).spriteFrame = this.picture[avatarIndex];
		// 昵称
		cc.find("nickname", usercenter).getComponent(cc.Label).string = userInfo.nick_name || "拼读达人";
		cc.find("Canvas/learnreport/nick_name").getComponent(cc.Label).string = userInfo.nick_name || "拼读达人";
		cc.find("Canvas/reportdetail/view/content/userdetail_scollpage/learnshow/avatarbg/namebg/nickname").getComponent(cc.Label).string = userInfo.nick_name || "拼读达人";
		// 日历牌
		cc.find("learndate", usercenter).getComponent(cc.Label).string = this.getFomartDate();
		// 当前学习进度
		if (userInfo.last_game_str){
			const gameNames = userInfo.last_game_str.split("~!");
			cc.find("Canvas/usercenter/view/content/scollpage/learning").getComponent(cc.RichText).string = `<color=#138977>当前正在学习</c>  <color=#ef8d36>${gameNames[0]} - ${gameNames[1]}</color>`;
		}
	}

	// 学习小节
	partCount = 0;
	// 本周学习小节
	partWeekCount = 0;
	async initPartInfo() {
		if (!this.userInfo) {
			return;
		}
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/part/count", { kidid: this.userInfo.id, token: this.token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const partInfo = resObj.data;
		if (partInfo) {
			this.partWeekCount = partInfo.weekcount;
			this.partCount = partInfo.count;
		}
		const usercenter = cc.find("Canvas/usercenter/view/content/scollpage/user_center");
		cc.find("learndesc", usercenter).getComponent(cc.RichText).string = `<color=#ae441c>本周已经学习</c> <color=#41916e><size=60>${this.partWeekCount}</size></color> <color=#ae441c>个小节</color>`;

		const smallbg_1_left = cc.find("Canvas/usercenter/view/content/scollpage/smallbg_1_left");
		cc.find("smtextbg/partcount", smallbg_1_left).getComponent(cc.Label).string = this.partCount + "";
		cc.find("numberbg/weekpartcount", smallbg_1_left).getComponent(cc.Label).string = "+" + this.partWeekCount;
	}

	// 开口次数
	speakCount = 0;
	// 本周开口次数
	speakWeekCount = 0;
	async initSpeakInfo() {
		if (!this.userInfo) {
			return;
		}
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/record/count", { kidid: this.userInfo.id, token: this.token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const speakInfo = resObj.data;
		if (speakInfo) {
			this.speakWeekCount = speakInfo.weekcount;
			this.speakCount = speakInfo.count;
		}

		const smallbg_1_right = cc.find("Canvas/usercenter/view/content/scollpage/smallbg_1_right");
		cc.find("smtextbg/partcount", smallbg_1_right).getComponent(cc.Label).string = this.speakCount + "";
		cc.find("numberbg/weekpartcount", smallbg_1_right).getComponent(cc.Label).string = "+" + this.speakWeekCount;
	}

	lettercount = 0;
	wordcount = 0;
	sentencecount = 0;
	async initKnowledgeInfo() {
		if (!this.userInfo) {
			return;
		}
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/knowledge/count", { kidid: this.userInfo.id, token: this.token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const knowledgeInfo = resObj.data;
		if (knowledgeInfo) {
			this.lettercount = knowledgeInfo.lettercount || 0;
			this.wordcount = knowledgeInfo.wordcount || 0;
			this.sentencecount = knowledgeInfo.sentencecount || 0;
		}

		const smallbg_2_left = cc.find("Canvas/usercenter/view/content/scollpage/smallbg_2_left");
		const smallbg_2_middle = cc.find("Canvas/usercenter/view/content/scollpage/smallbg_2_middle");
		const smallbg_2_right = cc.find("Canvas/usercenter/view/content/scollpage/smallbg_2_right");
		cc.find("lettercount", smallbg_2_left).getComponent(cc.RichText).string = `<color=#41954F>${this.lettercount}</c> <color=#726E6F><size=30>个</size></c>`;
		cc.find("wordcount", smallbg_2_middle).getComponent(cc.RichText).string = `<color=#41954F>${this.wordcount}</c> <color=#726E6F><size=30>个</size></c>`;
		cc.find("sentencecount", smallbg_2_right).getComponent(cc.RichText).string = `<color=#41954F>${this.sentencecount}</c> <color=#726E6F><size=30>个</size></c>`;
	}

	learntimes = [0, 0, 0, 0, 0, 0, 0];
	learntotal = 0;
	average = 0;
	async drawChart() {
		if (!this.userInfo) {
			return;
		}
		
		const res: any = await asyncCallNetworkApiGet("/api/oxford/v1/kid/learn/chart", { kidid: this.userInfo.id, token: this.token });
		const resObj = JSON.parse(res);
		if (resObj.code !== 200) {
			jumpToLogin();
      return;
    }	
		const chartInfo = resObj.data;
		if (chartInfo) {
			this.learntimes = chartInfo.learntimes;
			this.learntotal = chartInfo.learntotal;
			this.average = chartInfo.average;
		}
		const linebg = cc.find("Canvas/usercenter/view/content/scollpage/linebg");
		cc.find("textbg/desc", linebg).getComponent(cc.RichText).string = `<color=#726E6F>累计学习时长</c><color=#41954F><size=30> ${this.learntotal} </size></c><color=#726E6F>分钟</c>，<color=#726E6F>平均每日学习</c><color=#41954F><size=30> ${this.average} </size></c><color=#726E6F>分钟</c>`;

		// 清理之前的点
		for (let i = 1; i < 8; i++) {
			const beforeDot = cc.find(`dot_${i}`, linebg);
			if(beforeDot) {
				linebg.removeChild(beforeDot);
			}
		}

		const dotHide = cc.find("dothide", linebg);

		const xAxis = cc.find("xline", linebg);
		const line2 = cc.find("line2", linebg);

		const baseY = xAxis.y;
		const maxY = line2.y;

		const chart_line = cc.find(`chart_line`, linebg).getComponent(cc.Graphics);
		const max = Math.max(...this.learntimes);
		const itemLen = max ? (maxY - baseY) / max : 0;
		if (max) {
			cc.find(`dp8/hafy`, linebg).getComponent(cc.Label).string = Math.floor(max / 2) + "";
			cc.find(`dp9/max`, linebg).getComponent(cc.Label).string = max + "";
		}

		// 渲染刻度
		const date = new Date();
		let monthNum;
		for (let i = 1; i < 8; i++) {
			const index = i;
			const value = this.learntimes[i - 1];
			let day = date.getDay()==0 ? 7 : date.getDay();
			date.setDate(date.getDate() - day + index);
			const xNode = cc.find(`dp${index}/date${index}`, linebg);
			const dateStr = date["pattern"]("M月d日");
			if (dateStr.split("月")[0] != monthNum) {
				monthNum = dateStr.split("月")[0];
				xNode.getComponent(cc.Label).string = dateStr;
			} else {
				xNode.getComponent(cc.Label).string = date["pattern"]("d");
			}
			const today = new Date();
			if (today["pattern"]("d") == date["pattern"]("d")) {
				xNode.getComponent(cc.Label).string = "今天";
			}
			if (i == 1) {
				chart_line.moveTo(xNode.parent.x, itemLen * value + baseY);
			} else {
				chart_line.lineTo(xNode.parent.x, itemLen * value + baseY);
			}
			const dotClone = cc.instantiate(dotHide);
			dotClone.parent = linebg;
			dotClone.name = `dot_${i}`;
			cc.find("pop/text", dotClone).getComponent(cc.Label).string = `${value}分钟`;
			dotClone.setPosition(xNode.parent.x, itemLen * value + baseY);
			dotClone.active = true;
		}
		chart_line.stroke();
	}


	async drawLearnProcess() {
		if (!this.userInfo) {
			return;
		}

		const draw = async (type) => {
			const pdtd: any = await asyncCallNetworkApiGet(`/api/oxford/v1/kid/learn/${type}/process`, { kidid: this.userInfo.id, token: this.token });
			const resObj = JSON.parse(pdtd);
			if (resObj.code !== 200) {
				jumpToLogin();
				return;
			}	
			const resProcess = resObj.data;
			const typeNode = cc.find(`Canvas/usercenter/view/content/scollpage/${type}_node/typebg`);
			// 现在规定死5个级别
			for (let i = 1; i <= 5; i++) {
				const prcss = resProcess[i-1];
				if(prcss) {
					cc.find(`L${i}/percent`, typeNode).getComponent(cc.Label).string = prcss.process + "%";
					const maxLen = cc.find(`L${i}`, typeNode).width
					cc.find(`L${i}/processlan`, typeNode).width = Math.floor(maxLen * prcss.process / 100);
				}else {
					cc.find(`L${i}/percent`, typeNode).getComponent(cc.Label).string = "0%";
					cc.find(`L${i}/processlan`, typeNode).width = 0;
				}
			}
		}
		// 拼读天地
		await draw("pdtd");
		// 趣问趣答
		await draw("qwqd");
		// 阅读加油站
		await draw("ydjyz");

	}



	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;

		// 设置界面大小
		const arr = cc.find(`Canvas/usercenter/view/content/scollpage`).children.filter(item => item.active===true);
		const lastNode = arr[arr.length-1];
		cc.find(`Canvas/usercenter/view/content`).height = Math.abs(lastNode.y) + 400;
		cc.find(`Canvas/usercenter/view/content/scollpage`).height = Math.abs(lastNode.y) + 400;
		cc.find(`Canvas/usercenter/view/content/scollpage/bg`).height = Math.abs(lastNode.y) + 400;
	}

	initListener() {
		
	}

	update (dt) {

	}
	
}
