<template>
	<view class="page-container flex-column">

		<NavBar :title="navTitle" bgColor="#F5F5F5" isRightButton @right-click="onConfirm"></NavBar>

		<view class="tab-box" v-if="!isEditMode">
			<view class="tab" :class="{ active: item.key == activeTab }" v-for="item in shoppingType" :key="item.key"
				@click="switchTab(item)">
				<text>{{ item.label }}</text>
			</view>
		</view>

		<view v-if="!isEditMode" class="random-dice">
			<image style="width: 2rem;height: 2rem;" src="/static/image/common/random-dice.png"
				@click="clickRandomDate"></image>
		</view>


		<view class="hightlight-box">
			<view class="title-box flex-column flex-center">
				<view v-if="order.orderType == 'wait_pay'" class="flex-column flex-center">
					<view class="title flex-align-center">待付款 <auto-width-input style="margin-left: 16rpx;"
							v-model="order.statusDesc" show-edit fontSize="36rpx" fontWeight="500" />
					</view>
					<view class="sub-title flex-align-center">
						<text>请在</text>
						<picker mode="multiSelector" :range="timeRange" :value="waitPayTimeValue"
							@change="handleWaitPayTimeChange">
							<view class="flex-align-center" style="margin: 0 10rpx;">
								<text>{{ order.waitPayTime }}</text>
								<image style="width: 24rpx;height: 24rpx;margin-left: 6rpx;"
									src="/static/image/common/edit.png"></image>
							</view>
						</picker>
						<text>内支付，逾期订单将自动取消</text>
					</view>
				</view>
				<view v-if="order.orderType == 'wait_recv'" class="flex-column flex-center">
					<view class="title flex-align-center" style="color: #20A61E;">
						<image style="width: 44rpx;height: 44rpx;margin-right: 12rpx;"
							src="/static/image/shopping/pdd/paijianzhong.png"></image>
						<auto-width-input color="#20A61E" fontSize="36rpx" fontWeight="500"
							v-model="order.deliveryStatus" show-edit />
					</view>
					<view class="sub-title flex-align-center" style="color: #20A61E;margin-top: 8rpx;">
						<auto-width-input color="#20A61E" v-model="order.statusDesc" show-edit />
					</view>
				</view>
				<view v-if="order.orderType == 'received'" class="flex-column flex-center">
					<view class="title flex-align-center" style="color: #20A61E;">
						<image style="width: 44rpx;height: 44rpx;margin-right: 12rpx;"
							src="/static/image/shopping/pdd/yiqianshou.png"></image>
						已签收
					</view>
					<view class="sub-title flex-align-center" style="color: #20A61E;margin-top: 8rpx;">
						<auto-width-input color="#20A61E" v-model="order.statusDesc" show-edit />
					</view>
				</view>
			</view>
		</view>
		<!-- 头部信息卡片：优惠券 + 物流 + 地址 -->
		<view class="header-info-card">
			<!-- 优惠券横幅 -->
			<view v-if="order.orderType !== 'wait_pay' && order.couponInfo"
				class="coupon-banner flex-align-center flex-justify-between">
				<view class="flex-align-center">
					<view class="coupon-icon flex-center">￥</view>
					<text class="black-text">{{ order.couponInfo.title }}</text>
					<text class="red-text">{{ order.couponInfo.priceText }}</text>
					<text class="black-text">{{ order.couponInfo.timeText }}</text>
				</view>
				<uni-icons type="right" size="14" color="#D3D3D3"></uni-icons>
			</view>

			<!-- 物流信息 -->
			<view v-if="order.orderType !== 'wait_pay' && order.logistics"
				class="logistics-box flex-align-center flex-justify-between">
				<view class="icon-wrap flex-center">
					<image class="icon" src="/static/image/shopping/pdd/yunshuzhong.png" mode="widthFix"></image>
				</view>
				<view class="info flex-1 flex-column">
					<auto-width-input class="title text-ellipsis-1" v-model="order.logistics.desc" type="textarea"
						show-edit />
					<view class="flex-align-center" @click="openTimePicker('logistics')">
						<text class="time">{{ order.logistics.time }}</text>
						<image style="width: 24rpx;height: 24rpx;margin-left: 6rpx;"
							src="/static/image/common/edit.png"></image>
					</view>
				</view>
				<uni-icons type="right" size="14" color="#D3D3D3"></uni-icons>
			</view>

			<view v-if="order.orderType !== 'wait_pay'" class="divider-line"></view>

			<!-- 地址信息 -->
			<view class="adress-box flex-align-center flex-justify-between">
				<view class="icon-wrap flex-center">
					<image class="icon" src="/static/image/shopping/pdd/location.png" mode="widthFix"></image>
				</view>
				<view class="user-info flex-1 flex-column">
					<view class="name-phone flex-align-center">
						<auto-width-input class="name" v-model="order.address.name" show-edit />
						<auto-width-input class="phone" v-model="order.address.phone" show-edit />
						<image src="/static/image/shopping/pdd/eye-close.png" class="eye-icon" mode="aspectFit"></image>
					</view>
					<view class="detail text-ellipsis-2">
						<view class="flex-align-center flex-1"><auto-width-input v-model="order.address.province"
								show-edit type="textarea" />
							<!-- <auto-width-input v-model="order.address.detail" show-edit /> -->
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="upload-shop-logo-box flex-justify-between flex-align-center">
			<text>上传拼单头像</text>
			<view class="flex-align-center" style="margin-left: auto;">
				<view class="avatars-preview flex-align-center" style="margin-right: 16rpx;"
					v-if="order.avatars && order.avatars.length > 0">
					<image v-for="(av, idx) in order.avatars" :key="idx" :src="av" mode="aspectFill"
						style="width: 52rpx; height: 52rpx; border-radius: 50%; border: 2rpx solid #fff;"
						:style="{ marginLeft: idx > 0 ? '-16rpx' : '0' }" @click="deleteAvatar(idx)"></image>
				</view>
				<view class="add-avatar-btn flex-center" @click="chooseAvatar"
					v-if="!order.avatars || order.avatars.length < 4"
					style="width: 52rpx; height: 52rpx; border-radius: 50%; border: 1px dashed #ccc; background-color: #f8f8f8;">
					<text style="color: #999; font-size: 36rpx; line-height: 52rpx; margin-top: -6rpx;">+</text>
				</view>
			</view>
		</view>

		<view class="upload-shop-logo-box  flex-align-center">
			<text>店铺标签显示</text>
			<view class="flex-align-center" style="margin-left: auto;">
				<text style="font-size: 22rpx; color: #999;">品牌认证</text>
				<switch :checked="order.shop.hasBrandAuth" @change="(e) => order.shop.hasBrandAuth = e.detail.value"
					color="#E02E24" style="transform: scale(0.6); margin: 0 -10rpx;" />
				<text style="font-size: 22rpx; color: #999;">旗舰店 </text>
				<switch :checked="order.shop.hasFlagship" @change="(e) => order.shop.hasFlagship = e.detail.value"
					color="#E02E24" style="transform: scale(0.6); margin-left: -10rpx; margin-right: -20rpx;" />
				<text style="font-size: 22rpx; color: #999;">618 </text>
				<switch :checked="order.shop.has618" @change="(e) => order.shop.has618 = e.detail.value" color="#E02E24"
					style="transform: scale(0.6); margin-left: -10rpx; margin-right: -20rpx;" />
			</view>
		</view>


		<view class="product-card">
			<!-- 店铺信息 -->
			<view class="shop-header flex-align-center">
				<view class="shop-logo flex-center" @click="chooseImage('shopLogo')">
					<text style="color: #555555;font-size: 32rpx;" v-if="!order.shop.logo">+</text>
					<image v-else class="w100 h100" :src="order.shop.logo" mode="widthFix"></image>
				</view>
				<auto-width-input class="shop-name" v-model="order.shop.name" show-edit />
				<image v-if="order.shop.hasBrandAuth" class="brand-auth-tag"
					src="/static/image/shopping/pdd/pinpairenzheng.png" mode="heightFix">
				</image>
				<image v-if="order.shop.hasFlagship" class="flagship-tag"
					src="/static/image/shopping/pdd/qijiandian.png" mode="heightFix"></image>
				<image v-if="order.shop.has618" style="margin-left: 8rpx;height: 28rpx;" class="flagship-tag"
					src="/static/image/shopping/pdd/618.png" mode="heightFix"></image>
			</view>

			<!-- 商品主要内容 -->
			<view class="product-content flex" v-for="(product, idx) in order.products" :key="idx"
				:style="{ marginTop: idx > 0 ? '30rpx' : '0' }">
				<view class="img-box">
					<image class="product-img" :src="product.img || product.image" mode="aspectFill"
						@click="chooseImage('product', idx)"></image>
				</view>
				<view class="info-box flex-1">
					<view class="title-price flex">
						<view class="title flex-1">
							<!-- <auto-width-input type="textarea" v-model="product.title" show-edit /> -->
							<auto-width-input class="flex-1" v-model="product.title" fontSize="28rpx" color="#1A1A1A"
								type="textarea" show-edit />
						</view>
						<view class="price-box flex-column align-end">
							<text class="price">¥<auto-width-input v-model="product.price" type="digit"
									show-edit /></text>
							<text class="count">x<auto-width-input v-model="product.count" type="number"
									show-edit /></text>
						</view>
					</view>
					<view class="spec">
						<auto-width-input type="textarea" v-model="product.spec" show-edit />
					</view>
					<view class="tags flex-align-center" style="flex-wrap: wrap; gap: 8rpx 0;">
						<view class="green-tag" v-for="(tag, tagIdx) in product.serviceTags" :key="tagIdx">
							<auto-width-input v-model="product.serviceTags[tagIdx]" show-edit color="#1a1a1a" />
							<view @click="product.serviceTags.splice(tagIdx, 1)"
								style="margin-left: 4rpx; display: flex; align-items: center; padding: 4rpx;">
								<uni-icons type="closeempty" size="12" color="#1a1a1a"></uni-icons>
							</view>
						</view>
						<view class="green-tag flex-center" style="padding: 4rpx 12rpx; opacity: 0.8;"
							@click="product.serviceTags.push('新标签')">
							<text style="color: #1a1a1a; font-size: 26rpx; line-height: 26rpx;">+</text>
						</view>
					</view>
				</view>
			</view>

			<view class="divider"></view>

			<!-- 底部支付金额 -->
			<view class="payment-box flex-align-center">
				<view style="flex: 1;"></view>
				<text class="label">{{ order.orderType === 'wait_pay' ? '应付: ' : '实付: ' }} </text>
				<text class="symbol">¥</text>
				<auto-width-input class="amount" v-model="order.payment.totalAmount" type="digit" color="#DF2E26"
					show-edit />

				<auto-width-input class="freight" v-model="order.payment.freightDesc" show-edit />
			</view>
		</view>
		<!-- 订单信息 -->
		<view class="order-info">
			<view class="info-card flex-column">
				<view class="info-line flex-align-center flex-justify-between"
					v-for="(item, index) in (isOrderInfoExpanded || order.orderType === 'wait_pay' ? orderInfoList : orderInfoList.slice(0, 2))"
					:key="index">
					<view class="left flex-align-center">
						<text class="label">{{ item.label }}</text>
						<view class="flex-align-center" v-if="item.label.includes('时间')"
							@click="openTimePicker('orderInfo', index, item.value)">
							<text class="value" style="font-size: 28rpx; color: #1A1A1A;">{{ item.value || '请选择时间'
							}}</text>
							<image style="width: 28rpx;height: 28rpx;margin-left: 6rpx;"
								src="/static/image/common/edit.png"></image>
						</view>
						<auto-width-input v-else class="value" v-model="item.value" show-edit />
						<view class="avatars flex-align-center" v-if="item.hasAvatars && order.avatars">
							<image class="avatar" v-for="(avatar, aIdx) in order.avatars" :key="aIdx" :src="avatar"
								mode="aspectFill" :style="{ zIndex: 2 - aIdx, marginLeft: aIdx > 0 ? '-12rpx' : '0' }">
							</image>
						</view>
						<text class="arrow" v-if="item.hasArrow">></text>
					</view>
				</view>

				<view class="expand-btn flex-align-center" v-if="!isOrderInfoExpanded && order.orderType !== 'wait_pay'"
					@click="isOrderInfoExpanded = true">
					<text class="label">查看更多订单信息</text>
					<view class="icon-box">
						<uni-icons type="bottom" size="12" color="#999999"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 支付方式列表 -->
		<view v-if="order.orderType == 'wait_pay'" class="pay-list">
			<view class="pay-item flex-align-center" v-for="(item, index) in payList" :key="index"
				@click="order.activePayIndex = index">
				<image :src="item.icon" class="pay-icon" mode="aspectFit"></image>
				<view class="pay-info flex-1 flex-align-center">
					<text class="pay-name">{{ item.name }}</text>
					<text class="pay-subname" v-if="item.subName">{{ item.subName }}</text>
				</view>
				<image v-if="order.activePayIndex === index" style="width: 32rpx;height: 32rpx;"
					src="/static/image/shopping/pdd/pay/select.png"></image>
			</view>
		</view>
		<!-- 底部固定支付栏 -->
		<view v-if="order.orderType == 'wait_pay'" class="fixed-bottom-bar flex-justify-between">
			<!-- 样式 2：先用后付 (order.activePayIndex === 2) -->
			<view class="left-info style-2 flex-column" v-if="order.activePayIndex === 2">
				<view class="line-top flex-align-end">
					<text class="label">实付款: </text>
					<text class="symbol">￥</text>
					<text class="amount">0</text>
				</view>
				<view class="line-bottom">
					<text>确认收货后付款 ￥{{ order.payment.totalAmount }}</text>
				</view>
			</view>
			<!-- 样式 1：其它支付方式 -->
			<view class="left-info style-1 flex-align-center" v-else>
				<view class="flex-align-end">
					<text class="label">应付: </text>
					<text class="symbol">￥</text>
					<auto-width-input class="amount" v-model="order.payment.totalAmount" type="digit" show-edit />

					<text class="discount"><auto-width-input class="discount" color="#E02E24" fontSize="26rpx" show-edit
							v-model="order.payment.discountText" type="text" /></text>
				</view>
			</view>

			<view class="pay-btn flex-center">
				<text>去支付</text>
			</view>
		</view>
	</view>

	<uni-popup ref="timepopup" type="bottom" :z-index="9999" style="z-index: 9999;">
		<view class="timeBox">
			<view class="titleBox">
				<view class="title" @click="closeTimePicker">取消</view>
				<view class="btn" @click="settmes">确定</view>
			</view>
			<DateTimePicker :defaultDate="datePickerData.selectDate" :minDate="datePickerData.startDate"
				:maxDate="datePickerData.endDate" :mode="4" @onChange="onChangeStartDate" />
		</view>
	</uni-popup>
