import { Main } from './output';
import {
	checkShopFavoredStatus,
	commonToast,
	favorShop,
	getAuthUserInfo,
	getUserAddress,
	openDetail,
	playBgMusic,
	reportAnalytics
} from '../../utils/utils';

//这种方式/表示client下面的路径
import { getSystemInfo } from '/utils/utils';

//检查版本号
const checkSystem = async () => {
	const { version } = await getSystemInfo();
	console.log('version', version);
	return versionCompare(version, '9.10.0');
}
//对比版本号
const versionCompare = (cur, compare) => {
	const _cur = cur.split('.');
	const _compare = compare.split('.');
	if (+_cur[0] < +_compare[0]) {
		return false;
	} else if (+_cur[0] === +_compare[0] && +_cur[1] < +_compare[1]) {
		return false;
	} else if (+_cur[0] === +_compare[0] && +_cur[1] === +_compare[1] && +_cur[2] < +_compare[2]) {
		return false;
	}
	return true;
}

/**
 * 直接取，app
 */
const app = getApp()
/**
 * 分享信息
 */
const SHARE_CONFIG = {//待写
	title: 'babycare欢乐城！',
	desc: '赢TF彩妆礼盒',
	imageUrl: "https://yun.duiba.com.cn/db_games/activity/pacman/share.jpg",
	path: 'pages/index/index'
}

