<template>
	<!-- <div>订单详情</div> -->
	<view class="box box-size">
		<view class="top box-size" :style="{ borderRadius: '16rpx' }">
			<view class="top_left box-size">
				<view>
					本单客户支付金额
					<view class="vertically_center text1">
						¥ {{ orderDetail.order?.h5OrderVO?.payAmount }}
					</view>
				</view>
				X
				<view>
					您的分成比例
					<view class="vertically_center text1">
						<!-- 20% -->
						{{ orderDetail.pet_payment_bcs[userInfo.userBcsRole - 1].paramValueText }}
					</view>
				</view>
				=
				<view>
					本单酬劳
					<view class="vertically_center text1">
						¥ {{ orderDetail.order.orderGive}}
						<!-- ¥ {{ orderDetail.pet_payment_bcs[userInfo.userBcsRole - 1].paramValueNo * orderDetail.order?.h5OrderVO?.payAmount }} -->
					</view>
				</view>
			</view>
			<view class="top_bottom">
				<!-- 订单为系统派发，请确认订单信息后再抢单 -->
				{{ typeInfo[orderDetail.order.type].content }}
			</view>
			<view class="top-button" :style="{ borderRadius: '27rpx' }">
				{{ typeInfo[orderDetail.order.type].title }}
			</view>
		</view>
		<view class="information box-size" style="border-radius: 15rpx;
		padding-bottom: 30rpx;">
			<view class="form-title">
				基本信息
			</view>
			<view class="line1">
			</view>
			<view class="time">
				<view>
					服务日期
				</view>
				<view v-if="orderDetail.order" class="time-content">
					{{ getTextList().join('，') }}
				</view>
			</view>
			<view class="line1">
			</view>
			<view class="time">
				<view>
					服务地址
				</view>
				<view class="time-content">
					{{ orderDetail.order?.address }}
				</view>
			</view>
		</view>
		<view class="service box-size" :style="{ borderRadius: '8rpx' }">
			<!-- <view class="horizontal_distribution service_top">
				<view class="form-title">
					服务内容和酬劳
				</view>
				<view @click="petInfo" class="text2 flex">
					查看宠物信息
					<u-icon name="arrow-right-double" color="#F5F5F5" size="10"></u-icon>
				</view>
			</view>
			<view class="line1">
			</view>
			<view v-for="pet in orderDetail.order.h5OrderVO.petVOList" 
			@click="toDetail(pet.id)"
			:key="pet.id" class="pet_information box-size">
				<view class="flex pet_item box-size">
					<view class="img" :style="{borderRadius:'100rpx'}">
						<image :src="pet.photo" mode=""></image>
					</view>
					<view>
						<view class="flex name">
							<view class="name_text">
								{{ pet.breed }}
							</view>
							<image :src="pet.gender == '男生' ? 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/sex_m.png':
																'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/sex_f.png'" mode=""></image>
						</view>
						{{ pet.type }}{{ pet.bodyType }}
					</view>
				</view>
				<view class="pet-level" v-for="(it, i) in pet.productNameText"
				:key="i" style="margin: 4rpx 0;">
					<text style="color: #999;padding-right: 20rpx">{{ it.time }}</text>
					<text>{{ it.name }}</text>
					<text style="color: #999;padding-left: 20rpx">上门1次</text>
				</view>
				<view class="pet-level">
					12-15
					<text>专业喂养</text>
					上门1次
				</view>
			</view> -->
			
			<ServiceItems :items="serviceList"/>
			
			<view class="line1">
			</view>
			<view class="flex money_total">
				<view>
					合计
				</view>
				<view class="money_text">
					¥&nbsp;{{ orderDetail.order.price }}
				</view>
			</view>
		</view>
		<view class="other_information box-size">
			<view class="form-title">
				其他信息
			</view>
			<view class="line1">
			</view>
			<view class="horizontal_distribution text3">
				<view>
					订单编号：
				</view>
				<view>
					{{ orderDetail.order.orderSn }}
				</view>
			</view>
			<view class="line1">
			</view>
			<view class="horizontal_distribution text3">
				<view>
					下单时间：
				</view>
				<view>
					{{ orderDetail.order?.createTime }}
				</view>
			</view>
			<view class="line1">
			</view>
			<view class="horizontal_distribution text3">
				<view>
					支付时间：
				</view>
				<view>
					{{ orderDetail.order.payTime }}
				</view>
			</view>
		</view>
	</view>
	<view class="bottom" v-if="pathType != 'my'">
		<view @click="rushToBuyAnOrder" class="bottom_button level" :style="{ borderRadius: '41rpx' }">
			立即抢单
		</view>
	</view>

	<up-popup :show="showConfirmOrder" mode="bottom" @close="close" @open="open" :round="10" :closeable="true"
		:safeAreaInsetBottom="false"
		:customStyle="{padding:'60rpx 20rpx 40rpx 20rpx;position:relative;height:auto;background:#F6F5F8;'}">
		<view>
			<view style="position:absolute;top: 20rpx;left:0;text-align: center;width: 100%;">
				订单信息
			</view>
			<view style="text-align: center;">
				请全部确认后接单
			</view>
			<view class="order-confirmation">
				<view class="confirmation-item">
					<view class="confirmation-base">
						<view class="title">
							服务日期
						</view>
						<view class="desc">
							共{{ getTextList().length }}天:{{ getTextList().join('，') }}
						</view>
					</view>
					<view class="ok">
						<view class="btn" @click="handleConfirm(0)" :class="{ 'btn-confirmed': confirmStatus[0] }">
							{{ confirmStatus[0] ? '已确认' : '点击确定' }}
						</view>
					</view>
				</view>

				<view class="confirmation-item">
					<view class="confirmation-base">
						<view class="title">
							服务地址
						</view>
						<view class="desc">
							{{ orderDetail.order.address }}
						</view>
					</view>
					<view class="ok">
						<view class="btn" @click="handleConfirm(1)" :class="{ 'btn-confirmed': confirmStatus[1] }">
							{{ confirmStatus[1] ? '已确认' : '点击确定' }}
						</view>
					</view>
				</view>

				<view class="confirmation-item">
					<view class="confirmation-base">
						<view class="title">
							服务宠物
						</view>
						<view class="desc">
							<view v-for="pet in orderDetail.order.h5OrderVO.petVOList" :key="pet.id">
								{{ pet.breed }}（{{ pet.bodyType }}）
							</view>
						</view>
					</view>
					<view class="ok">
						<view class="btn" @click="handleConfirm(2)" :class="{ 'btn-confirmed': confirmStatus[2] }">
							{{ confirmStatus[2] ? '已确认' : '点击确定' }}
						</view>
					</view>
				</view>
			</view>
			<view class="handbook">
				接单即接受
				<text class="text" @click="configPopupRef.open('pet_platform_introduction')">《伴宠师手册》</text>
			</view>
			<up-button @click="conform" color="#FFBF60" text="确定" shape="circle"></up-button>
		</view>
	</up-popup>

	<!-- 抢单成功 -->
	<up-popup :show="showOrderSuccess" mode="center" @close="orderSuccessClose" @open="orderSuccessOpen" :zIndex="999"
		:round="10" :safeAreaInsetBottom="false" :customStyle="{ width:'80%' , 'background-color': 'transparent' }">
		<view>
			<image style="width: 100%;" :src="configList?.order_success?.paramValueImage" mode="widthFix"></image>
		</view>
		<view style="margin-top: -100%;padding: 40rpx;20rpx">
			<view class="success-desc">
				{{ configList?.order_success?.paramValueText || '请立即添加服务顾问，并提供订单编码' }}
			</view>
			<view style="position: relative;z-index: 999;" class="qr-code">
				<image class="code-img" :src="
				configList?.pet_qrcode?.paramValueImage ||
				'https://img.xjishu.com/img/zl/2018/6/30/1241359458913.gif'"
					mode="aspectFill"></image>
			</view>
			<view class="input">
				<up-input placeholder="" border="none" v-model="value" disabled
					:customStyle="{height:'60rpx','text-indent': '20rem', 'background-color': '#F3F3F3', position : 'relative','z-index' : '999' }"></up-input>
			</view>
			<view class="button-group">
				<up-button @click="noneOrder" color="#FFBF60" text="复制订单编号" shape="circle"></up-button>
				<up-button v-if="showSecondButton" @click="toMyOrder" color="#FFBF60" text="到我的订单查看" shape="circle"></up-button>
			</view>
		</view>
	</up-popup>
	<configPopup ref="configPopupRef" />

	<!-- 客服组件 -->
	<CustomerService />
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getByOrderId
	} from "@/api/receivingHall/index.js"
	import {
		onShow
	} from '@dcloudio/uni-app'
	import order from '../../../api/order/order'
	import {
		startByOrderId
	} from "@/api/receivingHall/index.js"
	import {
		useStore
	} from "vuex"
	
	import ServiceItems from '@/components/order/ServiceItems.vue'
	
	import dayjs from "dayjs";
	import configPopup from '@/components/configPopup.vue'
	const configPopupRef = ref(null)

	onLoad((options) => {
		orderId.value = options.id || null;
		pathType.value = options.type || ''
	});

	onShow(() => {
		getDetail();
	})

	const pathType = ref('')

	const store = useStore();
	const orderId = ref(null);
	const orderDetail = ref({});
	const serviceList = ref([]);
	const showConfirmOrder = ref(false);
	const showOrderSuccess = ref(false);
	const value = ref("45619491656")
	const petList = ref([])
	const confirmStatus = ref([false, false, false]); // 添加确认状态数组，分别对应三个确认项
	const showSecondButton = ref(false); // 控制第二个按钮的显示
	const userInfo = computed(() => {
		return store.getters.userInfo
	})
	const configList = computed(() => {
		return store.getters.configList;
	})
	// 抢单
	const rushToBuyAnOrder = () => {
		open()
	}
	
	const typeInfo = [
		{
			title : '系统派单',
			content : '订单为系统派发，请确认订单信息后再抢单',
		},
		{
			title : '个人订单',
			content : '订单为个人订单，请确认订单信息后再接单',
		},
		{
			title : '流失订单',
			content : '订单为系统派发，请确认订单信息后再抢单',
		},
	]

	// 查看宠物信息
	const petInfo = () => {
		uni.navigateTo({
			url: "/otherPages/orderTakingManage/pet/index?id=" + orderDetail.value.order.orderId
		})
	}

	const open = () => {
		showConfirmOrder.value = true;
	}

	const close = () => {
		showConfirmOrder.value = false;
	}

	const orderSuccessClose = () => {
		showOrderSuccess.value = false;
	};

	const orderSuccessOpen = () => {
		showOrderSuccess.value = true;
		// 重置按钮显示状态，初始只显示复制订单编号按钮
		showSecondButton.value = false;
	};

	// 处理确认按钮点击事件
	const handleConfirm = (index) => {
		confirmStatus.value[index] = true;
	}
	
	const conform = async () => {
		
		if(confirmStatus.value.includes(false)){
			uni.showToast({
				title: '请点击确认',
				icon: "none"
			});
			return
		}
		
		close();
		// 重置确认状态
		confirmStatus.value = [false, false, false];
		let response = await startByOrderId({
			id: orderId.value,
			userId: userInfo.value.userId
		})
		if (response.code == 200 && response.data) {
			uni.showToast({
				title: '接单成功~',
				icon: "none"
			});
			orderSuccessOpen();
		}
	}

	const getDetail = async () => {
		let response = await getByOrderId({
			id: orderId.value,
			userId: userInfo.value.userId,
		});
		if (response.code == 200 && response.data) {
			orderDetail.value = response.data;
			
			let data = response.data.order.h5OrderVO;
			
			//=====================服务项目以及费用的计算开始=====================
			
			let items = []
			
			//1、找出有哪些日期
			let days = [...new Set(data.orderServiceList.map(item => item.serviceDate))]
			
			
			days.forEach(day => {
			
			    let price = 0;
			
			    let itemsText = []
			
			    //2、找出每个日期对应的服务对象
			    let dayItems = data.orderServiceList.filter(item => item.serviceDate === day)
			
			    //3、找出每个服务对象对应的宠物
			    let pets = data.petVOList.filter(item => dayItems.some(dayItem => dayItem.petId === item.id))
			
			    //深度拷贝pets
			    pets = JSON.parse(JSON.stringify(pets))
			
			    //4、将每个服务对象添加进对应的宠物
			    pets.forEach(pet => {
			        pet.serviceList = dayItems.filter(item => item.petId === pet.id)
			
			        let itemList = []
			
			        //5、将每个服务对象中添加对应的项目
			        pet.serviceList.forEach(item => {
			            itemList.push(...(data.orderItemList.filter(n => n.orderServiceId == item.id)))
			        })
			        
			        itemList.forEach(p => {
			            price += p.salePrice * p.quantity
			            
			            itemsText = [...new Set([...itemsText, p.productName])]
			        })
			
			        pet.itemList = itemList
			    })
			
			    //6、将每个宠物添加进items
			    items.push({
			        price,
			        pets,
			        day,
			        itemsText,
			    })
			})
			
			
			//根据日期排序
			items = items.sort((a, b) => dayjs(a.day).valueOf() - dayjs(b.day).valueOf())
			
			items.forEach(n => {
				n.day = dayjs(n.day).format('MM-DD')
			})
			
			console.log(items);
			
			serviceList.value = items
			
			
			//=====================服务项目以及费用的计算结束=====================
			
			
			
			orderDetail.value.order.h5OrderVO.petVOList.forEach(pet => {
				
				pet.productNameText = getProductNameText(pet.id, orderDetail.value.order.h5OrderVO.orderItemList, 
				orderDetail.value.order.h5OrderVO.orderServiceList)
			})
		}
	}
	
	function getOrderServiceText(petId, orderServiceList){
		
		let YYYY = undefined
		
		return orderServiceList
		.filter(service => service.petId == petId)//过滤
		.map(service => dayjs(service.serviceDate))//转成时间
		.sort((a, b) => a.valueOf() - b.valueOf())//排序
		.map((service, i) => {
			// if(YYYY && YYYY.format('YYYY-MM') == service.format('YYYY-MM')){
			// 	return service.format('DD')
			// }
			// if(YYYY && YYYY.format('YYYY') == service.format('YYYY')){
			// 	return service.format('MM-DD')
			// }
			// YYYY = service
			return service.format('MM-DD')
		})
	}
	function getProductNameText(petId, productList, orderServiceList){
		
		let orderService = orderServiceList.filter(service => service.petId == petId)
		
		// return productList
		// .filter(product => orderService.filter(service => service.id == product.orderServiceId).length > 0)
		// .map(product => {
		// 	return {
		// 		time : dayjs(orderService.filter(service => service.id == product.orderServiceId)
		// 		.serviceDate).format('MM-DD'),
		// 		name : product.productName,
		// 	}
		// })
		
		return orderService.map(item => {
			
			let name = ''
			
			productList.forEach(product => {
				if(item.id == product.orderServiceId){
					name = product.productName
				}
			})
			
			return {
				time : dayjs(item.serviceDate).format('MM-DD'),
				name,
			}
		})
	}
	
	function getTextList(){
		// return orderDetail.value.order?.h5OrderVO
		// 	.orderServiceList.map(item => 
		// 	dayjs(item.serviceDate).format('MM-DD'))
		
		return serviceList.value.map(n => n.day)
	}
	
	const toDetail = (id) => {
		uni.navigateTo({
			url: `/otherPages/orderTakingManage/pet/detail?id=${id}`
		})
	}
	
	// 复制订单编号
	const noneOrder = () => {
		uni.setClipboardData({
			data: orderDetail.value.order.orderSn,
			success: function() {
				uni.showToast({
					title: '复制成功',
					icon: 'none'
				});
				// 点击复制按钮后显示第二个按钮
				showSecondButton.value = true;
			}
		});
	}
	
	// 跳转到我的订单页面
	const toMyOrder = () => {
		orderSuccessClose();
		uni.switchTab({
			url: '/pages/myOrdersManage/index'
		});
	}