</template>


<script setup>
import { ref, computed, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import NavBar from "@/components/nav-bar/nav-bar.vue";
import AutoWidthInput from "@/components/common/auto-width-input.vue";
import DateTimePicker from '@/components/dengrq-datetime-picker/dateTimePicker/index.vue';
import { shoppingType, shoppingClassfiy, shoppingProductList } from "../json/order.json";
import { stringUtil, util } from '@/utils/common.js';

const activeTab = ref("wait_pay");
const isEditMode = ref(false);
const currentId = ref('');
const navTitle = computed(() => isEditMode.value ? "修改订单" : "新增订单");

const isOrderInfoExpanded = ref(true);

const order = ref(JSON.parse(JSON.stringify(shoppingClassfiy[activeTab.value])));

// 自动计算商品总价 (监听单价和数量变化)
watch(() => order.value.products, (newProducts) => {
	if (!newProducts || !order.value.payment) return;
	let total = 0;
	newProducts.forEach(product => {
		const price = Number(product.price) || 0;
		const count = Number(product.count) || 0;
		total += price * count;
	});
	order.value.payment.totalAmount = total.toFixed(2);
}, { deep: true });

const switchTab = (item) => {
	// 备份当前数据，防止切 tab 导致用户填写的关键数据丢失
	const oldData = JSON.parse(JSON.stringify(order.value));

	activeTab.value = item.key;
	order.value = JSON.parse(JSON.stringify(shoppingClassfiy[activeTab.value]));

	// 将用户的核心更改覆盖回全新的状态模板中
	if (oldData) {
		order.value.shop = oldData.shop;
		order.value.avatars = oldData.avatars;
		order.value.products = oldData.products;
		order.value.address = oldData.address;
		order.value.payment = oldData.payment;
		order.value.waitPayTime = oldData.waitPayTime;
		if (oldData.logistics && oldData.logistics.desc) {
			order.value.logistics = oldData.logistics;
		}
		if (oldData.orderInfo && oldData.orderInfo.length > 0) {
			order.value.orderInfo.forEach(newItem => {
				const oldItem = oldData.orderInfo.find(o => o.label === newItem.label);
				if (oldItem && oldItem.value) {
					newItem.value = oldItem.value;
				}
			});
		}
		if (oldData.activePayIndex !== undefined) {
			order.value.activePayIndex = oldData.activePayIndex;
		}
		if (oldData.avatars) {
			order.value.avatars = oldData.avatars;
			syncAvatarsToOrderInfo();
		}
	}
};

onLoad((options) => {
	const editFlag = String(options.isEdit) === 'true' || options.isEdit === true;
	if (editFlag && options.id) {
		isEditMode.value = true;
		currentId.value = String(options.id);
		const list = uni.getStorageSync('pddOrderList') || [];
		const editData = list.find(item => String(item.id) === String(options.id));
		if (editData) {
			order.value = JSON.parse(JSON.stringify(editData));
			activeTab.value = editData.orderType;
		}
	} else {
		// Init for add mode
		clickRandomDate();
	}
});

const clickRandomDate = () => {
	if (!shoppingProductList || shoppingProductList.length === 0) return;
	const randomIndex = Math.floor(Math.random() * shoppingProductList.length);
	const selected = JSON.parse(JSON.stringify(shoppingProductList[randomIndex]));
	if (order.value && selected.products && selected.products.length > 0) {
		order.value.products[0] = {
			...order.value.products[0],
			...selected.products[0]
		};
		order.value.products[0].img = selected.products[0].img || selected.products[0].image || '/static/image/shopping/pdd/logo.png';
		order.value.shop.name = selected.shop.name;
		order.value.payment.totalAmount = selected.payment.totalAmount;

		// 随机生成 waitPayTime (hh:mm:ss，不能大于24小时)
		const h = Math.floor(Math.random() * 24).toString().padStart(2, '0');
		const m = Math.floor(Math.random() * 60).toString().padStart(2, '0');
		const s = Math.floor(Math.random() * 60).toString().padStart(2, '0');
		order.value.waitPayTime = `${h}:${m}:${s}`;

		// 随机生成 logistics.time ("今天/昨天/前天 hh:mm:ss")
		if (order.value.logistics) {
			const prefixes = ['今天', '昨天', '前天'];
			const randomPrefix = prefixes[Math.floor(Math.random() * prefixes.length)];
			const lh = Math.floor(Math.random() * 24).toString().padStart(2, '0');
			const lm = Math.floor(Math.random() * 60).toString().padStart(2, '0');
			const ls = Math.floor(Math.random() * 60).toString().padStart(2, '0');
			order.value.logistics.time = `${randomPrefix} ${lh}:${lm}:${ls}`;
		}

		// 随机生成订单编号、快递单号和各环节时间
		if (order.value.orderInfo && order.value.orderInfo.length > 0) {
			const randomOrderNo = `26${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}-${Math.floor(Math.random() * 1e14).toString().padStart(14, '0')}`;
			const randomExpressNo = `77${Math.floor(Math.random() * 1e14).toString().padStart(14, '0')}`;

			const fmt = (d) => {
				const Y = d.getFullYear();
				const M = (d.getMonth() + 1).toString().padStart(2, '0');
				const D = d.getDate().toString().padStart(2, '0');
				const h = d.getHours().toString().padStart(2, '0');
				const m = d.getMinutes().toString().padStart(2, '0');
				const s = d.getSeconds().toString().padStart(2, '0');
				return `${Y}-${M}-${D} ${h}:${m}:${s}`;
			};

			const now = new Date();
			const orderTimeStr = fmt(now);

			const spellDate = new Date(now.getTime());
			spellDate.setSeconds(spellDate.getSeconds() + Math.floor(Math.random() * 50) + 10);
			const spellTimeStr = fmt(spellDate);

			const deliverDate = new Date(spellDate.getTime());
			deliverDate.setHours(deliverDate.getHours() + Math.floor(Math.random() * 24) + 1);
			const deliverTimeStr = fmt(deliverDate);

			order.value.orderInfo.forEach(item => {
				if (item.label.includes('订单编号')) {
					item.value = randomOrderNo;
				} else if (item.label.includes('快递单号')) {
					item.value = randomExpressNo;
				} else if (item.label.includes('下单时间')) {
					item.value = orderTimeStr;
				} else if (item.label.includes('拼单时间')) {
					item.value = spellTimeStr;
				} else if (item.label.includes('发货时间')) {
					item.value = deliverTimeStr;
				}
			});
		}
	}
};

const removeLocalFile = (filePath) => {
	if (!filePath) return;
	if (filePath.startsWith('http') || filePath.startsWith('/static')) return;
	uni.removeSavedFile({
		filePath,
		fail: () => { }
	});
};

const syncAvatarsToOrderInfo = () => {
	if (order.value.orderInfo) {
		const target = order.value.orderInfo.find(item => item.hasAvatars);
		if (target) {
			target.avatars = order.value.avatars;
		}
	}
};

const deleteAvatar = (idx) => {
	if (!order.value.avatars) return;

	uni.showActionSheet({
		itemList: ['替换', '删除'],
		success: (res) => {
			if (res.tapIndex === 0) {
				uni.chooseImage({
					count: 1,
					success: (imgRes) => {
						const tempFilePath = imgRes.tempFilePaths[0];
						uni.saveFile({
							tempFilePath,
							success: (saveRes) => {
								const oldPath = order.value.avatars[idx];
								if (oldPath) removeLocalFile(oldPath);
								order.value.avatars.splice(idx, 1, saveRes.savedFilePath);
								syncAvatarsToOrderInfo();
							},
							fail: () => {
								order.value.avatars.splice(idx, 1, tempFilePath);
								syncAvatarsToOrderInfo();
							}
						});
					}
				});
			} else if (res.tapIndex === 1) {
				const oldPath = order.value.avatars[idx];
				if (oldPath) removeLocalFile(oldPath);
				order.value.avatars.splice(idx, 1);
				syncAvatarsToOrderInfo();
			}
		}
	});
};

const chooseAvatar = () => {
	const currentCount = order.value.avatars ? order.value.avatars.length : 0;
	if (currentCount >= 4) return;

	uni.chooseImage({
		count: 4 - currentCount,
		success: (res) => {
			if (!order.value.avatars) {
				order.value.avatars = [];
			}
			res.tempFilePaths.forEach(path => {
				uni.saveFile({
					tempFilePath: path,
					success: (saveRes) => {
						if (order.value.avatars.length < 4) {
							order.value.avatars.push(saveRes.savedFilePath);
						}
						syncAvatarsToOrderInfo();
					},
					fail: () => {
						if (order.value.avatars.length < 4) {
							order.value.avatars.push(path);
						}
						syncAvatarsToOrderInfo();
					}
				});
			});
		}
	});
};

const chooseImage = (type, idx = 0) => {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			const tempFilePath = res.tempFilePaths[0];
			uni.saveFile({
				tempFilePath: tempFilePath,
				success: (saveRes) => {
					if (type === 'shopLogo') {
						if (order.value.shop.logo) removeLocalFile(order.value.shop.logo);
						order.value.shop.logo = saveRes.savedFilePath;
					} else if (type === 'product') {
						if (order.value.products[idx].img) removeLocalFile(order.value.products[idx].img);
						order.value.products[idx].img = saveRes.savedFilePath;
					}
				},
				fail: () => {
					if (type === 'shopLogo') {
						order.value.shop.logo = tempFilePath;
					} else if (type === 'product') {
						order.value.products[idx].img = tempFilePath;
					}
				}
			});
		}
	});
};

