<template>
	<view class="min-page bg-f7 u-font-28 color-333 u-p-30">
		<view v-for="(item,index) in list" :key="index" class="block">
			<view class="font-bold u-font-32 ">序号{{index+1}}</view>
			<view class="u-m-t-32">
				<view class="font-bold u-m-b-14">单价</view>
				<view class="u-flex ">
					<up-input type="digit" placeholder="请输入单价" v-model="item.salePrice"
						@blur="salePriceBlur(item)"></up-input>
					<text class="u-m-l-24">元/根</text>
				</view>
			</view>
			<view class="u-m-t-32">
				<view class="font-bold u-m-b-14">数量</view>
				<up-input type="number" placeholder="请输入数量" v-model="item.number" @blur="numberBlur(item)"></up-input>
			</view>
		</view>

		<view class="bottom">
			<view class="font-bold">
				<text>合计：</text>
				<text class="color-red">{{totalMoney}}元</text>
				<text>/</text>
				<text>{{totalNumber}}根</text>
			</view>
			<view class="u-flex">
				<view class="btn main" @click="chooseImage">继续拍照</view>
				<view class="btn" @click="confirmOrder">下单</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		BigNumber
	} from "bignumber.js";
	import {
		computed,
		inject,
		onUnmounted,
		ref
	} from 'vue';
	import {
		hasPermission
	} from "@/commons/utils/hasPermission.js";
	import {
		stickCount
	} from '@/http/api/product/stick.js'
	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import go from "@/commons/utils/go.js";
	import {
		createOrder,
		getHistoryOrder
	} from "@/http/api/order.js";


	const websocketUtil = inject("websocketUtil"); // 注入 WebSocket 工具类实例
	const totalMoney = computed(() => {
		return list.value.reduce((prve, cur) => {
			return prve.plus(BigNumber(cur.number || 0).times(cur.salePrice || 0))
		}, BigNumber(0)).toNumber()
	})
	const totalNumber = computed(() => {
		return list.value.reduce((prve, cur) => {
			return prve.plus(BigNumber(cur.number || 0))
		}, BigNumber(0)).toNumber()
	})

	function chooseImage() {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ["album", "camera "],
			success: async function(res) {
				uni.showLoading({
					title: "上传中",
				});
				console.log(res);
				const fileRes = await stickCount(res.tempFiles[0]);
				uni.hideLoading();
				if (fileRes) {
					list.value.push({
						number: fileRes,
						salePrice: 0
					})
				} else {
					uni.showToast({
						title: "上传失败",
						icon: "none",
					});
				}
			},
		});
	}
	const list = ref([])
	const options = {}

	function salePriceBlur(item) {
		console.log('item', item)
		if (item.salePrice * 1 <= 0) {
			item.salePrice = 0
		}
		if (item.salePrice.split('.')[1] && item.salePrice.split('.')[1].length > 2) {
			item.salePrice = Number(item.salePrice).toFixed(2)
		}
	}

	function numberBlur(item) {
		if (item.number * 1 <= 0) {
			item.number = 0
		}
		if (item.number.split('.')[1] && item.number.split('.')[1].length >= 1) {
			item.number = Number(item.number.split('.')[0])
		}
	}

	function init(opt) {
		Object.assign(options, opt)
		initCart()
		if (opt.number) {
			list.value = [{
				number: opt.number,
				salePrice: 0
			}]
		}
	}
	/**
	 * 初始化购物车
	 */
	function initCart() {
		let params = {
			type: "onboc",
			account: uni.getStorageSync("iToken").loginId,
			shop_id: uni.getStorageSync("shopInfo").id,
			operate_type: "init",
			table_code: options.tableCode,
		};
		console.log("购物车初始化参数===", params);
		websocketUtil.send(JSON.stringify(params));
	}
	/**
	 * socket消息监听
	 */

	let hasReciveMsgLen = 0

	function onMessage() {
		websocketUtil.offMessage();
		websocketUtil.onMessage(async (res) => {
			let msg = JSON.parse(res);
			if (msg.msg_id) {
				websocketUtil.send(
					JSON.stringify({
						type: "receipt",
						msg_id: msg.msg_id,
					})
				);
			}
			if (statWatchMsg && msg.operate_type == "onboc_add") {
				if (sendMsgsku_names.value.find(v => msg.data.sku_name == v)) {
					hasReciveMsgLen++
				}
			}
			if (statWatchMsg && hasReciveMsgLen) {
				createAnOrder()
				hasReciveMsgLen = 0
				statWatchMsg = false;
				sendMsgsku_names.value = []
			}
			console.log('msg', msg)
		});
	}


	let sendMsgsku_names = ref([])
	let statWatchMsg = false

	function confirmOrder() {
		const isPas = list.value.every(v => {
			if (!v.number) {
				return false
			}
			if (v.salePrice < 0) {
				return false
			}
			return true
		})
		if (!isPas) {
			uni.showToast({
				title: '请输入正确的数量和单价',
				icon: 'none'
			})
		}
		statWatchMsg = true;
		for (let item of list.value) {
			const shop_id = uni.getStorageSync("shopInfo").id
			const roundNum = Math.floor(Math.random() * 10)
			const roundNum1 = Math.floor(Math.random() * 1000)
			const sku_name = `签子_${roundNum}_${shop_id}_${options.tableCode}_${roundNum1}`
			sendMsgsku_names.value.push(sku_name)
			websocketUtil.send(
				JSON.stringify({
					account: uni.getStorageSync("iToken").loginId,
					shop_id,
					type: "onboc",
					operate_type: "add",
					table_code: options.tableCode,
					product_name: '签子',
					is_gift: 0,
					pack_number: 0,
					discount_sale_amount: item.salePrice,
					number: item.number * 1,
					sku_name,
					is_temporary: 1, //是否是临时菜
					is_qz: 1
				})
			);
		}




		setTimeout(() => {
			// createAnOrder()
			// toConfimOrder()
		}, 200)
	}


	async function createAnOrder() {
		const shopInfo = uni.getStorageSync('shopInfo')
		if (
			shopInfo.registerType == "before"
		) {
			const canJiesuan = await hasPermission("允许收款");
			if (!canJiesuan) {
				return;
			}
		}
		const stickData = uni.getStorageSync('stickData')
		const orderInfo = stickData.orderInfo

		let placeNum = orderInfo ? orderInfo.placeNum + 1 : 1;
		let par = {
			shopId: shopInfo.id, //店铺Id
			userId: '', //用户Id
			tableCode: options.tableCode, //台桌编码
			dineMode: 'dine-in', //用餐模式 堂食 dine-in 外带 take-out 外卖 take-away
			remark: '', //备注
			seatNum: 0, //用餐人数
			packFee: 0, //打包费
			originAmount: 0, //订单原金额（不包含打包费+餐位费）
			placeNum: placeNum, //当前订单下单次数
			waitCall: 0, //是否等叫 0 否 1 等叫
			vipPrice: 0, //是否使用会员价
			limitRate: stickData.limitTimeDiscount,
		};

		if (stickData.orderInfo && shopInfo.registerType != "before") {
			par.orderId = stickData.orderInfo.id;
		}
		let res = null;
		res = await createOrder(par);
		console.log(res, "创建订单");
		if (!res) {
			uni.showToast({
				title: res.msg || "创建订单失败！",
				icon: "none",
			});
			return;
		}
		uni.$emit("update:createOrderIndex");
		websocketUtil.send(
			JSON.stringify({
				type: "onboc",
				account: uni.getStorageSync("iToken").loginId,
				shop_id: uni.getStorageSync("shopInfo").id,
				operate_type: "cleanup",
				table_code: stickData.table.tableCode,
			})
		);
		uni.removeStorageSync("table_code");

		if (
			shopInfo.registerType == "before"
		) {
			//先付
			return go.to(
				"PAGES_ORDER_DETAIL", {
					id: res.id || stickData.orderInfo.id,
					dinnerType: 'dine-in',
				},
				"redirect"
			);
		} else {
			if (!res.id && stickData.orderInfo.id) {
				return go.to(
					"PAGES_ORDER_PAY", {
						orderId: stickData.orderInfo.id,
						isNowPay: true,
						dinnerType: 'dine-in',
					},
					"redirect"
				);
			}
			//后付
			if (options.isCreateOrderToDetail != "0") {
				go.to(
					"PAGES_ORDER_DETAIL", {
						id: res.id || stickData.orderInfo.id,
						dinnerType: 'dine-in',
					},
					"redirect"
				);
			} else {
				uni.navigateBack({
					delta: 1,
				});
			}
		}
		uni.showToast({
			title: "提交成功",
			icon: "none",
		});
	}

	function toConfimOrder() {
		const stickData = uni.getStorageSync('stickData')
		console.log(stickData);
		const {
			name,
			status,
			type
		} = stickData.table;


		let shopInfo = uni.getStorageSync("shopInfo");

		go.to("PAGES_CONFIRM_ORDER", {
			type: type,
			tableId: stickData.table.id,
			tableCode: stickData.table.tableCode,
			name: name,
			status: status,
			isCreateOrderToDetail: options.isCreateOrderToDetail ? 1 : 0,
		});
	}

	onLoad(init)

	onHide(() => {
		console.log("onHide");
		websocketUtil.offMessage();
	});
	onShow(() => {
		onMessage();
	})
	onUnmounted(() => {
		console.log("onUnmounted");
		websocketUtil.offMessage();
	});
</script>

<style lang="scss">
	.block {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 28rpx;
		margin-bottom: 32rpx;

	}

	.bottom {
		display: flex;
		padding: 24rpx 32rpx;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding-bottom: 40rpx;
		background-color: #fff;
		z-index: 10;

		.btn {
			padding: 16rpx 24rpx;
			border-radius: 12rpx;
			background-color: #f2f2f2;
			margin-left: 24rpx;
			min-width: 188rpx;
			text-align: center;

			&.main {
				background-color: $my-main-color;
				color: #fff;
				font-weight: 700;
				font-size: 32rpx;
			}
		}
	}
</style>