<template>
	<view>
		<view class="content">
			<view class="header-box">
				<UniStatusBar></UniStatusBar>
				<view class="title flex align_center" :style="{height:(navHeight+'px')}">
					<u-image src="/static/logo-h.png" width="349" height='40'></u-image>
				</view>
			</view>
			<view class="cbody">
			<view class="body-box bg-blue">
				<!-- 滚动区域 -->
				<view class="scroll-list">
					<scrollBox v-if="list.length&&!hasRedPacket" :list="list"></scrollBox>
					<scrollBox v-if="slist.length&&hasRedPacket" :list="slist"></scrollBox>
				</view>
				<!-- 保证金 -->
				<view class="notices flex align_center" v-if="bondRecord" @click="toPayBondAmount">
					<view><u-icon name="volume" color="#f2a557" :size="28" :margin-right='15'></u-icon> 您有一笔保证金待支付 ￥{{bondRecord.bondAmount}}</view> 
					<!-- <text class="text">立即支付>></text> -->
				</view>
				<!-- 待取货提醒 -->
				<view class="notices flex align_center" v-if="!bondRecord&&orderTodo" @click="toOrder">
					<view><u-icon name="volume" color="#f2a557" :size="28" :margin-right='15'></u-icon> 您有待取货的货架订单哦！</view> <text class="text">立即处理>></text>
				</view>
				<!-- 门店审核不通过 -->
				<view class="notices flex justify_between" v-if="storeApply&&storeApply.auditStatus=='REFUSE'&&storeApply.readFlag=='0'">
					<view><u-icon name="volume" color="#f2a557" :size="28" :margin-right='15'></u-icon> 门店认证资料审核不通过，请重新提交审核！</view> <text class="text" @click="toKnow">知道了</text>
				</view>
				<!-- 名片 -->
				<view class="userCard flex align_center justify_between">
					<view class="userCard-info flex align_center">
						<view>
							<u-image shape='circle' v-if="!hasLogin" src="/static/def_personal_avatar.png" width="90" height="90"></u-image>
							<u-image shape='circle' v-else :src="avatarUrl||'/static/def_personal_avatar.png'" width="90" height="90"></u-image>
						</view>
						<view class="user-info" @click="toUser">
							<view v-if="!hasLogin" style="font-size: 40rpx;">
								请点击登录
							</view>
							<view v-else>
								<view class="user-name">{{userInfo.userNameCN || userInfo.mobile}}</view>
								<view v-if="hasLogin&&userInfo&&userInfo.sysUserFlag == '0'">
									<u-tag text="个人用户" mode="dark" type="warning" shape="circle" size="mini" />
								</view>
								<view v-else>{{userInfo.orgName}}</view>
							</view>
						</view>
					</view>
					<view @click="toUser">
						<text v-if="hasLogin&&userInfo&&userInfo.sysUserFlag == '0'" class="user-rz">
							{{storeApply&&storeApply.auditStatus=='WAIT'?'认证门店审核中':'认证成为门店'}}
						</text>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
			<view class="body-box">	
				<!-- 扫描按钮 -->
				<!-- <view class="scanButton flex align_center" @click="openCamera">
					<u-icon name="scan" size="60"></u-icon><text class="ml10">扫描VIN</text>
				</view> -->
				<!-- 直接取货 -->
				<!-- <view class="scanButton flex align_center" v-if="userInfo.sysUserFlag == '1'" @click="openTakeGood">
					<text>没有VIN,直接取货</text>
				</view> -->
				<view class="action-button flex" v-if="userInfo.sysUserFlag == '1'">
					<view></view>
					<view class="f1" @click="openTakeGood(1)">
						<view class="icons"><u-icon name="shujuchaxun" custom-prefix="custom-icon"></u-icon></view>
						<view class="tits">产品编码取货</view>
					</view>
					<view class="f2" @click="openTakeGood(0)">
						<view class="icons"><u-icon name="saomasoudan" custom-prefix="custom-icon"></u-icon></view>
						<view class="tits">二维码/条形码取货</view>
					</view>
					<view></view>
				</view>
				<view style="margin-top: 20upx;">
					<u-swiper mode="dot" bg-color="" img-mode="widthFix" @click="clickBanner" :interval="3000" :height="374" :list="imgList"></u-swiper>
				</view>
				<u-action-sheet :list="actionList" @click="clickAction" v-model="showAction"></u-action-sheet>
			</view>
			<!-- 扫描记录 -->
			<view class="list-box">
				<!-- 扫描记录 -->
				<u-cell-group :border="false">
					<u-cell-item title="VIN查询历史" @click="toAllRecord" :title-style="{fontSize:'1em'}" value="全部">
						<u-icon slot="icon" size="38" color="#066cff" style="margin-right: 0.3em;" name="order"></u-icon>
					</u-cell-item>
				</u-cell-group>
				<u-cell-group :border="false" v-if="hasLogin">
					<u-cell-item v-for="item in vinList" 
					@click="toChoosePart(item)" 
					:key="item.id" 
					:title="item.vinCode" 
					:title-style="{fontSize:'1em'}" 
					:label="userInfo&&userInfo.sysUserFlag == '0' ? item.createDate : (item.brandName +' '+item.modelName)">
						<text slot="icon"></text>
					</u-cell-item>
					<view style="padding: 20upx;">
						<u-empty :src="`/static/nodata.png`" icon-size="180" :text="noDataText" img-width="120" v-if="vinList.length==0 && status!='loading'" mode="list"></u-empty>
						<u-loadmore v-if="status=='loading'" :status="status" />
					</view>
				</u-cell-group>
				<view class="des" v-if="vinList.length&&hasLogin">仅展示最近5条记录，点击“全部”查看更多</view>
				<view class="des" v-if="!hasLogin">请登录后查看历史记录</view>
			</view>
			</view>
		</view>
		<u-tabbar :list="vuex_tabBarList" :before-switch="beforeSwitch" :mid-button="true"></u-tabbar>
	</view>