const onConfirm = () => {
	if (order.value.payment && order.value.payment.totalAmount !== undefined) {
		const amount = Number(order.value.payment.totalAmount);
		if (!isNaN(amount)) {
			order.value.payment.totalAmount = parseFloat(amount.toFixed(2));
		}
	}

	let list = uni.getStorageSync('pddOrderList') || [];
	if (isEditMode.value) {
		const idx = list.findIndex(item => String(item.id) === currentId.value);
		if (idx > -1) {
			list[idx] = { ...list[idx], ...order.value };
		}
	} else {
		const newOrder = {
			...order.value,
			id: Date.now().toString()
		};
		list.unshift(newOrder);
	}
	uni.setStorageSync('pddOrderList', list);
	uni.showToast({ title: '保存成功', icon: 'success' });
	console.log(order.value);
	setTimeout(() => {
		uni.navigateBack();
	}, 1000);
};

const orderInfoList = computed(() => {
	return order.value.orderInfo || [];
});

const payList = ref([
	{ name: '多多支付', icon: '/static/image/shopping/pdd/pay/duoduo.png' },
	{ name: '微信支付', icon: '/static/image/shopping/pdd/pay/wechat.png' },
	{ name: '先用后付', subName: ' (0元下单，确认收货后付款)', icon: '/static/image/shopping/pdd/pay/xianyonghoufu.png' },
	{ name: '支付宝', icon: '/static/image/shopping/pdd/pay/alipay.png' },
	{ name: '找微信好友支付', icon: '/static/image/shopping/pdd/pay/zhaohaoyou.png' },
	{ name: 'Apple Pay', icon: '/static/image/shopping/pdd/pay/apple.png' },
	{ name: 'QQ钱包', icon: '/static/image/shopping/pdd/pay/qq.png' },
	{ name: '云闪付', icon: '/static/image/shopping/pdd/pay/yunshanfu-red.png' },
	{ name: '云闪付', icon: '/static/image/shopping/pdd/pay/yunshanfu-blue.png' }
]);

