let pageInit = null,
	_Http = getApp().globalData.http,
	{
		vIndate
	} = require("../../utils/pay");


Page({
	data: {
		PageCur: 'Home',
		collectCount: "", //购物车商品数量
		msgList: [],
		favoriteCount: 0, //收藏夹数量
	},
	onLoad(options) {
		pageInit = {
			Home: false,
			Message: false,
			Market: false,
			Collect: false,
			UserCenter: false,
		};
		if (options.PageCur) this.setData({
			PageCur: options.PageCur
		})
		this.refreshData();

		this.getCollectCount();
		this.getFavoriteCount();

		this.updateMsgCount();
		this.getAnnunciate();
		if (getApp().globalData.remindchangepassword_str) wx.showModal({
			title: "提示",
			content: getApp().globalData.remindchangepassword_str,
			confirmText: '前往修改',
			cancelText: "下次再说",
			success: ({
				confirm
			}) => {
				getApp().globalData.remindchangepassword_str = null;
				if (confirm) wx.navigateTo({
					url: '/pages/index/userCenter/changePassword/index',
				})
			},
		})
		getApp().globalData.http.refreshData = this.refreshData.bind(this);
		this.getVIndete();
	},
	getVIndete() {
		if (wx.getStorageSync('siteP').siteid) {
			vIndate();
		} else {
			setTimeout(() => {
				this.getVIndete();
			}, 100)
		}
	},
	getAnnunciate() {
		_Http.basic({
			"id": 20221111090904,
			"content": {
				"nocache": true,
				"pageSize": 1,
				"where": {
					"condition": ""
				}
			}
		}).then(res => {
			console.log("获取一条通告", res)
			if (res.msg == '成功' && res.data.length) this.selectComponent("#Home").setData({
				annunciate: res.data[0]
			})
		})
	},
	onShow() {
		// if (wx.getAccountInfoSync().miniProgram.envVersion !== 'release') this.refreshData();
	},
	/**
	 * 更新站点信息
	 * 主要用来渲染首页的banner和宫格
	 */
	refreshData() {
		getApp().globalData.getCollectCount = this.getCollectCount.bind(this); //更新购物车件数
		getApp().globalData.getFavoriteCount = this.getFavoriteCount.bind(this); //更新收藏夹件数

		getApp().globalData.socketCallback = this.updateMsgCount.bind(this); //更新信息数量
		getApp().globalData.changeBar = this.cutBar.bind(this); //切换首页页面
		let page = this.selectComponent("#Home");
		if (page && wx.getStorageSync('userauth').length != 0) {
			let authList = {},
				entrance = [{
					label: "营销工具",
					icon: "work-yingxiaogongju",
					appid: "wx7505ddb0a1ec6146",
					list: gettool()
				}, {
					label: "E-订单",
					appid: "wx7505ddb0a1ec6146",
					icon: "work-E-dingdan",
					list: getedd()
				}];
			//营销工具
			function gettool() {
				const paths = [{
					name: "通告",
					path: "/marketing/annunciate/index",
					icon: "work-a-shouyejingangqutonggao",
					objectname: "sat_notice"
				}, {
					name: "营销物料",
					path: "/marketing/mediaLibrary/index",
					icon: "work-a-shouyejingangquyingxiaowuliao",
					objectname: "sys_attachment"
				}, {
					name: "推广素材",
					path: "/marketing/promotional/index",
					icon: "work-a-shouyejingangqutuiguangsucai",
					objectname: "sat_sharematerial"
				}, {
					name: "商学院",
					path: "/marketing/college/index",
					icon: "work-a-shangxueyuanxuexi",
					objectname: "sat_courseware"
				}, {
					name: "提报",
					path: "/marketing/submission/index",
					icon: "work-a-tibaoguanlitibao",
					objectname: "sat_submiteditmodel"
				}];
				let tool = getApp().globalData.queryPer.query(wx.getStorageSync('userauth'), ['营销工具'], paths.map(v => v.name)),
					list = [];
				tool.forEach(v => {
					let auth = v.apps[0].meta.auth;
					if (!auth.some(r => r.option == 'read')) return;
					authList[v.apps[0].name] = {
						options: auth.map(a => a.option),
						optionnames: auth.map(a => a.optionname)
					};
					let item = paths.find(s => s.name == v.systemmodulename);
					item && list.push(item)
				});
				return dye(list.sort((a, b) => a.index - b.index))
			};
			//E订单
			function getedd() {
				let paths = [{
					name: "商城",
					key: "wmarket",
					PageCur: "Market",
					icon: "work-shangcheng"
				}, {
					name: "订货单",
					key: "worderform",
					path: "/packageA/orderForm/index",
					icon: "work-dingdan"
				}, {
					name: "订单明细",
					key: "worderdetails",
					path: "/packageA/orderForm/rows",
					icon: "work-dingdan"
				}, {
					name: "账户",
					key: "waccount",
					path: "/packageA/account/index",
					icon: "work-zhanghu"
				}, {
					name: "促销活动",
					key: "wdiscounts",
					path: "/packageA/activity/index",
					icon: "work-cuxiaohuodong"
				}, {
					name: "打款凭证",
					key: "wpaymentdocument",
					path: "/packageA/remitVoucher/index",
					icon: "work-dakuanpingzheng"
				}, {
					name: "物流单",
					key: "wlogisticsbill",
					path: "/packageA/shipment/index",
					icon: "icon-shouhuo"
				}, {
					name: "返退申请单",
					key: "wreturn",
					path: "/packageA/returnOne/index",
					icon: "work-shujuchaxun"
				}, {
					name: "发货单",
					key: "wdispatch",
					path: "/packageA/dispatchBill/index",
					icon: "icon-shouhuo"
				}, {
					name: "发货明细",
					key: "wdeliverydetail",
					path: "/packageA/dispatchBill/rows",
					icon: "icon-shouhuo"
				}, {
					name: "工厂发退明细",
					key: "wsentandback",
					path: "/packageA/dispatchBill/sentandback",
					icon: "icon-shouhuo"
				}, {
					name: "业绩目标",
					key: "wtarget",
					path: "/packageA/target/index",
					icon: "work-yejimubiao"
				}, {
					name: "收藏夹",
					key: "wfavorites",
					path: "/packageA/favorites/index",
					icon: "work-webshoucang"
				}];
				let edd = getApp().globalData.queryPer.query(wx.getStorageSync('userauth'), ["E-订单"], ["商品档案", "销售管理", "财务管理", "售后管理", "发货管理", "业绩查询"]),
					list = [];
				edd.forEach(v => {
					v.apps.forEach(s => {
						authList[s.name] = {
							options: s.meta.auth.map(a => a.option),
							optionnames: s.meta.auth.map(a => a.optionname),
							forms: s.meta.forms
						}
						if (authList[s.name].options.some(s => s == "read")) {
							let i = paths.findIndex(k => k.key == s.name || k.name == s.meta.title);
							if (i != -1) {
								paths[i].name = s.meta.title;
								paths[i].index = i;
								paths[i].isneedpay = s.isneedpay;
								list.push(paths[i])
							}
						}
					})
				});
				return dye(list.sort((a, b) => a.index - b.index))
			};
			//染色
			function dye(list) {
				let colorList = [{
					color: "#3874F6",
					bColor: "#F0F3FF",
				}, {
					color: "#5AB73F",
					bColor: "#F4FAEF",
				}, {
					color: "#F29C37",
					bColor: "#FCF6EF",
				}, {
					color: "#EB4B5C",
					bColor: "#FDF1ED",
				}, {
					color: "#3874F6",
					bColor: "#F0F3FF",
				}, {
					color: "#F29C37",
					bColor: "#FCF6EF",
				}, {
					color: "#EB4B5C",
					bColor: "#FDF1ED",
				}, {
					color: "#3874F6",
					bColor: "#F0F3FF",
				}, {
					color: "#5AB73F",
					bColor: "#F4FAEF",
				}, {
					color: "#F29C37",
					bColor: "#FCF6EF",
				}, {
					color: "#5AB73F",
					bColor: "#F4FAEF",
				}, {
					color: "#3874F6",
					bColor: "#F0F3FF",
				}, {
					color: "#F29C37",
					bColor: "#FCF6EF",
				}, {
					color: "#EB4B5C",
					bColor: "#FDF1ED",
				}, {
					color: "#5AB73F",
					bColor: "#F4FAEF",
				}];
				return list.map((v, i) => {
					return {
						...v,
						...colorList[i > colorList.length - 1 ? i - colorList.length : i]
					}
				})
			};
			wx.setStorageSync('auth', authList)
			let banner = wx.getStorageSync('banner_list').find(v => v.location == "index_top");
			page.setData({
				entrance,
				bannerList: banner ? banner.ads : []
			});
			pageInit.Home = true;
			page.selectComponent("#ListBox").setHeight(".head", page);
			console.log("entrance", entrance)
			return entrance.find(v => v.label == "E-订单").list
		} else {
			setTimeout(this.refreshData, 10);
			return;
		}
	},
	/* 获取通告列表 */
	/**
	 * 更新购物车数量
	 */
	getCollectCount() {
		return _Http.basic({
			"id": 20220927093202,
			"content": {}
		}).then(res => {
			console.log("购物车数量", res)
			getApp().globalData.collectCount = res.data.num;
			pageInit.Collect = false;
			this.setData({
				collectCount: res.data.num
			})
			return res.data.num;
		});
	},
	/* 更新收藏夹数量 */

	getFavoriteCount() {
		return _Http.basic({
			"id": 20231121145103,
			"content": {
				pageSize: 1,
				nocache: true
			}
		}).then(res => {
			console.log("收藏夹数量", res)
			getApp().globalData.favoriteCount = res.total;
			this.setData({
				favoriteCount: res.data.num
			})
			return res.total;
		});
	},
	/* 更新消息数量 */
	updateMsgCount() {
		pageInit.Message = false;
		_Http.basic({
			"classname": "system.message.Message",
			"method": "unReadMessageCount",
			"content": {
				nocache: true
			}
		}, false).then(res => {
			console.log('信息数量', res)
			if (res.msg != '成功') return;
			let fcount = res.data.fcount > 99 ? '99+' : res.data.fcount;
			if (res.data.fcount == 0) fcount = "";
			this.setData({
				fcount
			})
		});
		_Http.basic({
			"classname": "system.message.Message",
			"method": "queryMessage",
			content: {
				nocache: true,
				pageNumber: 1,
				pageSize: 1,
				type: "",
				where: {}
			},
		}).then(res => {
			if (res.msg != '成功') return;
			this.selectComponent("#Home").setData({
				msgList: res.data
			})
		})
	},
	/** 
	 * 切换页面
	 */
	async NavChange(e) {
		let cur = e.currentTarget.dataset.cur;
		if (this.data.PageCur == cur) return;
		if (cur == 'Market' || cur == 'Collect') {
			let app = getApp().globalData.queryPer.query(wx.getStorageSync('userauth'), ["E-订单"], ["商品档案"])[0].apps
			let item = app.find(v => v.name == (cur == 'Market' ? "wmarket" : "wshoppingtrolley"))
			const res = await getApp().globalData.evidence(item);
			if (res) {
				this.cutBar({
					detail: e.currentTarget.dataset.cur
				});
				if (!getApp().globalData.socketEstablish) getApp().initSocket();
			}
		} else {
			this.cutBar({
				detail: e.currentTarget.dataset.cur
			});
			if (!getApp().globalData.socketEstablish) getApp().initSocket();
		}
	},
	/** 
	 * 切换bar
	 */
	cutBar({
		detail
	}) {
		let page = this.selectComponent("#" + detail);
		if (!page) return;
		if (!pageInit[detail] && page.init()) pageInit[detail] = true;
		this.setData({
			PageCur: detail
		})
	},
})