<template>
	<!-- 代跑腿/快递页 -->
	<view class="page1">
		<view class="title">
			<view class="title-sreach">
				<view class="back-btn" @tap="back" :style="{'top': menuButtonInfo.top +'px'}">
					<uni-icons type="left" size="28" color="#000"></uni-icons>
				</view>
				<view class="title-name" :style="{'top': menuButtonInfo.top +'px'}">
					<!-- 代取快递/跑腿 -->
				</view>
			</view>
		</view>
		<view style="position: absolute;top: 100rpx;width: 100%;">
			<view class="tab1" v-if="isKuaidi">
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/f1356c4db9b5488bb46140e2cdd2b4ee.png" alt=""
					style="position: absolute;" />
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/e380fd14442c476bb6d3f5ec471af515.png" alt="" />
				<view style="width: 100%;height: 160rpx;position: absolute;top:0;left: 0;display: flex;">
					<view style="width: 50%;height: 160rpx;"></view>
					<view style="width: 50%;height: 160rpx;" @tap="isKuaidi=!isKuaidi"></view>
				</view>
			</view>
			<view class="tab1" v-else>
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/3aea88803cb446139aa80ff5a606645a.png" alt=""
					style="position: absolute;" />
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/2cdff43ecdd4409a8bd1f5f46a6ad38d.png" alt=""
					style="position: absolute;" />
				<view style="width: 100%;height: 160rpx;position: absolute;top:0;left: 0;display: flex;">
					<view style="width: 50%;height: 160rpx;" @tap="isKuaidi=!isKuaidi"></view>
					<view style="width: 50%;height: 160rpx;"></view>
				</view>
			</view>
		</view>
		<view class="content">
			<view class="" style="background: #fff; border-radius: 20rpx; padding: 20rpx; margin-bottom: 20rpx; margin-top: 40rpx;box-shadow: 0 0 10rpx rgba(0,0,0,0.05);">
				<!-- 取货地址 -->
				<view v-if="isKuaidi" class="dizhi" style="border-bottom: 1px solid #eee; padding-bottom: 20rpx; margin-bottom: 20rpx;">
					<view class="dizhi-tu">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/1f77398a73454a6595c12a3c18731599.png" alt="" />
					</view>
					<view class="dizhi1" @tap="openKuaidiPicker">
						<view class="dizhi-ming" style="font-weight: normal; color: #333;" v-if="selectedPickupArea">
							{{selectedPickupArea.title}}
						</view>
						<view class="dizhi-ming" style="font-weight: normal; color: #999;" v-else>
							请选择快递代取点
						</view>
						<uni-icons type="right" size="14" color="#999"></uni-icons>
					</view>
				</view>
				<view v-else class="dizhi" style="border-bottom: 1px solid #eee; padding-bottom: 20rpx; margin-bottom: 20rpx;">
					<view class="dizhi-tu">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/1f77398a73454a6595c12a3c18731599.png" alt="" />
					</view>
					<view class="dizhi1" @tap="openAddressBook('get')">
						<view class="dizhi-ming" style="font-weight: normal; color: #333;" v-if="formData.pickupAddress">
							{{formData.pickupAddress.areaName || ''}}{{formData.pickupAddress.floor ? formData.pickupAddress.floor + '层' : ''}}{{formData.pickupAddress.roomNum || ''}} {{formData.pickupAddress.receiverName || ''}}
						</view>
						<view class="dizhi-ming" style="font-weight: normal; color: #999;" v-else>
							请选择取货地址
						</view>
						<uni-icons type="right" size="14" color="#999"></uni-icons>
					</view>
				</view>

				<!-- 收货地址 -->
				<view class="dizhi">
					<view class="dizhi-tu">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/d0764fb4138747769538cf1cafa3b017.png" alt="" />
					</view>
					<view class="dizhi1" @tap="openAddressBook('put')">
						<view class="dizhi-ming" style="font-weight: normal; color: #333;" v-if="formData.address">
							{{formData.address.areaName || ''}}{{formData.address.floor ? formData.address.floor + '层' : ''}}{{formData.address.roomNum || ''}} {{formData.address.receiverName || ''}}
						</view>
						<view class="dizhi-ming" style="font-weight: normal; color: #999;" v-else>
							请选择收货地址
						</view>
						<uni-icons type="right" size="14" color="#999"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 配送时间 -->
			<view class="time-box">
				<view class="time1" @tap="checkTime(true)"
					:style="{'background':formData.isImmediately?'linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1))':'#f5f5f5'}">
					<view style="font-weight: 700;">立即送出</view>
					<view style="font-size: 20rpx;color: #777;">预计{{immediateTimeStr}}送达</view>
				</view>
				<view class="time1" @tap="checkTime(false)"
					:style="{'background':formData.isImmediately==false?'linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1))':'#f5f5f5'}">
					<view style="font-weight: 700;">预约配送</view>
					<view>
						<view style="font-size: 20rpx;color: #777;" v-if="formData.isImmediately!=true&&formData.deliveryTime!=''">
							{{formData.deliveryTime}}
						</view>
						<view v-else style="font-size: 20rpx;color: #777;">选择时间 ></view>
					</view>
				</view>
			</view>

			<!-- 配送员模块 -->
			<view style="background: #fff; border-radius: 20rpx; padding: 20rpx; margin-top: 20rpx; box-shadow: 0 0 10rpx rgba(0,0,0,0.05);">
				<view style="border-bottom: 1px solid #eee; padding-bottom: 20rpx;">
					<view style="font-size: 28rpx;font-weight: 700;">配送员</view>
					<view style="font-size: 24rpx;color: #777;margin-top: 10rpx;">指定配送员，如配送员拒绝接单或者下线，订单进入抢单大厅</view>
					<view style="font-size: 24rpx;color: #777;margin-top: 10rpx;">不指定配送员超过10分钟没有人接单，会发送短信通知</view>
				</view>
				<view style="padding: 20rpx 0;">
					<view style="display: flex;font-size: 28rpx;font-weight: bold;line-height: 50rpx;margin-bottom: 30rpx;align-items: center;">
						<view style="width:50%;display: flex;align-items: center;">
							<view class="radio-check" v-if="selectedWorker === 'buzhiding'">
								<uni-icons type="checkmarkempty" size="12"></uni-icons>
							</view>
							<view class="radio-no-check" @tap="checkWorker('buzhiding')" v-else></view>
							不指定
						</view>
						<view style="width: 50%;display: flex;justify-content: flex-end;align-items: center;" v-if="selectedWorker === 'buzhiding'">
							<text style="color: #777; font-weight: normal; margin-right: 10rpx; font-size: 24rpx;">佣金 ￥</text>
							<input type="digit" v-model="customCommission"
								style="width: 140rpx; border-bottom: 1px solid #ccc; text-align: center; font-size: 28rpx; font-weight: normal; height: 50rpx; min-height: 50rpx;"
								placeholder="金额" />
						</view>
					</view>
					<view style="display: flex;font-size: 28rpx;font-weight: bold;line-height: 50rpx;">
						<view style="width:50%;display: flex;">
							<view class="radio-check" v-if="selectedWorker === 'zhiding'">
								<uni-icons type="checkmarkempty" size="12"></uni-icons>
							</view>
							<view class="radio-no-check" @tap="checkWorker('zhiding')" v-else></view>
							指定配送员
						</view>
						<view style="width: 50%;color: #777;text-align: right;" @tap="goDetail">
							{{ assignedWorker ? assignedWorker.workerName + ' ' + assignedWorker.mobile : '选配送员' }}
							<uni-icons type="right" size="12"></uni-icons>
						</view>
					</view>

					<view v-if="highFloorFeeCalc > 0" style="margin-top: 20rpx; color: #ff5722; font-size: 24rpx; background: #fff5f5; padding: 10rpx 20rpx; border-radius: 10rpx;">
						<uni-icons type="info" size="14" color="#ff5722"></uni-icons>
						因您的收货楼层在3楼以上，将额外收取配送费 ¥{{highFloorFeeCalc}}
					</view>
				</view>
			</view>

			<view class="content-box" style="height: 120rpx;">
				<view class="content-title">
					取件数量<text style="color:red;">*</text>
				</view>
				<view style="display:flex;height: 80rpx;margin-top: 20rpx;line-height: 80rpx;border: 1px solid #777;background: #eee;border-radius: 20rpx;width: 40%;">
					<view @tap="addFormData.num > 1 ? addFormData.num-- : 1" style="width: 30%;font-size: 44rpx;font-weight: 700;text-align: center;">-</view>
					<input type="number" v-model="addFormData.num" disabled style="line-height: 80rpx;height: 80rpx;flex: 1;font-size: 36rpx;font-weight: 700;text-align: center;">
					<view @tap="addFormData.num++" style="width: 30%;font-size: 44rpx;font-weight: 700;text-align: center;">+</view>
				</view>
			</view>
			<view class="content-box">
				<view class="content-title">
					取件凭证<text v-if="isKuaidi" style="color:red;">*</text>
				</view>
				<view style="flex: 1;">
					<view>
						<view style="display: flex;">手机尾号</view>
						<view class="check-input">
							<input type="text" v-model="addFormData.phoneNumber" style="width: 100%;height: 100%;padding: 0 20rpx;border: 1px solid #eee;border-radius:10rpx;" placeholder="建议填写预留手机尾号4位">
						</view>
					</view>
					<view v-if="isKuaidi">
						<view style="display: flex;">取件码</view>
						<view class="check-input" v-for="(item,index) in addFormData.codeList" :key="index" style="border: none;display: flex;">
							<input type="text" v-model="item.code" style="width: 100%;height: 100%;padding: 0 20rpx;border: 1px solid #eee;border-radius:10rpx;" placeholder="建议填写取件码">
							<view @tap="delCode(index)" v-if="addFormData.codeList.length>1" style="width: 90rpx;height: 70rpx;line-height: 70rpx;text-align: center;">
								<uni-icons type="trash" size="18"></uni-icons>
							</view>
						</view>
						<view class="check-add" @tap="addCode">+ 添加取件码</view>
					</view>
					<view>
						<view style="display: flex;">截图凭证</view>
						<view>
							<view style="display: flex; flex-wrap: wrap;">
								<view class="upload-img" @tap="pictureAdd" style="background: #eee;text-align: center;line-height: 160rpx;border-radius:10rpx;margin-top:10rpx;">
									<uni-icons type="camera" size="28" color="#777"></uni-icons>
								</view>
								<view v-for="(item,index) in addFormData.picture" :key="index" style="width: 160rpx;height: 160rpx;margin-left: 20rpx;margin-top:10rpx;position:relative;">
									<img :src="item" alt="" class="upload-img" style="border-radius:10rpx;">
									<uni-icons type="clear" size="24" color="red" @tap="delPicture(index)" style="position: absolute;top: -10rpx;right: -10rpx;background:#fff;border-radius:50%;"></uni-icons>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="content-box">
				<view class="content-title">
					特殊情况
				</view>
				<view style="flex: 1;">
					<view class="duoxuan" @tap="checkWeightOrVolume" :style="{'background':addFormData.isOverweightOrOvervolume?'rgba(166, 255, 234, 1)':'#eee'}">
						超重/超大
					</view>
				</view>
			</view>
			<view class="content-box" style="line-height: 200rpx;">
				<view class="content-title">
					订单备注
				</view>
				<view style="height: 200rpx;background: #eee;border-radius: 40rpx;padding: 20rpx;width: 70%;">
					<textarea v-model="addFormData.remark" cols="30" rows="10" placeholder="请填写备注" style="height: 160rpx;width: 100%;"></textarea>
				</view>
			</view>
			<view style="height: 80rpx;line-height: 80rpx;display: flex;margin-top: 20rpx;">
				<view style="flex: 1;color: #777;font-weight: 700;font-size:32rpx;">
					{{isKuaidi?'代取配送费':'跑腿费'}}
				</view>
				<view style="color: #000;font-weight:700;font-size:32rpx;">
					￥{{deliveryFeeCalc.toFixed(2)}}
				</view>
			</view>
			<view style="display: flex;height: 80rpx;line-height: 80rpx;border-top: 1px solid #eee;font-size: 28rpx;font-weight: 700; align-items:center;" @tap="openCouponPopup">
				<view style="flex: 1; color: #777; font-size:32rpx;">
					优惠券
				</view>
				<view style="color: #ff5722;" v-if="selectedCoupon">
					-￥{{selectedCoupon.discountAmount.toFixed(2)}}
				</view>
				<view style="color: #0b9b73;" v-else-if="availableCoupons.length > 0">
					有 {{availableCoupons.length}} 张可用
				</view>
				<view style="color: #999;" v-else>
					无可用券
				</view>
				<uni-icons type="right" size="14" color="#999" style="margin-left:10rpx;"></uni-icons>
			</view>
			<view style="display: flex;height: 80rpx;line-height: 100rpx;border-top: 1px solid #eee;font-size: 32rpx;font-weight: 700;margin-bottom: 20rpx;">
				<view style="flex: 1;">合计</view>
				<view>￥{{totalAmountCalc.toFixed(2)}}</view>
			</view>
			
			<view style="width: 100%;height: 400rpx;"></view>
		</view>
		
		<view class="buy-bottom">
			<view class="bottom-btn" @tap="submitPay">
				立即支付{{backendTotalAmount ? backendTotalAmount.toFixed(2) : totalAmountCalc.toFixed(2)}}
			</view>
		</view>
		
		<!-- 收货/取货地址簿弹出层 -->
		<uni-popup ref="bookPopup" background-color="#fff">
			<view class="book-popup-content">
				<address-list @selectAddress="handleSelectAddress" @syncAddress="handleSyncAddress" @shopAreaList="updateArea" @close="$refs.bookPopup.close()"></address-list>
			</view>
		</uni-popup>

		<!-- 快递代取点选择侧栏 (只对快递有效) -->
		<uni-popup ref="kuaidiPickerPopup" type="bottom" background-color="#fff">
			<view style="width: 100%; height: 700rpx; display: flex; flex-direction: column;">
				<view style="height: 100rpx; line-height: 100rpx; text-align: center; font-size: 32rpx; font-weight: bold; border-bottom: 1px solid #eee; position: relative;">
					选择快递代取点
					<uni-icons type="closeempty" size="24" @tap="$refs.kuaidiPickerPopup.close()" style="position: absolute; right: 30rpx; top: 0;"></uni-icons>
				</view>
				<scroll-view scroll-y style="flex: 1; padding: 20rpx; box-sizing: border-box;">
					<view v-for="(item, index) in kuaidiAreaList" :key="index" @tap="selectKuaidiArea(item)"
						style="padding: 30rpx 20rpx; border-bottom: 1px solid #f5f5f5; display: flex; align-items: center; justify-content: space-between;">
						<text style="font-size: 30rpx;">{{item.title}}</text>
						<uni-icons v-if="selectedPickupArea && selectedPickupArea.id === item.id" type="checkmarkempty" size="20" color="#a6ffea"></uni-icons>
					</view>
					<view v-if="kuaidiAreaList.length===0" style="text-align:center; padding-top: 100rpx; color: #999;">
						暂无可用快递点
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		
		<delivery-time-op @timeCallback="timeCallback" :dodge="true" ref='model' :content="content" :barHidth='600' title="选择预送达时间">> </delivery-time-op>

		<!-- 支付弹出层 -->
		<uni-popup ref="payPopup" background-color="#fff">
			<view class="pay-popup">
				<view class="content2">
					<view class="box1">
						<view style="height: 70rpx;line-height: 70rpx;text-align: center;">
							支付剩余时间 59:09
						</view>
						<view style="height: 90rpx;line-height: 90rpx;text-align: center;font-weight: 700;font-size: 30rpx;">
							￥<text style="font-size: 60rpx;">{{backendTotalAmount ? backendTotalAmount.toFixed(2) : totalAmountCalc.toFixed(2)}}</text>
						</view>
					</view>
					<view class="box1" style="display: flex;padding: 40rpx; flex-direction: row; margin: 0 auto; width: 90%;">
						<view style="flex: 1; display:flex; flex-direction:column;">
							<view style="height: 42rpx;line-height: 42rpx;display: flex;align-items:center;">
								<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/4c8e0cc311db4d38ab43e019673c4b8c.png"
									alt="" style="width: 42rpx;height: 42rpx;margin-right: 20rpx;" />
								<text style="font-size: 30rpx;font-weight: 700;">微信支付</text>
							</view>
							<view style="margin-left: 62rpx;color: #777; font-size:24rpx; margin-top:10rpx;">使用微信支付</view>
						</view>
						<view style="width: 36rpx;padding-top: 16rpx; display:flex; align-items:flex-start;">
							<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/02bff7edc4e04caaa1868955ff684f1f.png"
								alt="" style="width: 36rpx;height: 36rpx;" />
						</view>
					</view>
					<view class="btn" @tap="wxPayment" style="width: 90%; height: 100rpx; background: linear-gradient(90deg, #e3ff96, #a6ffea); font-size: 32rpx; font-weight: 700; line-height: 100rpx; text-align: center; border-radius: 100rpx; margin: 40rpx auto 60rpx;">
						确认付款
					</view>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="warnPopup" background-color="#fff">
			<view style="width:600rpx;height:740rpx;">
				<img v-if="warnPopup === 'shdz'" @tap="$refs.warnPopup.close()" src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/4996043b3987401794b974d359429b8e.png" alt="填写收货地址" style="width:100%;height:100%;" />
				<img v-if="warnPopup === 'psyj'" @tap="$refs.warnPopup.close()" src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/001cf760048b4718bdccd55085bef601.png" alt="填写配送佣金" style="width:100%;height:100%;" />
				<img v-if="warnPopup === 'psy'" @tap="$refs.warnPopup.close()" src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/e10ad77ca478413a9c53918750ecb932.png" alt="指定配送员" style="width:100%;height:100%;" />
			</view>
		</uni-popup>

		<uni-popup ref="couponPopup" type="bottom" background-color="#F5F8F5">
			<view style="width: 100%; height: 800rpx; display: flex; flex-direction: column;">
				<view style="height: 100rpx; line-height: 100rpx; text-align: center; font-size: 32rpx; font-weight: bold; border-bottom: 1px solid #eee; position: relative; background: #fff;">
					选择优惠券
					<uni-icons type="closeempty" size="24" @tap="$refs.couponPopup.close()" style="position: absolute; right: 30rpx; top: 0;"></uni-icons>
				</view>
				<scroll-view scroll-y style="flex: 1; padding: 20rpx; box-sizing: border-box;">
					<view v-for="(item, index) in availableCoupons" :key="index" @tap="selectCoupon(item)"
						style="background: #fff; border-radius: 12rpx; padding: 30rpx 20rpx; margin-bottom: 20rpx; display: flex; align-items: center; justify-content: space-between;">
						<view style="display: flex; align-items: center; flex: 1;">
							<view style="color: #ff5722; font-size: 40rpx; font-weight: bold; width: 140rpx;">
								<text style="font-size: 24rpx;">￥</text>{{item.discountAmount}}
							</view>
							<view style="flex: 1; display: flex; flex-direction: column; justify-content: center; margin-left: 20rpx;">
								<view style="font-size: 28rpx; font-weight: bold; color: #333; margin-bottom: 6rpx;">{{item.couponName}}</view>
								<view style="font-size: 22rpx; color: #999;" v-if="item.minAmount > 0">满{{item.minAmount}}可用</view>
								<view style="font-size: 22rpx; color: #999;" v-else>无门槛使用</view>
							</view>
						</view>
						<uni-icons v-if="selectedCoupon && selectedCoupon.id === item.id" type="checkmarkempty" size="20" color="#0b9b73"></uni-icons>
						<view v-else style="width: 40rpx; height: 40rpx; border-radius: 50%; border: 1px solid #ddd;"></view>
					</view>
					<view v-if="availableCoupons.length===0" style="text-align:center; padding-top: 100rpx; color: #999;">
						暂无可用优惠券
					</view>
					<view style="height:40rpx;"></view>
				</scroll-view>
				<view style="padding: 20rpx 40rpx; background: #fff;" v-if="availableCoupons.length>0">
					<view @tap="selectCoupon(null)" style="width: 100%; height: 80rpx; background: linear-gradient(90deg, #e3ff96, #a6ffea); font-size: 30rpx; font-weight: 700; line-height: 80rpx; text-align: center; border-radius: 100rpx;">
						不使用优惠券
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import deliveryTimeOp from '@/components/delivery-time-op/delivery-time-op.vue'
	import addressList from '@/package1/address/addressList.vue'
	export default {
		data() {
			return {
				isKuaidi: true,
				menuButtonInfo: {},
				selectedWorker:'buzhiding',
				assignedWorker:null,
				customCommission:'0',
				shopArea: [],
				kuaidiAreaList: [],
				selectedPickupArea: null,
				addressSelectMode: 'put', // 'put' | 'get'
				formData: {
					address: null, // 收货地址 putArea
					pickupAddress: null, // 取货地址 getArea (跑腿模式)
					isImmediately: true,
					deliveryTime: '',
					peisongyuan: ''
				},
				addFormData: {
					num: 1,
					phoneNumber: '',
					codeList: [{ code: '' }],
					picture: [],
					isOverweightOrOvervolume: false,
					remark: ''
				},
				content: [],
				immediateTimeStr: '',
				backendTotalAmount: 0,
				currentOrderId: '',
				warnPopup: '',
				availableCoupons: [],
				selectedCoupon: null
			}
		},
		components: {
			deliveryTimeOp,
			addressList
		},
		computed: {
			highFloorFeeCalc() {
				if (this.selectedWorker === 'zhiding' && this.assignedWorker) {
					let hFee = parseFloat(this.assignedWorker.highFloorFee || 0);
					if (hFee > 0 && this.formData.address && parseInt(this.formData.address.floor) > 3) {
						return hFee;
					}
				}
				return 0;
			},
			deliveryFeeCalc() {
				let commission = 0;
				if (this.selectedWorker === 'zhiding') {
					if (this.assignedWorker) {
						commission = parseFloat(this.assignedWorker.orderBkge || 3);
					}
				} else {
					let val = parseFloat(this.customCommission);
					if (!isNaN(val) && val > 0) commission = val;
				}
				return commission + this.highFloorFeeCalc;
			},
			totalAmountCalc() {
				let total = this.deliveryFeeCalc;
				if (this.selectedCoupon) {
					total = total - parseFloat(this.selectedCoupon.discountAmount);
				}
				return total > 0 ? total : 0.01;
			}
		},
		watch: {
			deliveryFeeCalc(newVal, oldVal) {
				if (newVal !== oldVal) {
					this.fetchCoupons();
				}
			}
		},
		onLoad() {
			//this.getShopArea()
		},
		onShow() {
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.initAddress()
			this.fetchCoupons()
			const now = new Date();
			const startTime = new Date(now);
			const endTime = new Date(now);
			startTime.setMinutes(startTime.getMinutes() + 20);
			endTime.setMinutes(endTime.getMinutes() + 35);
			const startStr = `${startTime.getHours().toString().padStart(2, '0')}:${startTime.getMinutes().toString().padStart(2, '0')}`;
			const endStr = `${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`;
			this.immediateTimeStr = `${startStr}-${endStr}`;

			uni.$on('updateDeliveryWorker', (worker) => {
				this.assignedWorker = worker;
				this.selectedWorker = 'zhiding';
			});
			
		},
		onUnload() {
			uni.$off('updateDeliveryWorker');
			uni.removeStorageSync('pendingAssignWorker');
		},
		methods: {
			openCouponPopup() {
				this.fetchCoupons();
				this.$refs.couponPopup.open('bottom');
			},
			fetchCoupons() {
				let userId = uni.getStorageSync('id');
				if (!userId) return;
				let amount = this.deliveryFeeCalc;
				this.tui.request('/mall/coupon/available', 'GET', {
					userId: userId,
					applyScene: 2,
					regionId:JSON.parse(uni.getStorageSync('area')).id,
					amount: amount,
					merchantId: '0'
				}, false, true).then((res) => {
					if (res.code == 200 && res.result) {
						this.availableCoupons = res.result;
						if (this.selectedCoupon) {
							let stillValid = this.availableCoupons.find(c => c.id === this.selectedCoupon.id);
							if (!stillValid) this.selectedCoupon = null;
						}
					}
				});
			},
			selectCoupon(item) {
				this.selectedCoupon = item;
				this.$refs.couponPopup.close();
			},
			getShopArea(){
				let that = this
				let areaStorage = uni.getStorageSync('area');
				if(!areaStorage) return;
				that.tui.request("/app/shopArea/getByParentId/"+JSON.parse(areaStorage).id, "GET", {}, false, true).then((res) => {
					if (res.code == 200) {
						if(res.result != null){
							that.shopArea = res.result;
							that.kuaidiAreaList = that.shopArea.filter(item => item.isCanteen === 2);
						}
					} else {
						that.tui.toast(res.message)
						return
					}
				}).catch((res) => {})
			},
			initAddress() {
				let cachedAddress = uni.getStorageSync('selectedAddress');
				if (cachedAddress && !this.formData.address) {
					this.formData.address = cachedAddress;
				} else if(!this.formData.address){
					let that = this;
					let userId = uni.getStorageSync('id');
					if(!userId) return;
					that.tui.request("/app/userAddress/list", "GET", {
						userId: userId
					}, false, true).then((res) => {
						if (res.code == 200 && res.result && res.result.length > 0) {
							let target = res.result.find(item => item.isDefault == 1) || res.result[0];
							that.formData.address = target;
							uni.setStorageSync('selectedAddress', target);
						}
					}).catch(() => {});
				}
			},
			openAddressBook(mode) {
				this.addressSelectMode = mode;
				this.$refs.bookPopup.open('bottom');
			},
			handleSelectAddress(address) {
				if (this.addressSelectMode === 'put') {
					this.formData.address = address;
					uni.setStorageSync('selectedAddress', address);
				} else {
					this.formData.pickupAddress = address;
				}
				this.$refs.bookPopup.close();
			},
			updateArea(v){
				this.shopArea = v
				this.kuaidiAreaList = v.filter(item => item.isCanteen === 2);
			},
			handleSyncAddress(address) {
				if (this.addressSelectMode === 'put') {
					this.formData.address = address;
				}
			},
			openKuaidiPicker() {
				this.$refs.kuaidiPickerPopup.open();
			},
			selectKuaidiArea(item) {
				this.selectedPickupArea = item;
				this.$refs.kuaidiPickerPopup.close();
			},
			goDetail() {
				let shopAreaId = '';
				if (this.isKuaidi) {
					shopAreaId = this.selectedPickupArea ? this.selectedPickupArea.id : '';
				} else {
					shopAreaId = this.formData.pickupAddress ? this.formData.pickupAddress.areaId : '';
				}
				let putAreaId = this.formData.address ? this.formData.address.areaId : '';
				if(this.isKuaidi){
					uni.navigateTo({
						url: `/package1/index/deliveryPersonList?orderType=1&shopAreaId=${shopAreaId}&putAreaId=${putAreaId}`
					});
				}else{
					uni.navigateTo({
						url: `/package1/index/deliveryPersonList?shopAreaId=${shopAreaId}&putAreaId=${putAreaId}`
					});
				}
				
			},
			checkTime(type) {
				if (type === this.formData.isImmediately) {
					if (type === false) {
						this.$refs.model.open()
						this.generateDeliveryTimes()
					}
					return;
				}
				this.formData.isImmediately = type;
				if (this.formData.isImmediately === false) {
					this.$refs.model.open()
					this.generateDeliveryTimes()
				}
			},
			generateDeliveryTimes() {
				const now = new Date();
				const today = new Date(now);
				const tomorrow = new Date(now);
				tomorrow.setDate(tomorrow.getDate() + 1);

				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const todayWeekday = weekdays[today.getDay()];
				const todayStr = `今天 (${todayWeekday})`;

				const month = tomorrow.getMonth() + 1;
				const day = tomorrow.getDate();
				const tomorrowStr = `${month}-${day}`;

				const todayTimelist = [{ timestr: '自动送达' }];
				const currentHour = now.getHours();
				const currentMinute = now.getMinutes();

				let nextHour = currentHour;
				let nextMinute = 30;
				if (currentMinute >= 30) {
					nextHour = currentHour + 1;
					nextMinute = 0;
				}

				for (let h = nextHour; h <= 23; h++) {
					const startMin = (h === nextHour) ? nextMinute : 0;
					for (let m = startMin; m < 60; m += 30) {
						if (h === 23 && m > 30) continue;
						const timeStr = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
						todayTimelist.push({ timestr: timeStr });
					}
				}

				const tomorrowTimelist = [];
				for (let h = 0; h <= 23; h++) {
					for (let m = 0; m < 60; m += 30) {
						if (h === 23 && m > 30) continue;
						const timeStr = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
						tomorrowTimelist.push({ timestr: timeStr });
					}
				}

				this.content = [
					{ timezh: todayStr, timelist: todayTimelist },
					{ timezh: tomorrowStr, timelist: tomorrowTimelist }
				];
			},
			timeCallback(val) {
				this.formData.deliveryTime = val.timestr;
				this.$refs.model.close();
			},
			checkWorker(type) {
				if (type == this.selectedWorker) return;
				this.selectedWorker = type;
				if (this.selectedWorker == 'buzhiding') {
					this.formData.peisongyuan = "";
					this.assignedWorker = null;
				}
			},
			checkWeightOrVolume() {
				this.addFormData.isOverweightOrOvervolume = !this.addFormData.isOverweightOrOvervolume
			},
			addCode() {
				this.addFormData.codeList.push({ code: '' })
			},
			delCode(index) {
				this.addFormData.codeList.splice(index, 1)
			},
			pictureAdd() {
				let that = this
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album'],
					success(res) {
						uni.showLoading({
							title: '加载中...',
							mask: true
						})
						for (let i = 0; i < res.tempFiles.length; i++) {
			
							that.upLoadFile(res.tempFiles[i].tempFilePath)
						}
			
					}
				})
			},
			async upLoadFile(path) {
				let that = this;
				let hiver_token = uni.getStorageSync("hiver_token")
				await uni.uploadFile({
					url: that.tui.interfaceUrl() + '/upload/file',
					filePath: path,
					name: 'file',
					header: {
						"content-type": "multipart/form-data",
						'accessToken': hiver_token
					},
					formData: {},
					success: (uploadFileRes) => {
						let data = JSON.parse(uploadFileRes.data);
						if (data.success) {
							that.addFormData.picture.push(data.result);
						} else {
							that.tui.toast(data.message);
						}
						that.$forceUpdate()
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: JSON.stringify(err),
							icon: 'none'
						})
					}
				});
				await setTimeout(res => {
					uni.hideLoading();
				}, 1000)
			},
			delPicture(index) {
				this.addFormData.picture.splice(index, 1);
			},
			getMustFinishTime() {
				if (this.formData.isImmediately || !this.formData.deliveryTime || this.formData.deliveryTime === '自动送达' || this.formData.deliveryTime === '尽快送达') {
					const now = new Date();
					now.setMinutes(now.getMinutes() + 35);
					const year = now.getFullYear();
					const month = String(now.getMonth() + 1).padStart(2, '0');
					const day = String(now.getDate()).padStart(2, '0');
					const hours = String(now.getHours()).padStart(2, '0');
					const minutes = String(now.getMinutes()).padStart(2, '0');
					const seconds = String(now.getSeconds()).padStart(2, '0');
					return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
				} else {
					let timeStr = this.formData.deliveryTime;
					if (timeStr.length === 5) {
						let [h, m] = timeStr.split(':');
						let targetHour = parseInt(h);
						let d = new Date();
						if (targetHour < d.getHours()) d.setDate(d.getDate() + 1);
						let yyyy = d.getFullYear();
						let MM = String(d.getMonth() + 1).padStart(2, '0');
						let DD = String(d.getDate()).padStart(2, '0');
						return `${yyyy}-${MM}-${DD}T${timeStr}:00`;
					}
				}
				return null;
			},
			submitPay() {
				if (this.isKuaidi && !this.selectedPickupArea) {
					uni.showToast({ title: '请选择代取点', icon: 'none' });
					return;
				}
				if (!this.isKuaidi && !this.formData.pickupAddress) {
					uni.showToast({ title: '请选择取货地址', icon: 'none' });
					return;
				}
				if (!this.formData.address) {
					this.warnPopup = 'shdz';
					this.$refs.warnPopup.open();
					return;
				}
				if (this.selectedWorker === 'buzhiding') {
					let comm = parseFloat(this.customCommission);
					if (isNaN(comm) || comm <= 0) {
						this.warnPopup = 'psyj';
						this.$refs.warnPopup.open();
						return;
					}
				}
				if (this.selectedWorker === 'zhiding' && !this.assignedWorker) {
					this.warnPopup = 'psy';
					this.$refs.warnPopup.open();
					return;
				}
				if (this.isKuaidi && (!this.addFormData.codeList || this.addFormData.codeList[0].code.trim() === '') && this.addFormData.picture.length === 0) {
					uni.showToast({ title: '请填写取件码或上传截图凭证', icon: 'none' });
					return;
				}
				
				this.submitOrderToBackend();
			},
			submitOrderToBackend() {
				let deliveryType = this.isKuaidi ? 2 : 3;
				
				let putAddressStr = (this.formData.address.areaName || '') + (this.formData.address.floor ? this.formData.address.floor + '层' : '') + (this.formData.address.roomNum || '');
				let shopAddressStr = '';
				let shopName = '';
				let shopPhone = '';
				let getAreaId = '';
				
				if (this.isKuaidi) {
					shopAddressStr = this.selectedPickupArea.title;
					shopName = this.selectedPickupArea.title;
					getAreaId = this.selectedPickupArea.id;
				} else {
					shopAddressStr = (this.formData.pickupAddress.areaName || '') + (this.formData.pickupAddress.floor ? this.formData.pickupAddress.floor + '层' : '') + (this.formData.pickupAddress.roomNum || '');
					shopName = this.formData.pickupAddress.receiverName || '个人寄件';
					shopPhone = this.formData.pickupAddress.receiverPhone || '';
					getAreaId = this.formData.pickupAddress.areaId;
				}
				
				let codes = this.addFormData.codeList.map(c => c.code).filter(c => c).join(',');
				let pics = this.addFormData.picture.join(',');

				let payload = {
					getAreaId: getAreaId,
					putAreaId: this.formData.address.areaId,
					deliveryType: deliveryType,
					receiverName: this.formData.address.receiverName,
					receiverPhone: this.formData.address.receiverPhone,
					receiverAddress: putAddressStr,
					shopAddress: shopAddressStr,
					shopId: uni.getStorageSync('id'),
					shopPhone: shopPhone,
					remark: this.addFormData.remark,
					allCount: this.addFormData.num,
					isBig: this.addFormData.isOverweightOrOvervolume ? 1 : 0,
					phoneNumber: this.addFormData.phoneNumber,
					getCodes: codes,
					getPictures: pics,
					regionId: JSON.parse(uni.getStorageSync('area')).id,
					deliveryFee: this.deliveryFeeCalc,
					userCouponId: this.selectedCoupon ? this.selectedCoupon.id : null
				};

				let mft = this.getMustFinishTime();
				if (mft) payload.mustFinishTime = mft;

				if (this.selectedWorker === 'zhiding' && this.assignedWorker) {
					payload.workerId = this.assignedWorker.workerId;
					payload.workerName = this.assignedWorker.workerName;
					payload.workerPhone = this.assignedWorker.mobile;
					payload.workerParam = { // Backend processing might specifically look for workerParam.orderBkge
						workerId: this.assignedWorker.workerId,
						workerName: this.assignedWorker.workerName,
						orderBkge: parseFloat(this.assignedWorker.orderBkge || 0) + this.highFloorFeeCalc
					}
					// deliveryFee override just in case
					payload.deliveryFee = parseFloat(this.assignedWorker.orderBkge || 3) + this.highFloorFeeCalc;
				} else if (this.selectedWorker === 'buzhiding') {
					payload.workerParam = { orderBkge: parseFloat(this.customCommission || 0) };
					payload.deliveryFee = parseFloat(this.customCommission || 0);
				}

				uni.showLoading({ title: '创建订单中...' });
				
				this.tui.request("/mall/delivery/insert", "POST", payload, false, false).then(res => {
					uni.hideLoading();
					if (res.success && res.result) {
						this.currentOrderId = res.result.id;
						this.backendTotalAmount = res.result.deliveryFee || this.deliveryFeeCalc;
						this.$refs.payPopup.open('bottom');
					} else {
						uni.showToast({ title: res.message || '下单失败', icon: 'none' });
					}
				}).catch(err => {
					uni.hideLoading();
				});
			},
			wxPayment() {
				let that = this;
				if (!this.currentOrderId || !this.backendTotalAmount) return;

				let amountInCents = Math.round(this.backendTotalAmount * 100);
				let payDesc = this.isKuaidi ? '代取快递费' : '代跑腿费';

				this.tui.request("/api/wechat/pay/unified-order", "POST", {
					openid: uni.getStorageSync('miniProgramOpenid') || 'test-openid',
					amount: amountInCents,
					description: payDesc,
					outTradeNo: this.currentOrderId
				}, false, false).then((res) => {
					if (res.code == 200) {
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.timeStamp,
							nonceStr: res.nonceStr,
							package: res.package,
							signType: res.signType,
							paySign: res.paySign,
							success: function(res2) {
								uni.showToast({ title: '支付成功', icon: 'success' });
								that.tui.request("/api/wechat/pay/paySuccess", "POST", {
									outTradeNo: that.currentOrderId
								}, false, false).then((res3) => {
									if(res3.code == 200) {
										that.handlePaymentSuccess();
									} else {
										that.tui.toast("系统繁忙，请联系客服处理");
									}
								})
							},
							fail: function(err) {
								uni.redirectTo({
									url: '/package1/order/orderDetail?id=' + that.currentOrderId
								});
							}
						});
					} else {
						uni.redirectTo({
							url: '/package1/order/orderDetail?id=' + that.currentOrderId
						});
					}
				})
			},
			handlePaymentSuccess() {
				uni.redirectTo({
					url: '/package1/order/orderDetail?id=' + this.currentOrderId
				});
			},
			back() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		background: #F5F8F5;
		color: #00231C;
	}

	.page1 {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		position: relative;
		overflow: hidden;
	}

	.title {
		background: url('https://jewel-shop.oss-cn-beijing.aliyuncs.com/8bc15960c2dc40268e295d6dd23aecce.png') no-repeat;
		width: 100%;
		height: 40%;
	}

	.title-sreach {
		width: 100%;
		display: flex;
		height: 200rpx;
		position: relative;
	}

	.back-btn {
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.title-name {
		padding-top: 110rpx;
		font-size: 36rpx;
		font-weight: 700;
		flex: 1;
		text-align: center;
	}

	.content {
		position: absolute;
		top: 280rpx;
		width: 100%;
		overflow: scroll;
		height: 100%;
		padding: 0 4%;
		box-sizing: border-box;
	}

	.tab1 {
		width: 100%;
		height: 160rpx;
		position: relative;

		img {
			width: 100%;
			height: 100%;
			background-size: 100%;
		}
	}

	.upload-img {
		width: 160rpx;
		height: 160rpx;
	}

	.dizhi {
		display: flex;
	}

	.dizhi-tu {
		width: 50rpx;
		height: 50rpx;
		margin: 26rpx 20rpx 0 0;

		img {
			width: 100%;
			height: 100%;
		}
	}

	.dizhi1 {
		flex: 1;
		height: 100rpx;
		line-height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.dizhi-ming {
		font-size: 30rpx;
		font-weight: 700;
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.content-box {
		width: 100%;
		display: flex;
		line-height: 120rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 0 20rpx;
		margin-top: 20rpx;
		box-shadow: 0 0 10rpx rgba(0,0,0,0.05);
		box-sizing: border-box;
	}

	.content-title {
		font-size: 28rpx;
		font-weight: 700;
		margin-right: 40rpx;
	}

	.radio-check {
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
		width: 48rpx;
		height: 48rpx;
		border-radius: 48rpx;
		text-align: center;
		line-height: 48rpx;
		margin: 0 20rpx 0 0;
	}

	.radio-no-check {
		width: 48rpx;
		height: 48rpx;
		border-radius: 48rpx;
		border: 1px solid #eee;
		margin: 0 20rpx 0 0;
	}

	.check-input {
		height: 70rpx;
		width: 100%;
		margin-bottom: 20rpx;
	}

	.check-add {
		width: 160rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		background: rgba(166, 255, 234, 1);
		margin-top: 10rpx;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		font-size: 22rpx;
	}

	.duoxuan {
		display: inline-block;
		text-align: center;
		height: 72rpx;
		background: #eee;
		line-height: 72rpx;
		border-radius: 10rpx;
		padding: 0 20rpx;
		color: #777;
		margin-right: 20rpx;
		margin-top: 24rpx;
	}

	.buy-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 150rpx;
		display: flex;
		background: #fff;
		z-index: 99;
		box-shadow: 0 -20rpx 30rpx rgba(0, 0, 0, 0.3);
	}

	.bottom-btn {
		width: 90%;
		height: 100rpx;
		background: linear-gradient(90deg, #e3ff96, #a6ffea);
		font-size: 32rpx;
		font-weight: 700;
		line-height: 100rpx;
		text-align: center;
		border-radius: 100rpx;
		margin: 20rpx auto;
	}

	.book-popup-content{
		position: relative;
		height: 1200rpx;
		width: 100%;
		padding: 20rpx;
		overflow: scroll;
		box-sizing: border-box;
	}
	
	.time-box {
		background: #fff;
		display: flex;
		height: 140rpx;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-top: 20rpx;
		box-shadow: 0 0 10rpx rgba(0,0,0,0.05);
		box-sizing: border-box;
	}

	.time1 {
		height: 100rpx;
		flex: 1;
		border-radius: 20rpx;
		text-align: center;
		margin: 0 10rpx;
		line-height: 40rpx;
		padding-top: 10rpx;
		box-sizing: border-box;
	}

    .content2 {
        background: #fff;
        border-radius: 40rpx 40rpx 0 0;
        overflow: hidden;
    }
</style>