// 时间选择器数据 (hh:mm:ss, 不能大于24小时)
const timeRange = ref([
	Array.from({ length: 24 }, (_, i) => (i < 10 ? '0' + i : i + '')), // 时 00-23
	Array.from({ length: 60 }, (_, i) => (i < 10 ? '0' + i : i + '')),  // 分 00-59
	Array.from({ length: 60 }, (_, i) => (i < 10 ? '0' + i : i + ''))   // 秒 00-59
]);

const waitPayTimeValue = computed(() => {
	if (!order.value || !order.value.waitPayTime) return [0, 0, 0];
	const parts = order.value.waitPayTime.split(':');
	if (parts.length !== 3) return [0, 0, 0];
	return [
		parseInt(parts[0]) || 0,
		parseInt(parts[1]) || 0,
		parseInt(parts[2]) || 0
	];
});

const handleWaitPayTimeChange = (e) => {
	const val = e.detail.value;
	const h = timeRange.value[0][val[0]];
	const m = timeRange.value[1][val[1]];
	const s = timeRange.value[2][val[2]];
	order.value.waitPayTime = `${h}:${m}:${s}`;
};

const logisticsPickerValue = computed(() => {
	if (!order.value || !order.value.logistics || !order.value.logistics.time) return '';
	const relativeStr = order.value.logistics.time;
	const parts = relativeStr.split(' ');
	if (parts.length < 2) return '';

	const prefix = parts[0];
	const timePart = parts[1];

	const now = new Date();
	let targetDate = new Date(now);

	if (prefix === '今天') {
		// 维持今天
	} else if (prefix === '昨天') {
		targetDate.setDate(targetDate.getDate() - 1);
	} else if (prefix === '前天') {
		targetDate.setDate(targetDate.getDate() - 2);
	} else if (prefix.includes('-')) {
		const dp = prefix.split('-');
		if (dp.length === 2) {
			targetDate.setMonth(parseInt(dp[0]) - 1);
			targetDate.setDate(parseInt(dp[1]));
		}
	}

	const Y = targetDate.getFullYear();
	const M = (targetDate.getMonth() + 1).toString().padStart(2, '0');
	const D = targetDate.getDate().toString().padStart(2, '0');
	return `${Y}-${M}-${D} ${timePart}`;
});

