<template>
	<view class="bg-gray min-page u-p-30 u-font-28">
		<view class="u-p-t-60 u-p-b-60 u-text-center">
			<view class="u-font-32">
				<text class="price-fuhao">￥</text>
				<text class="font-bold price">{{ orderCostSummary.finalPayAmount }}</text>
			</view>
			<view class="u-m-t-10 color-999 old-price" v-if="orderCostSummary.merchantReduction.actualAmount">
				<text class="">￥</text>
				<text class=" ">{{ returnMerchantReductionBeforeMoney }}</text>
			</view>
			<view class="u-m-t-10 u-flex u-row-center color-main">
				<view @click="discountShow">修改</view>
			</view>
			<view class="u-m-t-10 u-flex u-row-center color-main u-m-t-24">
				<view @click="chooseUser()">选择用户</view>
			</view>
		</view>
		<view class="content bg-fff border-r-12">
			<view class="u-p-l-26 u-p-r-26 card top u-m-t-30">
				<view class="border-bottom-dashed u-p-b-30 u-p-t-30" v-if="orderCostSummary.newUserDiscount">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between">
						<view>新客立减</view>
						<view class="color-red">-￥{{ orderCostSummary.newUserDiscount }}</view>
					</view>
				</view>
				<view class="border-bottom-dashed u-p-b-30 u-p-t-30" v-if="orderCostSummary.vipDiscountAmount">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between">
						<view>会员折扣</view>
						<view class="color-red">-￥{{ orderCostSummary.vipDiscountAmount }}</view>
					</view>
				</view>
				<view class="border-bottom-dashed u-p-b-30 u-p-t-30" v-if="orderCostSummary.merchantReduction.actualAmount">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between">
						<view>商家减免</view>
						<view class="color-red">-￥{{ orderCostSummary.merchantReduction.actualAmount }}</view>
					</view>
				</view>
				<view class="border-bottom-dashed u-p-b-30 u-p-t-30" v-if="orderCostSummary.fullReduction.actualAmount && orderCostSummary.fullReduction.usedThreshold">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between">
						<view>满减活动</view>
						<view class="color-red">-￥{{ orderCostSummary.fullReduction.actualAmount }}</view>
					</view>
				</view>

				<view class="border-bottom-dashed u-p-b-30 u-p-t-30">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between" @click="toQuan">
						<view>优惠券</view>
						<view class="color-999 u-flex u-col-center">
							<text class="color-red" v-if="orderCostSummary.fullReduction.usedThreshold">满减活动不可与优惠券同享</text>
							<text v-else-if="orderCostSummary.couponDeductionAmount <= 0">选择优惠券</text>
							<text class="color-red" v-else>-￥{{ orderCostSummary.couponDeductionAmount }}</text>

							<view class="u-flex u-col-center" v-if="!orderCostSummary.fullReduction.usedThreshold">
								<uni-icons type="right" color="#999"></uni-icons>
							</view>
						</view>
					</view>
				</view>

				<view class="border-bottom u-p-b-30" v-if="discount.value || accountPoints.sel">
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between u-p-t-30" v-if="discount.value">
						<view>服务员改价</view>
						<view class="u-flex u-col-center">
							<text style="color: rgb(255, 95, 46)">-￥{{ to2(discount.value) }}</text>
						</view>
					</view>
					<view class="u-flex u-p-l-24 u-p-r-24 u-row-between u-p-t-30" v-if="orderCostSummary.pointDeductionAmount && accountPoints.sel">
						<view>积分抵扣</view>
						<view class="u-flex u-col-center">
							<text style="color: rgb(255, 95, 46)">-￥{{ orderCostSummary.pointDeductionAmount }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="bg-fff border-r-12">
				<view class="u-p-t-30 u-p-l-50 u-p-r-50 card bottom">
					<my-tabs :list="pays.list" v-model="pays.selIndex"></my-tabs>
					<template v-if="pays.selIndex == 0">
						<view class="list">
							<view class="item" @click="changePayType(index, item)" :class="{ disabled: item.disabled }" v-for="(item, index) in pays.payTypes.list" :key="index">
								<view class="u-flex u-row-between u-p-t-30 u-p-b-30 border-bottom">
									<view class="u-flex">
										<image class="icon" :src="item.icon" mode=""></image>
										<text class="u-m-l-10 no-wrap">{{ item.payName }}</text>
									</view>
									<view class="u-flex color-999 u-font-24">
										<view class="u-m-r-20" v-if="item.payType == 'virtual' && pageData.buyer.id" @click.stop="chooseBuyer">
											<view>
												<text>挂账人：</text>
												<text class="u-m-r-4">{{ pageData.buyer.debtor }}</text>
											</view>
											<view>
												<text>挂账额度：</text>
												<text>￥{{ (pageData.buyer.creditAmount+pageData.buyer.accountBalance) || '0' }}</text>
											</view>
										</view>
										<view class="u-m-r-20" v-if="item.payType == 'member-account' && pageData.user.id" @click.stop="chooseUser">
											<view>
												<text>会员：</text>
												<text class="u-m-r-4">{{ pageData.user.phone || pageData.user.nickName }}</text>
											</view>
											<view>
												<text>余额：</text>
												<text>￥{{ pageData.user.amount || '0' }}</text>
											</view>
											<!-- <view>
												  <text>积分：</text>
												  <text>{{user.accountPoints||'0'}}</text>
											  </view> -->
										</view>
										<view :class="{ op3: item.disabled }">
											<my-radio @click="changePayType(index, item)" :modelValue="index == pays.payTypes.selIndex"></my-radio>
										</view>
									</view>
								</view>
							</view>
						</view>
						<input class="cash-input" type="text" placeholder="请输入现金支付备注（选填）" v-model="cashRemark" v-if="gyqPayType == 'cash'" />
						<view class="border-bottom-dashed"></view>
						<view class="u-flex u-row-between u-p-t-24" v-if="pageData.user.id" @click="changeAccountPoints">
							<view class="u-flex">
								<view class="">积分抵扣</view>
								<view class="color-999 u-m-l-10">
									<text>(</text>
									<text>{{ pageData.user.pointBalance || '0' }}</text>
									<text>)</text>
								</view>
								<!-- <view><text class="color-red font-bold">{{accountPoints.price}}</text>元</view> -->
							</view>
							<view class="u-flex">
								<view class="u-flex">
									<view>
										<text>{{ userPoints }}</text>
									</view>
									<view v-if="pointDeductionRule.enableRewards && accountPoints.sel" @click.stop="refPointsOpen">
										<up-icon name="edit-pen" size="16" color="#999"></up-icon>
									</view>
								</view>
								<view class="u-m-l-32 u-relative" v-if="pointDeductionRule.enableRewards">
									<view class="u-absolute position-all"></view>
									<my-radio :modelValue="accountPoints.sel"></my-radio>
								</view>
							</view>
						</view>
						<view class="color-999 u-font-24 u-m-t-16">
							<view class="" v-if="!pointDeductionRule.enableRewards">
								<text class="color-red">*</text>
								<text>积分不可用</text>
							</view>
							<view class="" v-if="pointDeductionRule.enableRewards">
								<text class="color-red">*</text>
								<text class="" v-if="pointDeductionRule.enableRewards">
									「可用积分{{ pageData.user.id ? pageData.user.pointBalance : 0 }}，最大可抵扣{{ maxPointDiscount }}元」
								</text>
							</view>
						</view>
						<view class="u-m-t-60 u-p-b-30">
							<my-button @click="payOrderClick">确认付款</my-button>
						</view>
					</template>
					<template v-if="pays.selIndex == 1">
						<view class="u-font-32 u-m-t-40 u-text-center">请让顾客使用微信/支付宝扫码</view>
						<view class="u-flex u-row-center u-m-t-40">
							<up-qrcode cid="code" :size="140" :val="payCodeUrl"></up-qrcode>
						</view>
					</template>
				</view>

				<!-- 二维码支付扫码 -->
				<template v-if="pays.selIndex == 1">
					<view class="card border-bottom top u-m-t-32"></view>
					<view class="bg-fff card bottom border-r-12 u-p-32">
						<view class="font-bold u-font-32 u-text-center">￥{{ payPrice }}</view>
						<view class="u-flex u-row-center u-m-t-24">
							<template v-if="order.status == 'unpaid'">
								<up-loading-icon size="14" text="等待支付"></up-loading-icon>
							</template>
							<template v-if="order.status == 'done'">
								<view class="u-flex pay-success">
									<up-icon color="#5CBB6F" name="checkmark-circle-fill"></up-icon>
									<view class="u-m-l-6">支付成功</view>
								</view>
							</template>
						</view>
					</view>
				</template>
			</view>
		</view>

		<edit-discount
			@confirm="editDiscountConfirm"
			title="优惠金额"
			:ref="setModel"
			name="editMoney"
			:price="returnMerchantReductionBeforeMoney"
			:discount="discount.discount"
		></edit-discount>

		<up-modal
			:title="modal.title"
			:content="modal.content"
			:show="modal.show"
			:confirmText="modal.confirmText"
			:cancelText="modal.cancelText"
			showCancelButton
			closeOnClickOverlay
			@confirm="confirmModelConfirm"
			@cancel="confirmModelCancel"
			@close="confirmModelCancel"
			width="300px"
		/>

		<edit-accountPoints
			@confirm="pointsConfirm"
			:price="userPoints"
			:pointDeductionRule="pointDeductionRule"
			:maxCanUsePoints="maxCanUsePoints"
			ref="refPoints"
		></edit-accountPoints>
	</view>
</template>

<script setup>
import { reactive, onMounted, nextTick, watch, ref, onBeforeUnmount, computed, inject } from 'vue';
import { onLoad, onBackPress, onShow } from '@dcloudio/uni-app';
import BigNumber from 'bignumber.js';
import go from '@/commons/utils/go.js';
import infoBox from '@/commons/utils/infoBox.js';
import { hasPermission } from '@/commons/utils/hasPermission.js';
import editDiscount from '@/components/my-components/edit-discount.vue';
import editAccountPoints from './components/edit-accountPoints.vue';
import { returnGoodsPayPriceMap, returnProCoupStartIndex, returnProductCoupAllPrice, returnProductCanUseNum } from '../quan_util.js';
import { mathFloorPrice } from '@/commons/utils/goodsUtil.js';
import { getDiscountByUserId } from '@/http/yskApi/market/consumeDiscount.js';
import { pointsConfig } from '@/http/api/market/points.js';
// import { getCouponList } from '@/http/api/coupon.js'
import { getHistoryOrder } from '@/http/api/order.js';
import { getPayTypeList } from '@/http/api/payType.js';
import { shopUserDetail } from '@/http/api/shopUser.js';
import { discountActivity } from '@/http/yskApi/market/discountActivity.js';

import {
	// scanPay,
	microPay,
	cashPay,
	vipPay,
	creditPay,
	getOrderPayUrl,
	queryOrderStatus
} from '@/http/api/pay.js';
import { calcUsablePoints, calcDeductionAmount, payedDeductPoints, consumeAwardPoints } from '@/http/api/points.js';

import yskUtils from 'ysk-utils';
//   import yskUtils from "@/lib/index";

const websocketUtil = inject('websocketUtil'); // 注入 WebSocket 工具类实例
const modal = reactive({
	title: '提示',
	cancelText: '取消',
	confirmText: '确认',
	content: '',
	key: 'cash',
	show: false,
	data: ''
});

const pageData = reactive({
	goodsList: [], //菜品列表
	user: {
		//会员信息
		userId: null,
		amount: 0
	},
	shopInfo: uni.getStorageSync('shopInfo'),
	buyer: {},
	payUrlShow: false
});
const order = reactive({
	orderAmount: 0
});

const pays = reactive({
	list: ['扫码收款', '二维码收款'],
	selIndex: 0,
	payTypes: {
		list: [],
		selIndex: 0
	},
	quan: [],
	seatNum: 0
});
//打折相关数据
const discount = reactive({
	discount: 100,
	currentPrice: 0,
	value: 0
});

const accountPoints = reactive({
	sel: false,
	num: 0,
	calcRes: {
		usable: false,
		unusableReason: '',
		minDeductionPoints: 0,
		maxUsablePoints: 0
	},
	price: 0
});
let timer = null;

const refPoints = ref(null);
let payCodeUrl = ref(''); //收款二维码地址
onShow(() => {
	watchChooseuser();
	watchChoosebuyer();
	watchChooseQuan();
});
const options = reactive({});
async function getDiscountActivity() {
	let res = await discountActivity({
		shopId: uni.getStorageSync('shopInfo').id || ''
	});
	if (res) {
		fullReductionActivities.value = res ? [res] : [];
	}
}
async function getPointsConfig() {
	let res = await pointsConfig();
	if (res) {
		const { equivalentPoints, maxDeductionAmount, enableRewards, minPaymentAmount, maxDeductionRatio } = res;

		pointDeductionRule.pointsPerYuan = equivalentPoints || 0;
		pointDeductionRule.maxDeductionAmount = maxDeductionAmount || 0;
		pointDeductionRule.maxDeductionRatio = maxDeductionRatio || 0;
		pointDeductionRule.enableRewards = enableRewards || 0;
		pointDeductionRule.minPaymentAmount = minPaymentAmount || 0;
		console.log('pointDeductionRule', pointDeductionRule);
	}
}
onLoad(async (opt) => {
	Object.assign(order, opt);
	Object.assign(options, opt);
	await getPayType();
	await getDiscountActivity();
	await getPointsConfig();
	console.log('pays.payTypes.list');
	init();
});
onBeforeUnmount(() => {
	clearInterval(timer);
	timer = null;
});
onBackPress(() => {
	uni.$emit('orderDetail:update');
	console.log('onBackPress');
});

function toDiancai() {
	setTimeout(() => {
		go.to('PAGES_CREATE_ORDER', {}, 'redirect');
	}, 1500);
}

/**
 * 初始化
 */
async function init() {
	nextTick(() => {
		onMessage();
	});
	// 获取订单详情
	const orderRes = await getHistoryOrder({
		orderId: order.orderId
	});
	if (orderRes.status == 'cancelled') {
		uni.showToast({
			title: '订单已取消',
			icon: 'none'
		});
		toDiancai();
		return;
	}
	if (orderRes.status == 'done') {
		uni.showToast({
			title: '订单已完成',
			icon: 'none'
		});
		toDiancai();
		return;
	}
	Object.assign(order, orderRes);
	pageData.goodsList = objToArrary(orderRes.detailMap);
	// console.log("order===",order)
	// console.log("pageData.user===",pageData.user)
	// 获取用户信息

	if (order.userId || pageData.user.userId) {
		shopUserDetail({
			userId: order.userId || pageData.user.userId
		}).then((res) => {
			if (res) {
				pageData.user = res;
				getCalcUsablePoints();
				if (orderRes.pointsNum) {
					accountPoints.sel = true;
				}
			}
		});
	}
	pageData.seatNum = order.seatNum;
	seatFeeConfig.personCount = order.seatNum;
	console.log('seatFeeConfig',seatFeeConfig);
}

/**
 * 判断是否是会员
 */
const isVip = computed(() => {
	return uni.getStorageSync('shopInfo').isMemberPrice && pageData.user && pageData.user.id && pageData.user.isVip;
});

const coupAllPrice = computed(() => {
	const n = pays.quan.reduce((prve, cur) => {
		return prve + cur.discountAmount * 1;
	}, 0);
	return n;
});

/**
 * 桌位费
 */
const tableFee = computed(() => {
	// console.log("桌位费===", order.seatNum > 0 ? order.seatNum*pageData.shopInfo.tableFee : 0)
	return order.seatNum > 0 ? order.seatNum * pageData.shopInfo.tableFee : 0;
});

// 计算商家减免前金额（使用bignumber.js确保精度）
const returnMerchantReductionBeforeMoney = computed(() => {
	const total = BigNumber(orderCostSummary.value.finalPayAmount).plus(orderCostSummary.value.merchantReduction.actualAmount);
	// 确保结果不小于0，返回数字类型
	return total.lte(0) ? 0 : total.toNumber();
});

//选择的优惠券
const selCoupon = ref([]);
//活动列表
const activityList = ref([]);
// 商家减免，初始配置：默认无减免（固定金额 0 元）
const merchantReductionConfig = reactive({
	type: 'fixed_amount',
	fixedAmount: 0
});
//积分规则
const pointDeductionRule = reactive({
	enableRewards: 0, //是否开启
	pointsPerYuan: 0,
	maxDeductionAmount: Infinity,
	maxDeductionRatio: 0, //积分抵扣比例
	minPaymentAmount: 0 //门槛
});
//餐费费
const seatFeeConfig = reactive({
	pricePerPerson: pageData.shopInfo.tableFee || 0,
	personCount: 0, //就餐人数
	isEnabled: !pageData.shopInfo.isTableFee,
});
//使用积分数量
const userPoints = ref(0);
//是否使用会员价
const useVipPrice = computed(() => {
	console.log('pageData.shopInfo', pageData.shopInfo);
	if (pageData.shopInfo.isMemberPrice == 1 && pageData.user.isVip == 1) {
		return true;
	}
	return false;
});
//新客立减
const newUserDiscount = ref(0);
//满减活动
const fullReductionActivities = ref([]);
// 商家霸王餐配置
const freeDineConfig = ref(null);
//店铺用户
const shopUserInfo = ref({});
//限时折扣
const limitTimeDiscount = ref(null);
// const orderExtraConfig = reactive({
//   // 引用扩展后的商家减免配置
//   merchantReduction: merchantReductionConfig,
//   additionalFee: 0,
//   pointDeductionRule: pointDeductionRule,
//   seatFeeConfig: seatFeeConfig,
//   currentStoreId: "",
//   userPoints: userPoints.value,
//   isMember: useVipPrice.value,
//   memberDiscountRate: 1,
//   newUserDiscount: newUserDiscount.value,
//   fullReductionActivities: fullReductionActivities.value,
//   currentDinnerType: options.dinnerType,
//   isFreeDine: false, //霸王餐
//   freeDineConfig: freeDineConfig.value,
//   limitTimeDiscount: order.limitRate,
//   shopUserInfo: shopUserInfo.value,
// });
const orderExtraConfig = computed(() => {
	return {
		// 引用扩展后的商家减免配置
		merchantReduction: merchantReductionConfig,
		additionalFee: 0,
		pointDeductionRule: pointDeductionRule,
		seatFeeConfig: seatFeeConfig,
		currentStoreId: '',
		userPoints: userPoints.value,
		isMember: useVipPrice.value,
		memberDiscountRate: 1,
		newUserDiscount: newUserDiscount.value,
		fullReductionActivities: fullReductionActivities.value,
		currentDinnerType: options.dinnerType||order.dineMode,
		isFreeDine: false, //霸王餐
		freeDineConfig: freeDineConfig.value,
		limitTimeDiscount: order.limitRate,
		shopUserInfo: pageData.user
	};
});
// 订单费用汇总
const orderCostSummary = computed(() => {
	const costSummary = yskUtils.OrderPriceCalculator.calculateOrderCostSummary(
		pageData.goodsList,
		(options.dinnerType||order.dineMode),
		selCoupon.value,
		activityList.value,
		orderExtraConfig.value,
		{},
		new Date()
	);
	console.log(' 订单费用汇总', costSummary);
	return costSummary;
});

//积分可抵扣最大金额
const pointsCanDicountMaxMoney = computed(() => {
	const maxMoney = orderCostSummary.value.finalPayAmount + orderCostSummary.value.pointDeductionAmount;
	console.log('pointsCanDicountMaxMoney.value', maxMoney);
	return maxMoney;
});

/**
 * 支付金额
 */
const payPrice = computed(() => {
	return orderCostSummary.value.finalPayAmount;
});

watch(
	() => accountPoints.sel,
	(newval) => {
		if (newval) {
			userPoints.value = maxCanUsePoints.value;
		} else {
			userPoints.value = 0;
		}
	}
);

watch(
	() => pointsCanDicountMaxMoney.value,
	(newval) => {
		if (pageData.user.id) {
			getCalcUsablePoints();
		}
	}
);
watch(
	() => pageData.user.id,
	(newval) => {
		if (newval) {
			getCalcUsablePoints();
		}
	}
);
watch(
	() => orderCostSummary.value.finalPayAmount,
	(newval) => {
		if (pageData.payUrlShow) {
			setTimeout(() => {
				getPayUrl();
			});
		}
		if (newval <= 0) {
			const arr = ['cash', 'member-account'];
			pays.payTypes.list.map((v) => {
				if (arr.includes(v.payType)) {
					v.disabled = false;
				} else {
					v.disabled = true;
				}
			});
			const index = pays.payTypes.list.findIndex((v) => !v.disabled);
			pays.payTypes.selIndex = index;
		} else {
			pays.payTypes.list.map((v) => {
				v.disabled = false;
			});
		}
	},
	{
		immediate: true
	}
);

watch(
	() => pays.selIndex,
	(newval) => {
		clearInterval(timer);
		if (newval) {
			timer = setInterval(() => {
				getHistoryOrder({
					orderId: order.orderId
				}).then((res) => {
					order.status = res.status;
					if (res.status == 'done') {
						paySuccess();
					}
				});
			}, 2000);
			if (newval == 1) {
				getPayUrl();
			}
		}
	}
);

function getPayParam() {
	const dinnerType=options.dinnerType||order.dineMode
	let params = {
		shopId: uni.getStorageSync('shopInfo').id || '',
		orderId: order.id,
		originAmount: orderCostSummary.value.goodsRealAmount, //订单原金额（不包含打包费+餐位费）
		discountRatio: 1,
		discountAmount: orderCostSummary.value.merchantReduction.actualAmount, //手动优惠金额
		productCouponDiscountAmount: orderCostSummary.value.productCouponDeduction, //商品优惠券抵扣金额
		otherCouponDiscountAmount: orderCostSummary.value.fullCouponDeduction, //其他优惠券抵扣金额
		couponList: selCoupon.value.map((v) => v.id), //用户使用的卡券
		orderAmount: orderCostSummary.value.finalPayAmount, // 订单金额
		roundAmount: 0, //抹零金额 减免多少钱
		pointsDiscountAmount: orderCostSummary.value.pointDeductionAmount, //积分抵扣金额(tb_points_basic_setting表)
		pointsNum: orderCostSummary.value.pointUsed, //(扣除各类折扣 enable_deduction后使用)
		seatNum: dinnerType == 'dine-in' ? seatFeeConfig.personCount : 0, //用餐人数
		newCustomerDiscountAmount: orderCostSummary.value.newUserDiscount, //新客立减
		newCustomerDiscountId: orderCostSummary.value.newUserDiscount > 0 ? newUserDiscountRes.value.id : '',

		discountActAmount: orderCostSummary.value.fullReduction.actualAmount, //满减抵扣金额
		discountActId:
			orderCostSummary.value.fullReduction.usedActivity && orderCostSummary.value.fullReduction.usedThreshold ? orderCostSummary.value.fullReduction.usedActivity.id : null,
		vipPrice: isVip.value ? 1 : 0, // 是否使用会员价
		limitRate:
			order.limitRate && order.limitRate.id
				? {
						id: order.limitRate.id,
						discountRate: order.limitRate.discountRate,
						discountPriority: order.limitRate.discountPriority,
						foodType: order.limitRate.foodType,
						foods: order.limitRate.foods
				  }
				: null,
		vipDiscountAmount: orderCostSummary.value.vipDiscountAmount //会员折扣减免金额
	};
	if (pays.quan.length > 0) {
		pays.quan.forEach((v) => {
			params.couponList.push(v.id);
		});
	}
	params.couponList = params.couponList.join(',');
	// params.couponList = JSON.stringify(params.couponList)
	return params;
}

/**
 * 获取店铺订单支付URL
 */
function getPayUrl() {
	console.log('支付参数 ===', getPayParam());
	let par = getPayParam();
	let params = {
		shopId: uni.getStorageSync('shopInfo').id || '',
		...par
	};
	if (order.userId || pageData.user.userId) {
		params.userId = order.userId || pageData.user.userId;
	}
	getOrderPayUrl(params).then((res) => {
		console.log(res, 'tishi');
		payCodeUrl.value = res;
		pageData.payUrlShow = true;
	});
}

/**
 * 获取支付方式
 */
async function getPayType() {
	const payTypeList = await getPayTypeList();
	pays.payTypes.list = [];
	const arr = ['cash', 'member-account'];
	payTypeList.map((v) => {
		if (v.payType != 'bank') {
			let disabled = false;
			if (orderCostSummary.value.finalPayAmount <= 0) {
				if (arr.includes(v.payType)) {
					disabled = false;
				} else {
					disabled = true;
				}
			}
			pays.payTypes.list.push({
				...v,
				disabled
			});
		}
	});
}

/**
 * 设置优惠券/商品券
 * @param {Object} arr
 */
function setQuan(arr) {
	selCoupon.value = arr;
	console.log('赋值优惠券', arr);
}

/**
 * 积分选择
 */
function refPointsOpen() {
	if (!pointDeductionRule.enableRewards && accountPoints.sel) {
		return;
	}
	refPoints.value.open();
}

/**
 * 积分确认
 * @param {Object} e
 */
function pointsConfirm(e) {
	userPoints.value = e;
}

const maxPointDiscount = ref(0);
const maxCanUsePoints = ref(0);

/**
 * 获取积分信息
 * @param {Object} orderAmount
 */
async function getCalcUsablePoints() {
	if (!pageData.user.userId) {
		return;
	}

	let userAccountPoints = pageData.user ? pageData.user.pointBalance * 1 : 0;

	//1积分等于多少钱
	const onePointsMoney = pointDeductionRule.pointsPerYuan ? (1 || 0) / pointDeductionRule.pointsPerYuan : 0;

	const calcMaxDiscount = Math.floor(pointsCanDicountMaxMoney.value * (pointDeductionRule.maxDeductionRatio / 100));
	const userMaxDiscount = BigNumber(userAccountPoints).times(onePointsMoney).decimalPlaces(2, BigNumber.ROUND_DOWN).toNumber();

	maxPointDiscount.value = Math.min(calcMaxDiscount, userMaxDiscount);
	console.log('积分最大可抵扣金额', maxPointDiscount.value);
	pointDeductionRule.maxDeductionAmount = maxPointDiscount.value || 0;
	if (pointDeductionRule.enableRewards) {
		let num = (maxPointDiscount.value || 0) * pointDeductionRule.pointsPerYuan;
		if (num > userAccountPoints) {
			num = userAccountPoints;
		}
		maxCanUsePoints.value = num;
		if (accountPoints.sel) {
			userPoints.value = num;
		}
	}

	if (!pointDeductionRule.enableRewards) {
		userPoints.value = 0;
	}
	console.log('maxCanUsePoints.value', maxCanUsePoints.value);
}

function changeAccountPoints() {
	if (!pointDeductionRule.enableRewards) {
		return;
	}
	accountPoints.sel = !accountPoints.sel;
	if (!accountPoints.sel) {
		accountPoints.num = 0;
	}
}

/**
 * 选择优惠券
 */
function toQuan() {
	if (orderCostSummary.value.fullReduction.usedThreshold) {
		return infoBox.showToast('满减活动不可与优惠券同享');
	}
	if (!order.userId && !pageData.user.id) {
		return infoBox.showToast('请先选择会员', 0.5).then(() => {
			chooseUser();
		});
	}
	uni.setStorageSync('selCoupon', selCoupon.value);

	go.to('PAGES_ORDER_QUAN', {
		orderId: order.id,
		shopUserId: pageData.user.id,
		orderPrice: BigNumber(payPrice.value).plus(BigNumber(orderCostSummary.value.couponDeductionAmount)).decimalPlaces(2, BigNumber.ROUND_DOWN)
	});
}

/**
 * 判断是否可以修改金额
 */
async function discountShow() {
	const bol = await hasPermission('yun_xu_da_zhe');
	if (bol) {
		showModel('editMoney', true);
	}
}

/**
 * 积分金额处理
 * @param {Object} n
 */
function to2(n) {
	if (!n) {
		return '';
	}
	return Number(n).toFixed(2);
}

/**
 * 优惠券选择
 */
function watchChooseQuan() {
	uni.$off('selCoupon');
	uni.$on('selCoupon', function (data) {
		setQuan(data);
	});
}

/**
 * 删除优惠券
 * @param {Object} i
 */
function delQuan(i) {
	pays.quan.splice(i, 1);
	discount.discount = 100;
	discount.value = 0;
}

/**
 * 选择用户
 */
function chooseUser() {
	go.to('PAGES_CHOOSE_USER');
}

/**
 * 更新选择用户
 */
function watchChooseuser() {
	uni.$off('choose-user');
	uni.$on('choose-user', (data) => {
		pageData.user = data;
	});
}

watch(
	() => pageData.user.id,
	(newval) => {
		selCoupon.value = [];
		accountPoints.sel = false;
		merchantReductionConfig.fixedAmount = 0;
		// 更新购物车和历史订单数据
		uodateCartAndHistory();
		if (newval) {
			getNewUserDiscount();
			// getShopUserDetail();
		}
	}
);

/**
 * 更新购物车和历史订单数据
 */
function uodateCartAndHistory() {
	let newData = {
		history: [],
		cart: []
	};
	for (let cart of pageData.goodsList) {
		const canUseLimitTimeDiscount = yskUtils.limitUtils.canUseLimitTimeDiscount(cart, order.limitRate, pageData.shopInfo, pageData.user, 'productId') ? 1 : 0;
		if (canUseLimitTimeDiscount != cart.isTimeDiscount) {
			newData.history.push({
				id: cart.id,
				is_time_discount: canUseLimitTimeDiscount
			});
		}
	}

	if (newData.history.length <= 0 && newData.cart.length <= 0) {
		return;
	}

	websocketUtil.send(
		JSON.stringify({
			type: 'pad',
			account: uni.getStorageSync('shopInfo').id,
			shop_id: uni.getStorageSync('shopInfo').id,
			operate_type: 'bulk_edit',
			table_code: order.takeCode,
			data: newData
		})
	);
}

function getShopUserDetail() {
	shopUserDetail({
		// shopId: uni.getStorageSync("shopInfo").id,
		id: pageData.user.id
	}).then((res) => {
		if (res) {
			pageData.user = res;
		}
	});
}

const newUserDiscountRes = ref(null);
//获取用户新客立减
function getNewUserDiscount() {
	getDiscountByUserId({
		shopUserId: pageData.user.id
	}).then((res) => {
		if (res) {
			newUserDiscount.value = res.amount || 0;
			newUserDiscountRes.value = res;
		}
	});
}

/**
 * 选择挂账人
 */
function chooseBuyer() {
	go.to('PAGES_CHOOSE_BUYER');
}

/**
 * 更新选择挂账人
 */
function watchChoosebuyer() {
	uni.$off('choose-buyer');
	uni.$on('choose-buyer', (data) => {
		pageData.buyer = data;
	});
}

/**
 * 修改价格确认
 * @param {Object} form
 */
function editDiscountConfirm(form) {
	accountPoints.sel = false;
	console.log(form);
	const discount = BigNumber(returnMerchantReductionBeforeMoney.value).minus(form.currentPrice).toNumber();
	merchantReductionConfig.fixedAmount = discount;
}

/**
 * 支付方式选择
 * @param {Object} i
 * @param {Object} item
 */
const gyqPayType = ref('');
function changePayType(i, item) {
	if (item.disabled) {
		return infoBox.showToast(item.payName + '不可用');
	}
	gyqPayType.value = item.payType;
	pays.payTypes.selIndex = i;
	if (item.payType == 'member-account' && !pageData.user.id) {
		chooseUser();
	}
	if (item.payType == 'virtual' && !pageData.buyer.id) {
		chooseBuyer();
	}
}

const models = new Map();

function setModel(el) {
	if (el && el.$attrs['name']) {
		models.set(el.$attrs['name'], el);
	}
}

function showModel(key) {
	const model = models.get(key);
	model && model.open();
}

let payStatus = '';

/**
 * 确认付款
 */
const tipsMap = {
	paying: '支付中',
	success: '已支付成功'
};

function payOrderClick() {
	const payType = pays.payTypes.list[pays.payTypes.selIndex].payType;
	if (payType == 'scanCode' || payType == 'deposit') {
		return saomaPay(payType);
	}
	if (payType == 'cash' && payPrice.value * 1 > 0) {
		return cashConfirmShow();
	}
	if (payType == 'virtual' && pageData.buyer.remainingAmount < payPrice.value * 1) {
		return infoBox.showToast('挂账额度不足');
	}
	if (payType == 'member-account' && pageData.user.amount * 1 < payPrice.value * 1) {
		return infoBox.showToast('余额不足');
	}
	if (payStatus) {
		return infoBox.showToast(tipsMap[payStatus]);
	}
	try {
		pay();
	} catch (e) {
		//TODO handle the exception
		payStatus = '';
	}
}

/**
 * 支付调佣
 * @param {Object} par
 */
const cashRemark = ref('');
async function pay(par) {
	const payType = pays.payTypes.list[pays.payTypes.selIndex].payType;
	let pars = getPayParam();
	payStatus = 'paying';
	let params = {
		shopId: uni.getStorageSync('shopInfo').id || '',
		checkOrderPay: {
			...pars,
			remark: cashRemark.value
		},
		...par
	};
	if (order.userId || pageData.user.userId) {
		params.checkOrderPay.userId = order.userId || pageData.user.userId;
	}
	if (payType == 'virtual') {
		params.creditBuyerId = pageData.buyer.id;
	}
	let payRes = null;
	try {
		if (payType == 'scanCode') {
			payRes = await microPay(params);
		}
		if (payType == 'cash') {
			payRes = await cashPay(params);
		}
		if (payType == 'virtual') {
			payRes = await creditPay(params);
		}
		if (payType == 'member-account' || payType == 'deposit') {
			if (pageData.user.amount * 1 >= payPrice.value * 1) {
				params.payType = 'userPay';
				params.shopUserId = pageData.user.id;
				payRes = await vipPay(params);
			} else {
				infoBox.showToast('余额不足');
				return;
			}
		}
	} catch (error) {
		console.log(error);
		let res;
		let timer;
		if (error.code == 211 && error.msg == '等待用户付款') {
			uni.showLoading({
				title: '支付中...'
			});
			timer = setInterval(async () => {
				res = await queryOrderStatus({
					orderId: pars.orderId
				});
				if (res == 'done') {
					clearInterval(timer);
					uni.hideLoading();
					paySuccess();
				}
				console.log(res);
			}, 1000);
		}
		if (error.code == 701) {
			uni.removeStorageSync('table_code');
			uni.navigateBack();
		}
		payStatus = '';
		return false;
	}
	paySuccess();
}

/**
 * 支付成功回调
 */
function paySuccess() {
	infoBox.showToast('支付成功');
	payStatus = 'success';
	setTimeout(() => {
		// uni.$emit('orderDetail:update')
		uni.$emit('get:table');
		uni.$emit('update:orderDetail');
		uni.navigateBack({
			delta: 1
		});
		websocketUtil.send(
			JSON.stringify({
				type: 'onboc',
				account: uni.getStorageSync('iToken').loginId,
				shop_id: uni.getStorageSync('shopInfo').id || '',
				operate_type: 'cleanup',
				table_code: order.tableCode
			})
		);
	}, 1500);
}

/**
 * 弹窗关闭
 */
function confirmModelCancel() {
	if (modal.key == 'fullCoupon') {
		// 取消改价
		discount.discount = 100;
		discount.value = 0;
	}
	modal.show = false;
	modal.key = '';
	modal.data = '';
}

/**
 * 弹窗确认
 */
async function confirmModelConfirm() {
	if (modal.key == 'cash') {
		await pay();
		confirmModelCancel();
		return;
	}
	if (modal.key == 'fullCoupon') {
		//删除满减券
		const index = pays.quan.findIndex((v) => v.type == 1);
		pays.quan.splice(index, 1);
		return;
	}
}

function objToArrary(obj) {
	if (Object.values(obj) && Array.isArray(Object.values(obj)[0])) {
		// 是数组
		let arr = [];
		Object.values(obj).forEach((item) => {
			item.map((v) => {
				v.salePrice = v.salePrice ? v.salePrice : v.price;
				v.number = v.num;
				v.packFee = v.packAmount || 0;
				return v;
			});
			arr = [...arr, ...item];
		});
		return arr;
	} else {
		// 不是数组
		return Object.keys(obj).map((key) => {
			return obj[key];
		});
	}
}
/**
 * 扫码/储值卡支付
 */
function saomaPay() {
	const item = pays.payTypes.list[pays.payTypes.selIndex];
	uni.scanCode({
		onlyFromCamera: true,
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);

			pay({
				authCode: res.result
			});
		}
	});
}

