<template>
	<view class="index-wrapper">
		<poster id="ali-poster" posid="idle_pos" :audible="true" style="width: 100%; height: 88vh"
			onSuccess="onDisplaySuccess" onFail="onDisplayFail" onChange="onPosterChange"
			v-if="!vdata.userInfo.realname || !vdata.adList.length" />
		<JeepayBanner v-else :list="vdata.adList" :interval="vdata.changeTime" />
		<!-- <view style="width: 100%; height: 88vh"></view> -->
		<view class="idnex-wrapper">
			<view class="left">
				<view class="tips-title">请等待商家发起收款</view>
				<view class="store-name">付款给：{{ vdata.userInfo.realname }}</view>
			</view>
			<view class="right">
				<view class="more-but log-in" hover-class="hover-more" hover-stay-time="50" v-if="!vdata.userInfo.realname"
					@tap="toLogin">请登录</view>
			</view>
		</view>
	</view>
	<uni-drawer ref="refShowRight" mode="right" @change="change">
		<view class="list-wrapper" :style="{ '--text-color': calcWorkState().value == 1 ? ' #108ee9' : 'tomato' }">
			<blocke v-for="(v, i) in vdata.navList" :key="i">
				<view class="list-item" hover-class="hover-more" hover-stay-time="50" @tap="tapNav(v)"
					v-if="v.value.includes(vdata.modelType)">
					{{ v.title }}
					<view class="list-item-right">
						<view class="face-model" v-if="v.title == '切换模式'">当前模式：{{ vdata.modelType == 'pos' ? 'POS' : '独立收银' }}模式
						</view>
						<image src="/static/right.svg" mode="scaleToFill" v-if="i != vdata.navList.length - 1" />
						<image src="/static/logout.svg" mode="scaleToFill" v-else />
					</view>
				</view>
			</blocke>
		</view>
	</uni-drawer>
	<SwitchModelCard ref="refSwitch" @makClose="open" v-model:value="vdata.modelType" />
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, onMounted, reactive, ref } from 'vue'
import { req, $appPay, $workRecords, $userInfo, API_URL_PAY_ORDER_LIST, $adBannerList } from '@/http/apiManager'
import storageManage from '@/commons/utils/storageManage.js'
// 生命周期 进入页面
onLoad(() => {
	if (storageManage.token()) {
		getAd()
	}
})
// 初始化 modelType
if (!storageManage.faceModel()) {
	storageManage.faceModel('cashier')
}
const refShowRight = ref(null)
const refSwitch = ref(null)
const vdata = reactive({
	userInfo: storageManage.userInfo(), //取出用户信息
	navList: [
		{ title: '订单', url: '/pages/order/order', value: 'cashier' },
		{ title: '统计', url: '/pages/stat/stat', value: 'cashier' },
		{ title: `${calcWorkState().value == 1 ? '上班' : '下班'}打卡`, fun: working, value: 'cashier' },
		{ title: '交班', url: '/pages/handover/handover', value: 'cashier' },
		{ title: '切换模式', fun: switchModel, value: 'cashierpos' },
		{ title: '系统设置', fun: () => { my.ix.startApp({ appName: 'settings' }) }, value: 'cashierpos' },
		{ title: '刷新广告数据', fun: getAd, value: 'cashierpos' },
		{ title: '退出登录', fun: loginOut, value: 'cashier' }
	],
	modelType: storageManage.faceModel(), //取出本地存储的模式类型
	adList:[]
})

my.ix.onKeyEventChange(r => {
	// console.log('r', r)
	const timeStamp = new Date().getTime()
	switch (r.keyCode) {
		case 134:
			if (!storageManage.token()) return uni.$J.showErrorToast('请先登录')
			if (vdata.isShow) return my.ix.startApp({ appName: 'settings' })
			open()
			break
		case 132:
			if (storageManage.faceModel() && storageManage.faceModel() == 'pos') return posCashier()
			break
		case 131: //收款按键
			if (storageManage.faceModel() && storageManage.faceModel() == 'pos') return posCashier()
			my.ix
				.startApp({
					appId: '2021002172674746',
					appName: 'cashier',
					bizNo: timeStamp,
					totalAmount: r.amount,
					showScanPayResult: true,
					scanLoadingTimeout: '10'
				})
				.then(res => {
					my.ix.writeHID({
						protocol: 'barcode',
						value: res.barCode,
						success: r => {
							console.log('r', r)
						},
						fail: err => {
							console.log('err', err)
						}
					})
					$appPay(res.totalAmount, res.barCode).then(r => {
						findOrderState(r.bizData)
						console.log('支付后结果', r)
						//扫码付支付成功主动调起结果页
						if (res.codeType == 'C' && r.bizData.orderState == 2) {
							my.ix.startApp({
								appName: 'scanPayResult',
								bizNo: timeStamp,
								totalAmount: res.totalAmount,
								success: r => {
									console.log(r)
								}
							})
						}
					})
				})
				.catch(err => {
					console.log('err', err)
				})
			break
		case 133:
			close()
			break

	}
})
// 展示成功回调
const onDisplaySuccess = () => {
	console.log('poster display success')
}
// 展示失败回调
const onDisplayFail = e => {
	console.log('poster display fail, error = ' + e.detail.error)
}
// 广告可用性变化回调
const onPosterChange = e => {
	console.log('poster availability changed, now has poster = ' + e.detail.hasPoster)
}
// 打开抽屉
const open = () => {
	refShowRight.value.open()
}
// 关闭抽屉
const close = () => {
	refShowRight.value.close()
}
// pos 收银模式
function posCashier() {
	const timeStamp = new Date().getTime()
	my.ix
		.startApp({
			appId: '2021002172674746',
			appName: 'cashier',
			bizNo: timeStamp,
			showScanPayResult: true,
			scanLoadingTimeout: '10'
		})
		.then(res => {
			my.ix.writeHID({
				protocol: 'barcode',
				value: res.barCode,
				success: r => {
					console.log('r', r)
				},
				fail: err => {
					console.log('err', err)
				}
			})
		})
}
// 退出等领域
function loginOut() {
	uni.showModal({
		title: '提示',
		content: '是否确认退出登录',
		showCancel: true,
		success: ({ confirm, cancel }) => {
			if (confirm) {
				storageManage.cleanByLogout()
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}
		}
	})
}
// 打卡函数
function working() {
	uni.showModal({
		title: `提示：${calcWorkState().value == 1 ? '上班' : '下班'}打卡`,
		content: '是否确认打卡？',
		showCancel: true,
		success: ({ confirm, cancel }) => {
			if (confirm) {
				$workRecords(calcWorkState().value).then(res => {
					uni.showToast({
						title: '打卡成功',
						icon: 'success',
						mask: true
					})
					// 重新请求用户信息
					$userInfo().then(({ bizData }) => {
						// 更新用户数据
						storageManage.userInfo(bizData)
						// 更新用户数据
						vdata.userInfo = bizData
						vdata.navList[2].title = (calcWorkState().value == 1 ? '上班' : '下班') + '打卡'
					})
				})
			}
		}
	})
}
// 切换模式函数、
function switchModel() {
	refShowRight.value.close()
	refSwitch.value.open()
}
/****
 * @param {v} Object  url 跳转地址 fun 执行函数
 * */