const timepopup = ref();
const datePickerData = ref({
	selectDate: "",
	startDate: "",
	endDate: "",
});

// 记录当前弹窗编辑的目标类型与索引
const activeTimePicker = ref({ type: '', index: -1 });

const openTimePicker = (type, index = -1, currentValue = '') => {
	activeTimePicker.value = { type, index };

	let initVal = currentValue;
	if (type === 'logistics' && logisticsPickerValue.value) {
		initVal = logisticsPickerValue.value;
	} else if (!initVal) {
		initVal = util.formatTime(new Date());
	}

	datePickerData.value.selectDate = initVal;
	datePickerData.value.endDate = "2099-12-31 23:59:59";
	timepopup.value.open();
};

const closeTimePicker = () => {
	timepopup.value.close();
};

const onChangeStartDate = (e) => {
	datePickerData.value.selectDate = e;
};

const settmes = () => {
	const val = datePickerData.value.selectDate;
	if (!val) {
		timepopup.value.close();
		return;
	}

	if (activeTimePicker.value.type === 'logistics') {
		// val 格式为 "YYYY-MM-DD HH:mm:ss"
		const selectedDate = new Date(val.replace(/-/g, '/'));
		const now = new Date();

		const selectedDay = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate());
		const todayDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());

		const diffTime = todayDay - selectedDay;
		const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

		const h = selectedDate.getHours().toString().padStart(2, '0');
		const m = selectedDate.getMinutes().toString().padStart(2, '0');
		const s = selectedDate.getSeconds().toString().padStart(2, '0');
		const timePart = `${h}:${m}:${s}`;

		if (diffDays === 0) {
			order.value.logistics.time = `今天 ${timePart}`;
		} else if (diffDays === 1) {
			order.value.logistics.time = `昨天 ${timePart}`;
		} else if (diffDays === 2) {
			order.value.logistics.time = `前天 ${timePart}`;
		} else {
			const MM = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
			const DD = selectedDate.getDate().toString().padStart(2, '0');
			order.value.logistics.time = `${MM}-${DD} ${timePart}`;
		}
	} else if (activeTimePicker.value.type === 'orderInfo' && activeTimePicker.value.index !== -1) {
		// 订单信息中的各种时间（发货、拼单等），直接回填 YYYY-MM-DD HH:mm:ss 格式
		order.value.orderInfo[activeTimePicker.value.index].value = val;
	}

	timepopup.value.close();
};
</script>