Page({
	//暂时先不用吧，有问题
	data: {},
	onLoad(query) {
		// 页面加载
		console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
		//带参数的取链接参数
		if (query.inviteId) this.inviteId = query.inviteId;
		//版本提示
		checkSystem().then(r => {
			if (!r) {
				my.showToast({
					content: "请升级最新版本的淘宝体验",
					duration: 5000
				});
			}
		});
	},
	onReady() {
	},

	onCanvasReady() {
		console.log("进canvas了")
		//版本检查
		checkSystem().then(r => {
			if (r) {//检查通过开始授权
				this.getAuth();
			}
		});
	},
	//创建引入的Main
	createMain() {
		var self = this;
		my.createCanvas({
			id: 'canvas',
			success: (ccc) => {
				const dpr = my.getSystemInfoSync().pixelRatio
				const windowWidth = my.getSystemInfoSync().windowWidth;
				const windowHeight = my.getSystemInfoSync().windowHeight;
				ccc.width = windowWidth * dpr + dpr;//重新修改会有误差
				ccc.height = windowHeight * dpr + dpr;
				// console.log(Main)
				console.log(ccc.width, ccc.height)
				if (!this.main) {
					try {
						this.main = new Main(ccc)
						//添加事件，为了和main里的通信
						this.main.addGlobalEvent("onMessage", self.onMessage, self)
					} catch (err) {
						console.error(err)
					}
				}
			}
		})
	},
	//授权
	async getAuth() {
		const userInfo = await getAuthUserInfo().catch(() => {
			commonToast('未授权成功');
			this.postMessage('mine.authorize', { success: false })
		})
		//未授权成功不进入活动
		if (!userInfo) return
		const { nickName, avatar } = userInfo
		app.nickName = nickName;
		app.avatar = avatar;
		//检查是否关注的
		const isFollow = await checkShopFavoredStatus(app.sellerId).catch(() => {
		})
		app.isFollow = isFollow;//app上也挂一个

		const { function: fc } = app.cloud
		//登录的接口，到时用
		fc.invoke(
			app.cloudName,//可以写自己的
			{
				"avatar": avatar,
				"userNick": nickName,
				"activityId": app.activityId,
				"inviteId": this.inviteId,
				"isFollow": isFollow
			},
			"login"
		).then(async res => {//登录完才显示页面
			app.openId = res.data.openId
			app.isFirstLogin = res.data.isFirstLogin;
			app.loginAddPower = res.data.loginAddPower;
			app.isNewUser = res.data.isNewUser;

			// 创建Main，授权登录完后才创建
			this.createMain()
			// 后续可以通过getAppData接口获取信息了
			// this.postMessage('mine.authorize', { success: true });
		});

		//分享图片，TODO，注释打开替换
		const result1 = await app.cloud.file.getTempFileURL({ fileId: 'cloud://2D60DC04FC1888AF6F865B88F0B2EBCC//share.png' });
		if (result1[0]) SHARE_CONFIG.imageUrl = result1[0].url
		//音乐路径
		const resultSrc = await app.cloud.file.getTempFileURL({ fileId: 'cloud://293F2E7D0C6799617660563A322DEE55//bgm_babycare.mp3' });
		if (resultSrc[0]) this.musicUrl = resultSrc[0].url;
	},
	/**
	 * 获取及选择用户收货地址
	 * @param {*} prizeId
	 */
	async getUserAddress(prizeId) {
		const userAddress = await getUserAddress().catch(res => {
			commonToast(res.errorMessage)
			this.postMessage('mine.getUserAddress', { success: false })
		})
		if (userAddress) {//格式需要修改具体
			const { name, phone, address } = userAddress.duibaAddress
			const { provinceName, cityName, countyName } = userAddress;
			my.confirm({
				title: '提示',
				content: '确认使用该收货地址：' + name + phone + address,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				success: (result) => {
					const { confirm } = result
					if (confirm) {
						//发接口提交地址
						const { cloud, activityId, cloudName } = app
						cloud.function.invoke(cloudName, {//定制
							activityId,
							id: prizeId,
							_id: prizeId,
							// address,
							name,
							phone,
							addressdetail: address,
							provice: provinceName,
							city: cityName,
							area: countyName,
							// address: JSON.stringify(userAddress.duibaAddress)
						}, "receiveObjectPrize")
							.then(res => {
								if (res && res.success) {
									//确认发送成功信息
									this.postMessage('mine.getUserAddress', { success: true })
								} else {
									//新增失败0514
									this.postMessage('mine.getUserAddress', { success: false })
								}
							})
							.catch(() => {
								//新增失败0514
								this.postMessage('mine.getUserAddress', { success: false })
							})
					} else {
						//新增失败0514
						this.postMessage('mine.getUserAddress', { success: false })
					}
				},
			})
		}
	},
	/**
	 * 关注店铺
	 */
	async doFavorShop() {
		const { sellerId } = getApp()
		const success = await favorShop(sellerId).catch(err => {
			// commonToast(err.errorMessage || '活动太火爆，请稍后重试')
			//这个包括用户取消的，所以下面不用判断success了；
			this.postMessage('mine.favorShop', { success: false })
			//  console.log("啊啊啊请问请问")
		})
		// console.log("asdasd",success)
		if (success) {
			this.postMessage('mine.favorShop', { success: true })
		}
		// else {
		//   // console.log("飒飒飒飒大苏打")
		//   this.postMessage('mine.favorShop', { success: false })
		// }
	},
	//和main通信的方法，接收main的信息
	onMessage(e) {
		//接口名字
		let netName = e.data.netName;
		//接口参数
		let parameter = e.data.parameter;
		//暂时发现3个需要用户操作的接口
		//定制的授权
		if (netName == "mine.authorize") {
			this.getAuth()
		}
		//获取地址
		else if (netName == "mine.getUserAddress") {
			this.getUserAddress(parameter.prizeId)
		}
		//关注店铺的操作
		else if (netName == "mine.favorShop") {
			this.doFavorShop()
		}
		//领养名字，有弹框的
		else if (netName == "mine.getAdoptName") {
			this.setData({ "adoptModalVisible": true, type: parameter.type })
		}
		//打开详情页，还有成功失败
		else if (netName == "mine.openDetail") {
			openDetail(parameter.itemId).then(
				() => {
					this.postMessage(netName, { success: true })
				},
				() => {
					this.postMessage(netName, { success: false })
				}
			)
		}

		//前端同步接口
		else if (netName.indexOf("mine") == 0) {
			var data = { success: true }
			switch (netName) {
				case "mine.getAppData"://获取信息
					data = {
						success: true,
						data: {
							activityId: app.activityId,//|| "5e7c40e98564b57d7fb95812",
							nickName: app.nickName,
							avatar: app.avatar,
							openId: app.openId,
							inviteId: this.inviteId,//判断是否要发助力用
							isFollow: app.isFollow,
						}
					}
					break;
				case "mine.navigateToOutside"://跳转小程序外的页面
					my.call("navigateToOutside", {
						url: parameter.url
					}, (res) => {
						// my.alert({ content: "success - " + JSON.stringify(res)})
					})
					console.log(parameter.url)
					break;
				case "mine.navigateTo"://跳转小程序内的页面
					my.navigateTo({
						url: parameter.url
					})
					break;
				case "mine.navigateBack"://返回页面
					my.navigateBack({
						delta: parameter.delta || 1
					})
					break;
				case "mine.showSharePanel"://分享
					//多一个参数
					this.openId = parameter.openId//1是任务分享，2是复活液分享
					my.showSharePanel()
					break;
				case "mine.reportAnalytics":  ////淘宝自定义埋点
					reportAnalytics(parameter.logkey);
					break;
				case "mine.openMusic":  //音频
					playBgMusic(parameter.isOn, this.musicUrl);
					break;
				case "mine.openRankPanel":  //打开排行榜
					this.setData({ "expRankModalVisible": true });
					break;
			}
			// this.webViewContext.postMessage({ netName: netName, data: data })
			this.postMessage(netName, data)
		} else {
			//获取后端接口
			const { function: fc } = app.cloud;
			//处理下带上activityId
			if (!parameter) parameter = {};
			parameter.activityId = app.activityId;
			//netName得分割下
			fc.invoke(netName.split(".")[0], parameter, netName.split(".")[1])
				.then(res => {
					// console.log("返回数据" + JSON.stringify(res));
					//发送消息
					// this.webViewContext.postMessage({ netName: netName, data: res })
					this.postMessage(netName, res || { success: false })
				}, (err) => {
					//网络异常，返回失败
					this.postMessage(netName, { success: false })
				})
		}
	},
	postMessage(netName, data) {
		// this.main.dispatchGlobalEvent(netName, data)
		this.main && this.main.dispatchGlobalEvent({ type: netName }, data)//以防复用事件event串了，就用这种方式
	},
	onShow() {
		// 页面显示
		this.main && this.main.run();
	},
	onHide() {
		// 页面隐藏
		this.main && this.main.pause();
	},
	onUnload() {
		// 页面被关闭
		this.main && this.main.destroy();
	},
	/**
	 * 分享参数处理
	 */
	onShareAppMessage() {
		// 返回自定义分享信息
		// const { activityId, openId } = app
		// 发送分享记录，记录数据用
		// API.getShareId({ activityId });
		let { path, ...rest } = SHARE_CONFIG
		if (this.openId) {
			path = path + '?inviteId=' + this.openId
			this.openId = null//用完清掉
		}
		//生成淘口令携带参数，不做额外判断了，如果投放了带generateMark的链接，后果自负
		// if (this.generateMark) path = path + '?wxMark=wxMark';//暂时去掉
		console.log(path)
		return {
			...rest,
			path
		}
	},
	//鼠标事件
	onMouseEvent(e) {
		if (this.main) this.main.stage.onMouseEvent(e)
	},
});
