<template>
	<view class="index-container">
		<view class="ic-content">
			<view class="ic-header">
				<view class="ih-address" v-if="isLogin" @click="toStoreList">
					<view>{{indexData.brand_name || '-'}}(共{{indexData.stadium_num || '0'}}家)</view>
					<image src="/static/images/icon/arrow_ff.png" mode="aspectFit"></image>
				</view>
				<view v-else class="ih-btn" hover-class="hover-active" @click="showAuthor">点击登陆</view>
				<view class="ih-tip">今日总收入</view>
				<view class="ih-price"><text>{{isLogin?'¥':''}}</text>{{isLogin?(indexData.amount || '0'):'***'}}</view>
				<view class="ih-amount">
					<view>
						<view>收款笔数</view>
						<view>{{isLogin?(indexData.in_count || '0'):'**'}}</view>
					</view>
					<view>
						<view>退款笔数</view>
						<view>{{isLogin?(indexData.out_count || '0'):'**'}}</view>
					</view>
				</view>
				<image class="ih-bg-icon" style="left: 0;" mode="aspectFit" src="/static/images/icon/index/header_bg_a.png"></image>
				<image class="ih-bg-icon" mode="aspectFit" src="/static/images/icon/index/header_bg_b.png"></image>
			</view>
			<view class="ic-notice" @click="toNoticeList">
				<view class="in-left">
					<image src="/static/images/icon/index/notice.png" mode="aspectFit"></image>
					<text>消息中心</text>
				</view>
				<view class="in-right">
					<view v-if="indexData.message_count>0">{{indexData.message_count || '0'}}</view>
					<image src="/static/images/icon/arrow_b2.png" mode="aspectFit"></image>
				</view>
			</view>
			<view class="ic-tabs">
				<view class="it-item" v-for="e in tabList" :key="e.id" @click="toPageInfo(e)">
					<image mode="aspectFit" :src="'/static/images/icon/index/tab_'+ e.id + '.png'"></image>
					<view>{{e.name}}</view>
				</view>
			</view>
		</view>
		<view class="ox-dark-mask" v-if="isShowAuthorModal">
			<view class="ic-author-modal">
				<view class="iam-title">微信授权</view>
				<view class="iam-tip">您的信息和数据将受到保护</view>
				<image class="iam-pic" mode="aspectFit" src="/static/images/icon/author_modal.png"></image>
				<view class="iam-btns">
					<button plain hover-class="hover-active" @click="cancelAuthor">取消</button>
					<button 
						plain 
						hover-class="hover-active" 
						open-type="getUserInfo"
						lang="zh_CN"
						@getuserinfo="confirmAuthor"
					>授权并登录</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	
	import util from '../../utils/util';
	import { servers } from '../../js/server';
	import { API } from '../../js/api';
	const tabList = [
		{
			id: 0,
			name: '营业额',
			path: '/pages/turnover/turnover',
			serverKey: 1001  // 后端对应权限编号
		},
		{
			id: 1,
			name: '收款记录',
			path: '/pages/collection/record/record',
			serverKey: 1002  // 后端对应权限编号
		},
		{
			id: 2,
			name: '经营分析',
			path: '',
			serverKey: 1003  // 后端对应权限编号
		},
		{
			id: 3,
			name: '场馆订单',
			path: '/pages/order_list/order_list',
			serverKey: 1004  // 后端对应权限编号
		},
		{
			id: 4,
			name: '会员卡订单',
			path: '/pages/order_list/order_list',
			serverKey: 1005  // 后端对应权限编号
		},
		{
			id: 5,
			name: '积分订单',
			// path: '/pages/order_list/order_list',
			path: '',
			serverKey: 1006  // 后端对应权限编号
		},
		{
			id: 6,
			name: '员工管理',
			path: '/pages/employee/manage/manage',
			serverKey: 1007  // 后端对应权限编号
		},
		{
			id: 7,
			name: '核销查询',
			path: '/pages/write_off/list/list',
			serverKey: 1008  // 后端对应权限编号
		},
		{
			id: 8,
			name: '场地管理',
			path: '',
			serverKey: 1009  // 后端对应权限编号
		},
	];
	
	const uniGetSetting = util.promisify(uni.getSetting);
	const uniLogin = util.promisify(uni.login);
	const uniGetUserInfo= util.promisify(uni.getUserInfo);
	const app = getApp();
	const APPID = uni.getAccountInfoSync().miniProgram.appId;
	export default {
		computed: {
			
		},
		data() {
			return {
				tabList,
				isShowAuthorModal: false,
				isLogin: false,
				indexData: {},
			}
		},
		async onLoad() {	
			try{
				util.showLoad();
				await this.checkUserAuthor();
				util.hideLoad();
				this.$nextTick(_=>this.isLogin = app.isLogin());
				if(!!app.isLogin())this.getIndexInfo();
			}catch(err){
				util.hideLoad();
				uni.removeStorageSync('token');
				this.$nextTick(_=>this.isLogin = app.isLogin());
				util.showNone(err.message || '身份校验失败！');
				console.log('onLoad err',err);
			}
		},
		onShow(){
			let { indexData } = this; 
			if(JSON.stringify(indexData)!='{}'&&!!app.isLogin())this.getIndexInfo();
		},
		methods: {
			toNoticeList(){
				if(!app.isLogin())return this.showAuthor();
				util.routeTo(`/pages/message/list/list`,'nT');
			},
			toPageInfo(tabInfo){
				let { indexData } = this;
				let _permission = indexData.permission || {};
				if(!app.isLogin())return this.showAuthor();
				if(!tabInfo.path)return util.showNone('暂未开放！');
				if(!_permission[tabInfo.serverKey])return util.showNone('暂无权限，请联系管理员开启！')
				if(this.isOrderTab(tabInfo.id))return util.routeTo(tabInfo.path + `?order_type=${tabInfo.id}`,'nT');
				util.routeTo(tabInfo.path,'nT');
			},
			isOrderTab(ID){
				return	ID == 3 || ID == 4 || ID == 5
			},
			getIndexInfo(){
				servers.get({
					url: API.calc,
					data: {},
					failMsg: '加载数据失败！'
				})
				.then(res=>{
					this.indexData = res;

					this.$store.commit('setBrandInfo',res);
				})
			},	
			// 看是否授权，清除token
			async checkUserAuthor(){
				try{
					let setting;
					try{setting = await uniGetSetting({})}catch(err){console.error(err)};
					if(setting&&setting.authSetting&&setting.authSetting['scope.userInfo'] === true){

						let [ loginRes, userRes ] = await Promise.all([uniLogin(), uniGetUserInfo()]);

						return servers.post({
							url: API.wechatMiniAppLoginAndSync,
							data: {
								appid: APPID,
								code: loginRes.code,
								encryptedData: userRes.encryptedData,
								iv: userRes.iv,
								is_details: 1,
							},
							isDefaultGet: false,
						})
						.then(res=>{
							util.hideLoad();
							if(res.data.code == 0){
								let _data = res.data.data;
								if(_data.user.role == ''){
									uni.removeStorageSync('token');
									return util.routeTo(`/pages/merchant_login/merchant_login`,'rL');
								}
								uni.setStorageSync('token',_data.token);
								
								return _data;
							}else{
								throw res.data || {};
							}
							
						})
						.catch(err=>{
							throw err;
						})
					}else{
						throw 'author err';
					}
				}catch(err){
					throw err;
				}
			},
			showAuthor(){
				this.isShowAuthorModal = true
			},
			closeAuthor(){
				this.isShowAuthorModal = false
			},
			cancelAuthor(){
				this.closeAuthor();
			},
			async confirmAuthor(userRes){
				if(!userRes.detail.userInfo){
					this.closeAuthor();
					return util.showNone('获取用户信息失败！请稍后重试');
				}
				let loginRes = await uniLogin();

				if(!loginRes.code){
					this.closeAuthor();
					return util.showNone('获取登陆凭证失败！稍后重试');
				}

				util.showLoad();
				
				servers.post({
					url: API.wechatMiniAppLoginAndSync,
					data: {
						appid: APPID,
						code: loginRes.code,
						encryptedData: userRes.detail.encryptedData,
						iv: userRes.detail.iv,
						is_details: 1,
						// 'avatar_url': userRes.detail.userInfo.avatarUrl,
						// ...userRes.detail.userInfo,
					},
					isDefaultGet: false,
				})
				.then(res=>{
					util.hideLoad();
					if(res.data.code == 0){
						let _data = res.data.data;
						if(_data.user.role == '')return util.routeTo(`/pages/merchant_login/merchant_login`,'rL');
						util.showNone(res.data.message || '登陆成功！');
						
						uni.setStorageSync('token',_data.token);
						setTimeout(_=>{
							this.isLogin = app.isLogin();
							this.getIndexInfo();
							this.closeAuthor();
						}, 1200);
					}else{
						util.showNone(res.data.message || '后台登陆失败！');
						setTimeout(_=>this.closeAuthor(), 1200);
					}
					
				}).catch(util.hideLoad)

			},
			
			toStoreList(){
				if(!app.isLogin())return this.showAuthor();
				let { indexData } = this;
				util.routeTo(`/pages/store_list/store_list?brand_id=${indexData.brand.id}`,'nT');
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../style/public.scss";
	.index-container{
		position: relative;
	}
	.ic-content{
		padding: 24upx;
	}
	.ic-header{
		position: relative;
		height: 476upx;
		margin-bottom: 48upx;
		padding: 38upx 24upx 0;
		border-radius: 14upx;
		background-color: $themeColor;
		.ih-address{
			margin-bottom: 26upx;
			@include centerFlex(center);
			>view{
				max-width: 90%;
				line-height: 50upx;
				text-align: center;
				font-size: 36upx;
				color: #fff;
				@include textHide(1);
			}
			>image{
				flex-shrink: 0;
				margin-left: 20upx;
				width: 28upx;
				height: 28upx;
			}
		}
		.ih-btn{
			margin: 0 auto 28upx;
			width: 160upx;
			height: 48upx;
			text-align: center;
			line-height: 48upx;
			font-size: 28upx;
			color: $themeColor;
			background-color: #fff;
			border-radius: 24upx;
		}
		.ih-tip{
			margin-bottom: 8upx;
			line-height: 40upx;
			text-align: center;
			font-size: 28upx;
			color: rgba($color: #fff, $alpha: .7);
		}
		.ih-price{
			margin-bottom: 50upx;
			line-height: 96upx;
			text-align: center;
			font-size: 84upx;
			font-weight: 500;
			color: #fff;
			@include textHide(1);
			>text{
				line-height: 74upx;
				font-size: 64upx;
			}
		}
		.ih-amount{
			@include centerFlex(space-around);
			>view{
				>view{
					&:first-child{
						margin-bottom: 16upx;
						line-height: 40upx;
						text-align: center;
						font-size: 28upx;
						color: rgba($color: #fff, $alpha: .7);
					}
					&+view{
						line-height: 56upx;
						text-align: center;
						font-size: 40upx;
						font-weight: 500;
						color: #fff;
					}
				}
			}
		}
		.ih-bg-icon{
			position: absolute;
			top: 0;
			width: 120upx;
			height: 142upx;
			&+.ih-bg-icon{
				right: 0;
				top: 38upx;
				width: 240upx;
				height: 400upx;
			}
		}
	}
	.ic-notice{
		margin-bottom: 24upx;
		padding: 0 24upx;
		height: 108upx;
		border-radius: 10upx;
		background-color: #fff;
		@include centerFlex(space-between);
		.in-left{
			>image{
				vertical-align: middle;
				margin-right: 10upx;
				width: 52upx;
				height: 50upx;

			}
			>text{
				font-size: 28upx;
				line-height: 40upx;
				color: #1a1a1a;
			}
		}
		.in-right{
			@include centerFlex(flex-end);
			>view{
				margin-right: 14upx;
				line-height: 50upx;
				text-align: center;
				width: 50upx;
				height: 50upx;
				line-height: 50upx;
				font-size: 24upx;
				border-radius: 50%;
				color: #fff;
				background-color: #ea5061;
				@include textHide(1);

			}
			>image{
				width: 28upx;
				height: 28upx;

			}
		}
	}
	.ic-tabs{
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
		.it-item{
			padding-top: 54upx;
			margin-bottom: 24upx;
			flex-shrink: 0;
			flex-grow: 0;
			width: 218upx;
			height: 218upx;
			border-radius: 10upx;
			background-color: #fff;
			>image{
				display: block;
				margin: 0 auto 20upx;
				width: 52upx;
				height: 52upx;
			}
			>view{
				text-align: center;
				line-height: 40upx;
				font-size: 28upx;
				color: #1a1a1a;
			}
		}
	}
	.ic-author-modal{
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		padding-top: 60upx;
		width: 662upx;
		height: 884upx;
		border-radius: 10upx;
		background-color: #fff;
		.iam-title{
			margin-bottom: 22upx;
			text-align: center;
			line-height: 60upx;
			font-size: 44upx;
			font-weight: 500;
			color: #1a1a1a;
		}
		.iam-tip{
			margin-bottom: 52upx;
			line-height: 40upx;
			text-align: center;
			font-size: 28upx;
			color: #9c9c9f;
		}
		.iam-pic{
			margin: 0 auto 62upx;
			display: block;
			width: 488upx;
			height: 416upx;
		}
		.iam-btns{
			@include centerFlex(center);
			>button{
				margin: 0 20upx;
				width: 240upx;
				height: 92upx;
				line-height: 88upx;
				text-align: center;
				border-radius: 46upx;
				border: 2upx solid $themeColor;
				font-size: 32upx;
				color: $themeColor;
				&+button{
					background-color: $themeColor;
					color: #fff;
				}
			}
		}

	}
</style>