<style lang="less" scoped>
.tab-box {
	display: flex;
	background-color: #ffffff;
	padding: 20rpx 24rpx 0;
	border-bottom: 1rpx solid #F2F3F7;

	.tab {
		flex: 1;
		text-align: center;
		padding-bottom: 20rpx;
		font-size: 28rpx;
		color: #1A1A1A;
		border-bottom: 4rpx solid transparent;

		&.active {
			color: #DD223F;
			border-bottom-color: #DD223F;
			font-weight: 500;
		}
	}
}

.random-dice {
	margin-top: 16rpx;
	display: flex;
	align-items: center;
	justify-content: flex-end;
}

.title {
	font-weight: 500;
	font-size: 36rpx;
	color: #1A1A1A;
	line-height: 36rpx;

}

.sub-title {
	font-weight: 400;
	font-size: 26rpx;
	color: #DF2E26;
	line-height: 26rpx;
	white-space: nowrap;
	margin-top: 14rpx;
}

.hightlight-box {
	border-bottom: 1rpx solid #F4F4F4;
	background-color: #ffffff;
	padding: 24rpx 24rpx;
	margin: 16rpx 0;
}

.header-info-card {
	background-color: #ffffff;
	margin-bottom: 18rpx;

	.icon-wrap {
		width: 60rpx;
		flex-shrink: 0;

		.icon {
			width: 40rpx;
		}
	}

	.coupon-banner {
		background-color: #FFF2E2;
		padding: 18rpx 24rpx;

		.coupon-icon {
			width: 30rpx;
			height: 30rpx;
			background-color: #DF2E26;
			color: #ffffff;
			font-size: 20rpx;
			border-radius: 4rpx;
			margin-right: 12rpx;
		}

		.black-text {
			font-size: 26rpx;
			color: #333333;
		}

		.red-text {
			font-size: 26rpx;
			color: #DF2E26;
		}
	}

	.logistics-box {
		padding: 24rpx;

		.info {
			margin-left: 10rpx;
			margin-right: 20rpx;
			width: 100px;

			.title {
				font-weight: 400;
				font-size: 30rpx;
				color: #535353;
				line-height: 30rpx;
			}

			.time {
				font-weight: 400;
				font-size: 26rpx;
				color: #999999;
				line-height: 26rpx;
				margin-top: 14rpx;
			}
		}
	}

	.divider-line {
		height: 1rpx;
		background-color: #F4F4F4;
		margin-left: 80rpx;
		margin-right: 24rpx;
	}

	.adress-box {
		padding: 24rpx;

		.user-info {
			margin-left: 10rpx;
			margin-right: 20rpx;

			.name-phone {
				font-size: 28rpx;
				color: #535353;
				line-height: 30rpx;

				.name {
					margin-right: 12rpx;
				}

				.phone {
					margin-right: 8rpx;
				}

				.eye-icon {
					width: 32rpx;
					height: 32rpx;
					margin: 0 10rpx;
				}

				.province {
					color: #999999;
				}
			}

			.detail {
				font-size: 28rpx;
				color: #535353;
				margin-top: 8rpx;
				line-height: 30rpx;
			}
		}

		.edit-btn {
			flex-shrink: 0;
			font-weight: 400;
			font-size: 30rpx;
			line-height: 30rpx;
			color: #DF2E26;
			border-radius: 8rpx;
			border: 1rpx solid #DF2E26;
			text-align: center;
			padding: 8rpx 20rpx;
		}
	}
}