/**
 * 现金支付唤起
 */
function cashConfirmShow() {
	modal.content = '是否确认已现金收款' + payPrice.value;
	modal.key = 'cash';
	modal.show = true;
}

/**
 * 获取历史订单并更新商品列表
 */
async function getHistoryAndUpdateGoodsList() {
	// 获取订单详情
	const orderRes = await getHistoryOrder({
		orderId: order.orderId
	});
	if (orderRes.status == 'cancelled') {
		uni.showToast({
			title: '订单已取消',
			icon: 'none'
		});
		toDiancai();
		return;
	}
	if (orderRes.status == 'done') {
		uni.showToast({
			title: '订单已完成',
			icon: 'none'
		});
		toDiancai();
		return;
	}
	Object.assign(order, orderRes);
	pageData.goodsList = objToArrary(orderRes.detailMap);
	pageData.seatNum = order.seatNum;
}
/**
 * socket消息监听
 */
function onMessage() {
	websocketUtil.offMessage();
	websocketUtil.onMessage((res) => {
		let msg = JSON.parse(res);
		console.log('onMessage', msg);
		switch (msg.operate_type) {
			case 'pad_init':
				getHistoryAndUpdateGoodsList();
				break;
			case 'pad_add':
			case 'add':
				break;
			case 'pad_edit':
			case 'edit':
				break;
			case 'bulk_edit':
				getHistoryAndUpdateGoodsList();
				break;
			case 'pad_del':
			case 'del':
				break;
			case 'pad_cleanup':
			case 'cleanup':
				break;
			case 'product_update':
				break;
			case 'pad_batch':
				break;
		}
	});
}
</script>