</template>

<script>
	import {
	    mapState,
	    mapMutations,
	} from 'vuex'
	import scrollBox from '@/components/scrollBox.vue'
	import UniStatusBar from '@/components/uni-status-bar/uni-status-bar.vue'
	import { shelfBondRecordWaitPayRecord, findStoreShelf, shelfGetTotalWaitQty, getProductfindByScanCode } from '@/api/shelf.js'
	import { xprhStoreApplyRead } from '@/api/xprh.js'
	import { findCurrentRewardRule } from '@/api/rewardRule.js'
	import { listLookUp, getLookUpDatas, getCurrUserInfo } from '@/api/data.js';
	import { scanVinLogQueryRoll, getScanVinLogList, getScanGetMaxQty }from '@/api/car.js'
	import { getRewardRollList } from '@/api/rewardRule.js'
	export default {
		components: {
			scrollBox,
			UniStatusBar
		},
		data() {
			return {
				status: 'loading',
				noDataText: '暂无数据',
				bondRecord: null, // 保证金
				list:[], // 扫描记录滚动
				slist:[], // 红包滚动
				vinList: [],
				orderTodo: null,
				avatarUrl:'',
				navHeight: '44',
				scanMaxNums: 10,
				showAction: false,
				actionList: [
					{
						text: '扫描条形码/二维码',
						fontSize: 32
					},
					{
						text: '按产品编码查询',
						fontSize: 32
					}
				],
			}
		},
		computed: {
			...mapState(['hasLogin','vuex_vinScanNums','vuex_tabBarList']),
			hasShelf(){
				return this.$store.state.vuex_storeShelf
			},
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			storeApply(){
				return this.$store.state.vuex_storeAuthInfo || null
			},
			hasRedPacket(){
				const rule = this.$store.state.vuex_rewardRule
				return rule&&rule.ruleStatus == 'release'
			},
			imgList(){
				if(this.hasRedPacket&&this.hasShelf){
					return [{
						image: '/static/banner2.png'
					}]
				}else{
					return [{
						image: '/static/banner1.png'
					}]
				}
			}
		},
		onReady() {
			this.getScrollLog()
			
			// 获取导航栏高度
			const res = uni.getSystemInfoSync()
			const system = res.platform
			if (system === 'android') {
				this.navHeight = 48
			} else if (system === 'ios') {
				this.navHeight = 44
			}
		},
		onLoad() {
			this.orderTodo = null
			this.bondRecord = null
			this.vinList = []
			// 检测是否登录
			this.$store.dispatch('checkLogin',()=>{
				// 获取数据字典
				this.getListLookUp();
				// 获取支付，收款方式
				this.getLookUpList('PAY_PROCUCT_TYPE', 'vuex_paymentTypeList');
				// 价格类型
				this.getLookUpList('PRICE_SHOW_TYPE', 'vuex_priceTypeList');
				// 初始化页面
				this.pageInit()
				// 查询红包活动
				this.getRedPacketRule()
				// 更新用户信息
				this.getCurrUserInfo()
			})
			// 刷新首页数据
			uni.$on("refashHome",()=>{
				this.pageInit()
			})
		},
		onUnload() {
			uni.$off('refashHome')
		},
		// 下拉刷新
		onPullDownRefresh(){
			this.pageInit()
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onShareAppMessage() {},
		onShow() {
			// 用户头像
			this.avatarUrl = uni.getStorageSync('userPhoto');
			if(this.hasLogin){
				// 更新用户信息
				this.getCurrUserInfo()
				// 查询门店认证信息
				if(this.userInfo.sysUserFlag == '0'){
					this.findLastApply()
				}
				if(this.userInfo.sysUserFlag == '1'){
					// 查询红包活动
					this.getRedPacketRule()
				}
			}
		},
		methods: {
			// 扫描vin
			beforeSwitch(index){
				if(index==1){
					this.openCamera()
				}else{
					return true
				}
			},
			pageInit(){
				if(this.hasLogin){
					// 获取扫描记录
					this.getVinLog()
					// 非游客
					if(this.userInfo.sysUserFlag == '1'){
						// 查询是否有数字货架
						this.getStoreShelf()
					}else{
						// 获取扫描次数
						this.$store.dispatch("getScanNums")
						// 获取最大扫描次数
						this.getMaxQty()
						// 查询门店认证信息
						this.findLastApply()
					}
					
				}else{
					uni.removeStorageSync('token')
				}
			},
			//  获取数据字典
			getListLookUp() {
				const _this = this;
				listLookUp({ pageNo: 1, pageSize: 1000 }).then(res => {
					if (res.status == 200) {
						_this.$store.state.vuex_allLookUp = res.data;
					}
				});
			},
			// 或某一项字典列表，参数code
			getLookUpList(code, vuexKey) {
				getLookUpDatas({ type: code }).then(res => {
					if (res.status == 200) {
						this.$store.state[vuexKey] = res.data || [];
					}
				});
			},
			// 最新用户信息
			getCurrUserInfo(){
				getCurrUserInfo().then(res => {
					if(res.data){
						this.$store.state.vuex_userInfo.userNameCN = res.data.name;
						this.$store.state.vuex_userInfo.mobile = res.data.mobile;
						this.$store.state.vuex_userInfo.adminId = res.data.id;
						this.$store.state.vuex_userPhoto = res.data.photo;
						uni.setStorageSync('userPhoto', res.data.photo);
					}
				})
			},
			// 获取最大扫描数
			getMaxQty(){
				getScanGetMaxQty().then(res => {
					this.scanMaxNums = res.data || 10
					this.$store.state.vuex_scanMaxNums = this.scanMaxNums
				})
			},
			// 获取最新申请门店
			findLastApply(){
				const mobile = this.userInfo.mobile
				this.$store.dispatch('getSotreAuth',mobile)
			},
			// 知道审核不通过
			toKnow(){
				uni.showLoading({
					title: "正在提交"
				})
				xprhStoreApplyRead({sn:this.storeApply.applySn}).then(res => {
					if(res.status == 200){
						this.findLastApply()
					}
					uni.hideLoading()
				})
			},
			// 待取货数量合计
			shelfGetTotalWaitQty(){
				shelfGetTotalWaitQty({billState:'WAIT'}).then(res => {
					if(res.status == 200){
						this.orderTodo = res.data;
					}
				})
			},
			// 货架订单列表
			toOrder(){
				if(this.hasShelf){
					uni.navigateTo({
						url: "/pagesA/digitalShelf/orderList"
					})
				}else{
					uni.showToast({
						icon:'none',
						title: '门店没有关联数字货架，无法使用此功能！'
					})
				}
			},
			// 获取上方滚动扫描记录
			getScrollLog(){
				scanVinLogQueryRoll({pageNo:1,pageSize:1000}).then(res => {
					console.log(res)
					this.list = res.data.list || []
					this.list.map(item => {
						item.placeText = item.userName + '刚刚扫描了一个VIN'
					})
				})
			},
			// 获取当前门店扫描记录
			getVinLog(){
				this.vinList  = []
				this.status = "loading"
				// VISITOR：游客，EMPLOYEE：雇员
				getScanVinLogList({ pageNo:1, pageSize:5, identifyType: this.userInfo.identifyType }).then(res => {
					this.vinList = res.data&&res.data.list || []
					this.vinList = this.vinList.filter(item => item.vinCode)
					this.status = 'nomore'
				})
			},
			// 查询是否支持数字货架
			getStoreShelf(){
				findStoreShelf().then(res => {
						console.log(res)
						this.$store.state.vuex_storeShelf = res.data;
						if(res.data){
							// 保证金查询
							this.getShelfBWPayRecord()
							// 获取订单信息
							this.shelfGetTotalWaitQty()
						}
				})
			},
			// 查询是有红包活动
			getRedPacketRule(){
				findCurrentRewardRule().then(res => {
					this.$store.state.vuex_rewardRule = res.data;
					this.getRedScroll()
				})
			},
			getRedScroll(){
				getRewardRollList({pageNo:1,pageSize:1000}).then(res => {
					this.slist = res.data || []
					this.slist.map(item => {
						item.placeText = item.userName + '刚刚得到了'+item.totalRewardAmount+'元 红包奖励'
					})
				})
			},
			// 获取保证金金额
			getShelfBWPayRecord(){
				const data = this.$store.state.vuex_storeShelf
				shelfBondRecordWaitPayRecord({shelfSn: data.shelfSn, storeSn: data.storeSn}).then(res => {
					console.log(res,'获取保证金金额')
					this.bondRecord = res.data
				})
			},
			// 保证金支付
			toPayBondAmount(){},
			openTakeGood(index){
				// 已有数字货架
				if(this.hasShelf){
					// this.showAction = true
					this.clickAction(index)
				}else{
					uni.showToast({
						icon:'none',
						title: '门店没有关联数字货架，无法使用此功能！'
					})
				}
			},
			// 单击banner
			clickBanner(index){
				if(index == 0 && this.hasRedPacket){
					uni.navigateTo({url:"/pages/morePage/redPacket"})
				}
			},
			// 选择取货方式
			clickAction(index){
				const shelfSn = this.hasShelf.shelfSn
				const _this = this
				// 扫描
				if(index == 0){
					uni.scanCode({
						success: function (ret) {
							console.log(ret);
							const params = {
								codeType: ret.scanType == 'QR_CODE' ? 0 : 1
							}
							// 二维码
							if(ret.scanType == 'QR_CODE'){
								const result = ret.result.split("&")
								params.productSn = result[2] // 产品编码sn
							}else{
								params.qrCode = ret.result
							}
							uni.showLoading({
								title: "正在查询产品..."
							})
							// 确认取货
							getProductfindByScanCode(params).then(res => {
								if(res.status == 200 && res.data){
									if(res.data.currentInven){
										const billSource = ret.scanType == 'QR_CODE' ? 'qr_code': 'bar_code'
										const params = Object.assign({shelfSn: shelfSn, billSource: billSource},res.data)
										_this.$store.state.vuex_tempData = params
										uni.navigateTo({
											url: '/pagesA/queryByCode/confirmQh'
										})
									}else{
										uni.showModal({
											title: '提示',
											content: '产品库存为0，无法取货！',
											confirmText: '好的',
											showCancel: false
										})
									}
								}else{
									uni.showModal({
										title: '提示',
										content: '产品不属于此货架，请重新扫描！',
										confirmText: '好的',
										showCancel: false
									})
								}
								uni.hideLoading()
							})
						}
					});
				}else{
					// 按编码搜索
					uni.navigateTo({
						url: '/pagesA/queryByCode/queryByCode'
					})
				}
			},
			// 去扫描
			openCamera(){
				if(this.hasLogin){
					if(this.userInfo.sysUserFlag == '0'){
						if(this.vuex_vinScanNums < this.scanMaxNums){
							uni.navigateTo({
								url: "/pages/scan-frame/scan-frame"
							})
						}else{
							uni.showModal({
								title: '提示',
								content: '个人用户扫描VIN仅限10次，您的次数已用完！',
								confirmText: '好的',
								showCancel: false,
								success(res) {}
							})
						}
					}else{
						uni.navigateTo({
							url: "/pages/scan-frame/scan-frame"
						})
					}
				}else{
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			// 查看扫描记录
			toAllRecord(){
				uni.navigateTo({
					url: this.hasLogin ? "/pages/vinRecord/vinRecord" : '/pages/login/login'
				})
			},
			toUser(){
				if(this.hasLogin){
					// 用户详细信息 或 门店认证
					uni.navigateTo({
						url: this.userInfo.sysUserFlag == '1' ? '/pages/personData/personData' : '/pages/storeManage/storeAuth'
					})
				}else{
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			toChoosePart(item){
				item.text = item.modelInfo
				uni.navigateTo({
					url: "/pagesA/digitalShelf/choosePart?vinNumber="+item.vinCode+"&carList="+encodeURIComponent(JSON.stringify(item))+'&type=log'
				})
			}
		}
	}
</script>

<style lang="less">
	page{
		background-color: #ffffff;
	}
	.content {
		margin: 0;
		padding: 0;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-image: linear-gradient(#86defa 0%,#cdeff9 25%,#ffffff 40%);
		.header-box{
			z-index: 5;
			padding: 0em 1em;
			background: #066cff;
			 .title{
				 padding: 0;
			 }
		}
		.cbody{
			flex-grow: 1;
			overflow-y: auto;
			overflow-x: hidden;
		}
		.body-box{
			padding: 0em 1em 0.8em;
			z-index: 4;
			.notices{
				padding: 0.5em 0 0;
				font-size: 0.9em;
				margin-top: 0.5rem;
				view{
					color: #ffaf46;
					max-width: 80%;
				}
				.text{
					color: #ffffff;
					margin-left: 1em;
				}
			}
			.action-button{
				padding:40upx 0 0 0;
				justify-content: space-between;
				> view{
					text-align: center;
					display: flex;
					align-items: center;
					flex-direction: column;
				}
				.f1{
					width: 140rpx;
				}
				.f2{
					width: 150rpx;
				}
				.icons{
					font-size: 60rpx;
					background: #066cff;
					color: #fff;
					border-radius: 30rpx;
					width: 110rpx;
					height: 110rpx;
					text-align:center;
					display: flex;
					align-items: center;
					flex-direction: column;
					justify-content: center;
				}
				.tits{
					font-size:30rpx;
					font-weight: bold;
					padding: 10upx  0;
				}
			}
			.scanButton{
				margin: 0.8em 0 0.5em;
				padding: 0.5em;
				background: #066cff;
				color: #fff;
				font-size: 1.5em;
				border-radius: 5em;
				justify-content: center;
				&:active{
					opacity: 0.8;
				}
			}
			.quickButton{
				margin: 0.8em 0 0.5em;
				padding: 0.5em;
				background: #fff;
				color: #333;
				font-size: 1.5em;
				border-radius: 5em;
				justify-content: center;
				border:0.1rpx solid #eee;
				box-shadow: 1rpx 2rpx 5rpx #f8f8f8;
				&:active{
					opacity: 0.8;
				}
			}
			.ml10{
				margin-left: 0.4em;
			}
		}
		.bg-blue{
			position: relative;
			> view{
				z-index: 100;
				position: relative;
			}
			&::after{
				/* 这个伪类的作用就是一个圆弧的背景色 */
				width: 130%;
				height: 100%;
				position: absolute;
				/*设置水平居中*/
				left: -15%;
				/* 之所以left:20%,是因为width:140%，若width:160%，那么left:30%才能水平居中 */
				top: -20%; 
				/*层叠顺序，最底层显示*/
				content: '';
				border-radius: 0 0 50% 50%;
				/*分别对应 左上 右上 右下 左下 可以修改成其它颜色*/
			    background: linear-gradient(to bottom, #066cff, #1d77ff);  
			}
			.userCard{
				position:relative;
				left:0;
				bottom:-1rem;
				padding:0.8em;
				background: #fff;
				border-radius: 0.5em;
				box-shadow: 0.3em 0.3em 1em #c4e5ee;
				.userCard-info{
					flex-grow:1;
					> view{
						&:last-child{
							margin-left: 0.5em;
							line-height: 1.5em;
							.user-name{
								font-size: 1rem;
							}
							>view{
								padding: 0.2em;
							}
						}
					}
					.user-info{
						flex-grow:1;
					}
				}
				.user-rz{
					font-size: 0.8rem;
					color:#58aff5;
				}
			}
		}
		.list-box{
			padding: 0 1em;
			overflow: auto;
			.des{
				text-align: center;
				padding: 1em 0;
				color: #999;
				font-size: 0.8em;
			}
		}
	}
</style>