.pay-list {
	background-color: #ffffff;
	margin-bottom: 16rpx;
	margin-top: 16rpx;

	.pay-item {
		height: 90rpx;
		margin-left: 24rpx;
		margin-right: 22rpx;
		border-bottom: 1rpx solid #F6F6F6;

		&:last-child {
			border-bottom: none;
		}

		.pay-icon {
			width: 44rpx;
			height: 44rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.pay-info {
			.pay-name {
				font-weight: 400;
				font-size: 30rpx;
				color: #1A1A1A;
				line-height: 30rpx;
			}

			.pay-subname {
				font-weight: 400;
				font-size: 28rpx;
				color: #535353;
				line-height: 30rpx;
			}
		}
	}
}

.product-card {
	background-color: #ffffff;
	padding: 16rpx 0 0;
	// margin-bottom: 20rpx;

	.shop-header {
		margin-bottom: 16rpx;
		padding: 0 24rpx;

		.shop-logo {
			width: 40rpx;
			height: 40rpx;
			border-radius: 4rpx;
			margin-right: 16rpx;
			background-color: #F4F4F4;
		}

		.shop-name {
			font-weight: 400;
			font-size: 28rpx;
			color: #1A1A1A;
			line-height: 24rpx;
			margin-right: 8rpx;
		}

		.brand-auth-tag {
			height: 28rpx;
			margin-right: 10rpx;
		}

		.flagship-tag {
			height: 28rpx;
		}
	}

	.product-content {
		margin-bottom: 16rpx;
		padding: 0 24rpx;

		.img-box {
			width: 164rpx;
			height: 164rpx;
			border-radius: 4rpx;
			background-color: #f5f5f5;
			margin-right: 32rpx;
			flex-shrink: 0;
			overflow: hidden;

			.product-img {
				width: 100%;
				height: 100%;
			}
		}

		.info-box {
			width: 0;

			.title-price {
				align-items: flex-start;

				.title {
					margin-right: 24rpx;
					font-size: 28rpx;
					color: #1A1A1A;
					font-weight: 400;
					line-height: 36rpx;
				}

				.price-box {
					flex-shrink: 0;

					.price {
						font-size: 26rpx;
						color: #999999;
						line-height: 36rpx;
					}

					.count {
						font-size: 24rpx;
						color: #999999;
						margin-top: 4rpx;
						text-align: right;
					}
				}
			}

			.spec {
				font-weight: 400;
				font-size: 26rpx;
				color: #999999;
				line-height: 34rpx;
				margin-bottom: 14rpx;
				margin-right: 110rpx;
			}

			.tags {
				.green-tag {
					color: #1a1a1a;
					border: 1px dashed #D2D2D2;
					font-size: 26rpx;
					line-height: 26rpx;
					padding: 4rpx 2rpx 4rpx 6rpx;
					border-radius: 4rpx;
					margin-right: 6rpx;
					display: inline-flex;
					align-items: center;
				}
			}
		}
	}

	.divider {
		height: 1rpx;
		background-color: #EFEFEF;
		width: 100%;
	}

	.payment-box {
		padding: 16rpx 24rpx;
		align-items: baseline;

		.label {
			font-weight: 400;
			font-size: 26rpx;
			color: #1A1A1A;
			line-height: 24rpx;
		}

		.symbol {
			font-size: 24rpx;
			color: #DF2E26;
			margin-left: 10rpx;
			font-weight: 500;
			margin-right: 4rpx;
		}

		.amount {
			font-size: 34rpx;
			color: #DF2E26;
			font-weight: 500;
		}

		.decimal {
			font-size: 26rpx;
			color: #DF2E26;
			font-weight: 500;
		}

		.freight {
			font-size: 26rpx;
			color: #1A1A1A;
			margin-left: 8rpx;
		}
	}
}

.text-ellipsis-2 {
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.align-end {
	align-items: flex-end;
}

.upload-shop-logo-box {
	background-color: #fff;
	padding: 24rpx 26rpx;
	margin-bottom: 18rpx;
}

.order-info {
	.info-card {
		background-color: #ffffff;
		padding: 22rpx 24rpx;
		margin-bottom: 16rpx;

		.info-line {
			margin-bottom: 8rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label,
			.value {
				font-weight: 400;
				font-size: 26rpx;
				color: #999999;
				line-height: 30rpx;
			}

			.value {
				margin-left: 10rpx;
			}

			.arrow {
				font-size: 20rpx;
				color: #BDBDBD;
				margin-left: 6rpx;
				font-family: monospace;
			}

			.avatars {
				margin-left: 14rpx;

				.avatar {
					width: 32rpx;
					height: 32rpx;
					border-radius: 50%;
					border: 2rpx solid #FFFFFF;
					background-color: #EFEFEF;
				}
			}
		}

		.expand-btn {
			margin-top: 8rpx;

			.label {
				font-weight: 400;
				font-size: 26rpx;
				color: #999999;
			}

			.icon-box {
				width: 24rpx;
				height: 24rpx;
				border-radius: 2rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 6rpx;
			}
		}
	}

	.cancel-card {
		background-color: #ffffff;
		height: 96rpx;

		text {
			font-size: 30rpx;
			color: #535353;
			line-height: 30rpx;
		}
	}
}

.page-container {
	padding-bottom: 200rpx;
}

.fixed-bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: #ffffff;
	border-top: 1rpx solid #F0F0F0;
	display: flex;
	z-index: 100;
	padding-bottom: env(safe-area-inset-bottom);
	padding-bottom: constant(safe-area-inset-bottom);

	.left-info {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		padding-right: 24rpx;
		height: 108rpx;

		&.style-1 {
			align-items: center;

			.label {
				font-size: 26rpx;
				color: #1A1A1A;
				font-weight: 400;
			}

			.symbol {
				font-size: 24rpx;
				color: #E02E24;
				margin-left: 6rpx;
				font-weight: 500;
			}

			.amount {
				font-size: 40rpx;
				color: #E02E24;
				font-weight: 500;
			}

			.decimal {
				font-size: 28rpx;
				color: #E02E24;
				font-weight: 500;
			}

			.discount {
				font-size: 26rpx;
				color: #E02E24;
			}
		}

		&.style-2 {
			flex-direction: column;
			justify-content: center;
			align-items: flex-end;

			.line-top {
				display: flex;
				align-items: baseline;

				.label {
					font-size: 26rpx;
					color: #1A1A1A;
					font-weight: 400;
				}

				.symbol {
					font-size: 24rpx;
					color: #E02E24;
					margin-left: 6rpx;
					font-weight: 500;
				}

				.amount {
					font-size: 40rpx;
					color: #E02E24;
					font-weight: 500;
				}
			}

			.line-bottom {
				font-size: 26rpx;
				color: #E02E24;
				font-weight: 500;
				line-height: 26rpx;
				margin-top: 4rpx;
			}
		}
	}

	.pay-btn {
		width: 250rpx;
		height: 108rpx;
		background-color: #E02E24;

		text {
			font-weight: 400;
			font-size: 34rpx;
			color: #FFFFFF;
		}
	}
}

.timeBox {
	background-color: #fff;
	padding: 10px;
	border-radius: 24rpx 24rpx 0 0;

	.titleBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 0 10px;

		.title {
			font-size: 28rpx;
			color: #999;
		}

		.btn {
			font-size: 28rpx;
			color: #1676FE;
			font-weight: 500;
		}
	}
}
</style>
<style>
@import '@/common/main.css';
</style>