<style lang="scss" scoped>
$quan-color: #318afe;
.cash-input {
	height: 80upx;
	background-color: #efefef;
	border-radius: 8upx;
	margin-bottom: 20upx;
	padding-left: 20upx;
}
.op3 {
	opacity: 0.3;
}

.hui {
	// background-color: $quan-color;
	background-image: linear-gradient(to right bottom, rgb(254, 103, 4), rgb(241, 50, 42));
	padding: 4rpx 10rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	color: #fff;
}

.box-shadow {
	box-shadow: 0 0 5px #e5e5e5;
}

.pay-success {
	color: #5cbb6f;
}

.icon {
	width: 40rpx;
	height: 40rpx;
}

.border-bottom-dashed {
	border-bottom: 1px dashed #bbb;
}

.border-bottom {
	border-color: rgb(240, 240, 240);
}

.list {
	.item {
		&.disabled {
			color: #999;
		}
	}

	.item:last-child {
		.border-bottom {
			border-bottom: none;
		}
	}
}

.old-price {
	text-decoration: line-through;
}

.price-fuhao {
	font-size: 24px;
}

.price {
	font-size: 32px;
}

$dotSize: 20rpx;
$position: calc($dotSize / (-2));

.card {
	position: relative;

	&::after,
	&:before {
		content: '';
		display: block;
		position: absolute;
		background-color: #f9f9f9;
		width: $dotSize;
		height: $dotSize;
		border-radius: 50%;
	}

	&.top {
		&::after {
			right: $position;
			bottom: $position;
		}

		&:before {
			left: $position;
			bottom: $position;
		}
	}

	&.bottom {
		&::after {
			right: $position;
			top: $position;
		}

		&:before {
			left: $position;
			top: $position;
		}
	}
}
</style>