</script>

<style scoped lang="scss">
	@import "index";
	
	.line1 {
		position: relative;
		margin: 10rpx 0 20rpx 0;

		&::before {
			position: absolute;
			top: 10rpx;
			left: -10rpx;
			content: "";
			width: 690rpx;
			height: 0.5rpx;
			background-color: #EFEFEF;
			// background-color: red;
		}
	}
	
	.time-content {
		max-height: 120rpx;
		overflow-y: auto;
		word-break: break-word;
		line-height: 1.5;
		padding: 4rpx 0;
	}

	.order-confirmation {
		.confirmation-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			background: white;
			padding: 20rpx;
			border-radius: 20rpx;
			overflow: hidden;
			margin: 20rpx 0rpx;

			.confirmation-base {
				width: 75%;

				.title {
					font-size: 34rpx;
				}

				.desc {
					color: #999999;
					font-size: 28rpx;
					margin-top: 20rpx;
				}
			}

			.ok {
				display: flex;
				justify-content: center;
				width: 25%;

				.btn {
					display: flex;
					align-items: center;
					justify-content: center;
					background: #FFBF60;
					color: white;
					width: 100%;
					font-size: 26rpx;
					padding: 15rpx 20rpx;
					border-radius: 30rpx;
				}
			}
		}
	}

	.handbook {
		color: #999999;
		margin: 10rpx 0rpx;

		.text {
			color: #FFBF60;
		}
	}

	.success-desc {
		text-align: center;
		color: #787878;
		font-size: 32rpx;
	}

	.qr-code {
		display: flex;
		justify-content: center;
		margin: 40rpx 0rpx;

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

	.input {
		margin-bottom: 40rpx;
	}
	
	.button-group {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.btn-confirmed {
		background: #CCCCCC !important; /* 灰色背景 */
	}
</style>