const tapNav = v => {
	if (v.url)
		return uni.navigateTo({
			url: v.url
		})
	v.fun()
}
// 计算状态上班还是下班 0 未知  1上班 2下班
function calcWorkState() {
	return computed(() => {
		const state = storageManage.userInfo().workState
		return state == 0 ? '1' : state == 1 ? 2 : 1
	})
}
// 定向到登录页
const toLogin = () => uni.reLaunch({ url: '/pages/login/login' })
function findOrderState(val) {
	switch (val.orderState) {
		case 2:
			break
		case 3:
			uni.$J.showToast('支付失败' + val.errMsg)
			break
		case 4:
			uni.$J.showToast('订单撤销')
			break
		case 1:
			// 支付中 进行查单操作
			console.log('订单状态1进行查单 操作 ')
			findOrder(val.payOrderId)
			break
	}
}
let num = 1
function findOrder(payOrderId) {
	if (num > 20)
		return uni.showModal({
			title: '确认订单状态',
			content: '订单状态查询失败 请与客户确认订单状态 点击确认跳转订单列表页面',
			showCancel: true,
			success: ({ confirm, cancel }) => {
				if (confirm) {
					uni.navigateTo({
						url: '/pages/order/order'
					})
				}
			}
		})
	uni.$J.showToast(`支付中正在进行第${num}次订单查询`).then(res => {
		req.getById(API_URL_PAY_ORDER_LIST, payOrderId).then(({ bizData }) => {
			num += 1
			console.log('查单结果', bizData)
			bizData.orderState = bizData.state
			findOrderState(bizData)
		})
	})
}
function getAd() {
	$adBannerList().then(({ bizData }) => {
		if(!bizData){
			vdata.adList  =[]
			uni.showToast({title:'请求广告数据成功',icon:'success'})
			return false
		}
		vdata.adList = bizData?.appContent ? JSON.parse(bizData.appContent) : []
		vdata.changeTime = bizData.changeTime
		uni.showToast({title:'请求广告数据成功',icon:'success'})
	
	})
}
// 抽屉打开状态
const change = (e) => {
	vdata.isShow = e
}
</script>

<style lang="scss" scoped>
.idnex-wrapper {
	padding: 30rpx;
	box-sizing: border-box;
	height: 11.8vh;
	display: flex;
	justify-content: space-between;
	align-items: center;
	color: #108ee9;

	.tips-title {
		font-size: 38rpx;
		margin-bottom: 20rpx;
	}

	.store-name {
		color: #2c2c2c;
		font-size: 22rpx;
	}

	.more-but {
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 80rpx;
		height: 50rpx;
		border-radius: 7rpx;
		background-color: rgba($color: #108ee9, $alpha: 0.3);

		view {
			width: 4rpx;
			height: 4rpx;
			border-radius: 50%;
			background-color: #108ee9;
		}

		view:nth-child(2) {
			margin: 0 4rpx;
		}
	}
}

.list-wrapper {
	margin-top: 100rpx;

	.list-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 10rpx 30rpx 30rpx;
		box-sizing: border-box;
		background-color: rgba($color: #108ee9, $alpha: 0.05);
		color: #108ee9;

		image {
			width: 60rpx;
			height: 40rpx;
		}

		.list-item-right {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.face-model {
				font-size: 24rpx;
			}
		}
	}

	.list-item:nth-child(3) {
		color: var(--text-color);
	}

	.list-item:nth-child(8) {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		color: tomato;
		background-color: rgba(255, 99, 71, 0.05);

		image {
			svg {
				fill: tomato !important;
			}
		}
	}
}

.hover-more {
	background-color: rgba($color: #000000, $alpha: 0.07) !important;
}

.log-in {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 5rpx 15rpx;
}
</style>
