<template>
	<!-- <view>打卡</view> -->
	<view class="box box-size">
		<view class="top box-size" :style="{borderRadius:'16rpx'}">
			<view class="form-title">
				个人准备
			</view>
			<view class="mt32 ml10">
				<span :style="{fontSize:'30rpx',fontWeight:'400'}">手套照片</span>
				<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(至少1张)</span>
			</view>
			<view class="level">
				<view class="mt20 ml10">

					<up-upload :fileList="fileList.glove" @afterRead="afterRead" @delete="deletePic" name="glove"
						multiple :maxCount="2" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>


				</view>
			</view>
			<view class="mt32 ml10">
				<span :style="{fontSize:'30rpx',fontWeight:'400'}">鞋套照片</span>
				<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(至少1张)</span>
			</view>
			<view class="level">
				<view class="mt20 ml10">
					<up-upload :fileList="fileList.ShoeCover" @afterRead="afterRead" @delete="deletePic"
						name="ShoeCover" multiple :maxCount="2" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
				</view>
			</view>
		</view>
		<view class="top mt24 box-size" :style="{borderRadius:'16rpx'}">
			<view class="form-title">
				宠物状态记录
			</view>
			<view v-for="(pet, index) in petList" :key="index">
				<view class="mt32 ml10">
					<span :style="{fontSize:'30rpx',fontWeight:'400'}">{{ pet.title }}照片</span>
					<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(至少2张)</span>
				</view>
				<view class="level">
					<view class="mt20 ml10 mr20">
						<up-upload :fileList="fileList['pet' + index]" @afterRead="afterRead" @delete="deletePic"
							:name="'pet' + index" multiple :maxCount="2" width="131rpx" height="131rpx" :disabled="isRead">

							<image src="/static/images/ydd/add_photo.png" mode=""
								:style="{width:'131rpx',height:'131rpx'}">
							</image>

						</up-upload>
					</view>
				</view>
			</view>
		</view>
		<view class="top mt24 box-size" :style="{borderRadius:'16rpx'}">
			<view class="form-title">
				基础服务记录
			</view>
			<view class="mt32 ml10" :style="{fontSize:'30rpx',fontWeight:'400'}">粮碗前后对比 </view>
			<view class="level">
				<view class="mt20 ml10">
					<up-upload :fileList="fileList.foodA" @afterRead="afterRead" @delete="deletePic" name="foodA"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">前</view>
				</view>
				<view class="mt20 ml10 ml28">
					<up-upload :fileList="fileList.foodB" @afterRead="afterRead" @delete="deletePic" name="foodB"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">后</view>
				</view>
			</view>
			<view class="mt32 ml10" :style="{fontSize:'30rpx',fontWeight:'400'}">水碗前后对比 </view>
			<view class="level">
				<view class="mt20 ml10">
					<up-upload :fileList="fileList.waterA" @afterRead="afterRead" @delete="deletePic" name="waterA"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">前</view>
				</view>
				<view class="mt20 ml10 ml28">
					<up-upload :fileList="fileList.waterB" @afterRead="afterRead" @delete="deletePic" name="waterB"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">后</view>
				</view>
			</view>
			<view class="mt32 ml10" :style="{fontSize:'30rpx',fontWeight:'400'}">猫砂盆、尿垫前后对比 </view>
			<view class="level">
				<view class="mt20 ml10">
					<up-upload :fileList="fileList.urinalA" @afterRead="afterRead" @delete="deletePic" name="urinalA"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">前</view>
				</view>
				<view class="mt20 ml10 ml28">
					<up-upload :fileList="fileList.urinalB" @afterRead="afterRead" @delete="deletePic" name="urinalB"
						multiple :maxCount="1" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
					<view class="jus-center level" :style="{color:'#999999',fontSize:'22rpx',width:'131rpx'}">后</view>
				</view>
			</view>
		</view>
		<view class="top mt24 box-size" 
		v-if="projectList.length > 0"
		:style="{borderRadius:'16rpx'}">
			<view class="form-title">
				定制服务记录
			</view>
			
			<view v-for="(product, pindex) in projectList"
			:key="pindex">
				<view class="mt32 ml10">
					<span :style="{fontSize:'30rpx',fontWeight:'400'}">{{ product.title }}</span>
					<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(2-3张)</span>
				</view>
				<view class="level">
					<view class="mt20 ml10 mr20">
						<up-upload :fileList="fileList['project' + pindex]" @afterRead="afterRead" @delete="deletePic" 
						:name="'project' + pindex"
							multiple :maxCount="3" width="131rpx" height="131rpx" :disabled="isRead">
				
							<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
							</image>
				
						</up-upload>
					</view>
				</view>
			</view>
			
			<!-- <view class="mt32 ml10">
				<span :style="{fontSize:'30rpx',fontWeight:'400'}">遛狗</span>
				<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(2-3张)</span>
			</view>
			<view class="level">
				<view class="mt20 ml10 mr20">
					<up-upload :fileList="fileList.testa" @afterRead="afterRead" @delete="deletePic" name="testa"
						multiple :maxCount="3" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
				</view>
			</view> -->
			<!-- <view class="mt32 ml10">
				<span :style="{fontSize:'30rpx',fontWeight:'400'}">陪玩</span>
				<span :style="{fontSize:'26rpx',color:'#C7C7C7'}">(2-3张)</span>
			</view>
			<view class="level">
				<view class="mt20 ml10 mr20">
					<up-upload :fileList="fileList.testb" @afterRead="afterRead" @delete="deletePic" name="testb"
						multiple :maxCount="3" width="131rpx" height="131rpx" :disabled="isRead">

						<image src="/static/images/ydd/add_photo.png" mode="" :style="{width:'131rpx',height:'131rpx'}">
						</image>

					</up-upload>
				</view>
			</view> -->
		</view>
		<view class="top mt24 box-size" :style="{borderRadius:'16rpx'}">
			<view class="form-title">
				其他补充信息(必填)
			</view>
			<view class="mt32 ml10" :style="{color:'#999999',fontSize:'30rpx'}">
				可记录一下今日趣事、宠物状况、提醒事项等，最少30个字
			</view>
			<view class="mt24">
				<textarea cols="30" rows="10" 
				placeholder="请输入内容"
				v-model="form.notes"
				:style="{color:'#999999',fontSize:'30rpx',backgroundColor:'#F5F5F5',borderRadius:'16rpx',width:'681rpx',height:'180rpx'}"
				class="pd20 box-size" :disabled="isRead"></textarea>
			</view>
		</view>
		<view class="buttom mt60 box-size" 
		v-if="!isRead"
		style="display: flex;gap: 20rpx;"
		>
			<view class="buttom-item buttom-item-2 level size-30" 
			@click="saveDraft(false)"
			:style="{borderRadius:'41rpx',color:'#ff842c'}">
				保存草稿
			</view>
			
			<view class="buttom-item level size-30" 
			@click="submit"
			:style="{borderRadius:'41rpx',color:'#fff'}">
				确定提交
			</view>
			
		</view>
		<!-- 客服组件 -->
		<CustomerService />
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref,
	} from "vue";
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ossUpload
	} from '@/utils/oss-upload/oss/index.js'
	
	import {
		appletOrderDateFrequencyById,
		appletOrderDateFrequencyCheck,
	} from "@/api/order/frequency.js"

	onLoad((options) => {
		checkId.value = options.id || null;
		GetByOrderId()
	});
	
	const checkId = ref(0)
	const orderId = ref(0)
	const itemOrderID = ref(0)
	const serviceId = ref(0)
	const isRead = ref(false)
	const content = ref('')
	

	const fileList = reactive({
		// glove: [],//手套
		// ShoeCover: [],//鞋套
		// food: [],//粮碗
		// water: [],//水碗
		// urinal: [],//猫砂盆、尿盆
	})

	const form = ref({})

	const petList = ref([
		// {
		// 	title: '小汪'
		// },
		// {
		// 	title: '大黄'
		// },
	])
	//附加项目
	const projectList = ref([
		// {
		// 	title: '小汪'
		// },
		// {
		// 	title: '大黄'
		// },
	])

	

	// 删除图片
	const deletePic = (event) => {
		if (fileList[event.name]) {
			fileList[event.name].splice(event.index, 1);
		}
	};

	// 新增图片
	const afterRead = (event) => {
		if (!fileList[event.name]) {
			fileList[event.name] = []
		}
		event.file.forEach(n => {
			ossUpload(n.url)
				.then(url => {
					console.log(url);
					fileList[event.name].push({
						url
					})
				})
		})
	};

	function submit() {
		// 参数效验
		if (!fileList.glove || fileList.glove.length == 0) {
			return msg('请上传鞋套照片')
		}
		if (!fileList.ShoeCover || fileList.ShoeCover.length == 0) {
			return msg('请上传鞋套照片')
		}

		for (let i = 0; i < petList.value.length; i++) {
			if (!fileList['pet' + i] || fileList['pet' + i].length < 2) {
				return msg(`请上传${petList.value[i].title}照片`)
			}
		}

		if (!fileList.foodA || fileList.foodA.length < 1 ||
			!fileList.foodB || fileList.foodB.length < 1) {
			return msg('请上传粮碗前后照片')
		}

		if (!fileList.waterA || fileList.waterA.length < 1 ||
			!fileList.waterB || fileList.waterB.length < 1) {
			return msg('请上传水碗前后照片')
		}

		if (!fileList.urinalA || fileList.urinalA.length < 1 ||
			!fileList.urinalB || fileList.urinalB.length < 1) {
			return msg('请上传猫砂盆、尿盆照片')
		}
		
		for (let i = 0; i < projectList.value.length; i++) {
			if (!fileList['project' + i] || fileList['project' + i].length < 2) {
				return msg(`请上传${projectList.value[i].title}照片`)
			}
		}
		
		if(!form.value.notes){
			return msg('请填写补充信息')
		}
		
		if(form.value.notes.length < 30){
			return msg('补充信息不少于30字')
		}

		saveDraft(true)
	}
	
	function GetByOrderId(){
		appletOrderDateFrequencyById(checkId.value)
		.then(res => {
			const data = res.data.check;
			const frequency = res.data.frequency;
			isRead.value = frequency.status == 2
			if(res.code == 200 && data) {
				form.value = data
				// 回显手套照片
				if(data.glovePhoto) {
					fileList.glove = data.glovePhoto.split(',').map(url => ({ url }));
				}
				// 回显鞋套照片
				if(data.shoeCoverPhoto) {
					fileList.ShoeCover = data.shoeCoverPhoto.split(',').map(url => ({ url }));
				}
				// 回显宠物照片
				if(data.petPhoto) {
					const pets = JSON.parse(data.petPhoto);
                    petList.value = pets;
					pets.forEach((pet, index) => {
						if(pet.fileList) {
							fileList['pet' + index] = pet.fileList.split(',').map(url => ({ url }));
						}
					});
				}
				// 回显项目照片
				if(data.workDogImage) {
					const pList = JSON.parse(data.workDogImage);
				    projectList.value = pList;
					pList.forEach((pet, index) => {
						if(pet.fileList) {
							fileList['project' + index] = pet.fileList.split(',').map(url => ({ url }));
						}
					});
				}
				// 回显粮碗照片
				if(data.grainBowlFront) fileList.foodA = data.grainBowlFront.split(',').map(url => ({ url }));
				if(data.grainBowlAfter) fileList.foodB = data.grainBowlAfter.split(',').map(url => ({ url }));
				// 回显水碗照片
				if(data.waterBowlFront) fileList.waterA = data.waterBowlFront.split(',').map(url => ({ url }));
				if(data.waterBowlAfter) fileList.waterB = data.waterBowlAfter.split(',').map(url => ({ url }));
				// 回显猫砂盆/尿垫照片
				if(data.basinFront) fileList.urinalA = data.basinFront.split(',').map(url => ({ url }));
				if(data.basinAfter) fileList.urinalB = data.basinAfter.split(',').map(url => ({ url }));
				// 回显定制服务照片
				// if(data.workDogImage) fileList.testa = data.workDogImage.split(',').map(url => ({ url }));
				// if(data.workPalyImage) fileList.testb = data.workPalyImage.split(',').map(url => ({ url }));
				
			}else{
                // getOrderPetByIdFN()
				
				let projectNameList = []
				
				frequency.pets.forEach((n, i) => {
					fileList['pet' + i] = []
					
					n.orderItemList.forEach((item, inde) => {
						fileList['project' + inde] = []
					})
				})
				frequency.pets.forEach((n, i) => {
					petList.value.push({
						title : n.name,
				        id : n.id,
					})
					n.orderItemList.forEach((item, inde) => {
						
						if(item.isMainProduct == 1){
							return
						}
						
						if(!projectNameList.includes(item.productName)){
							projectNameList.push(item.productName)
							projectList.value.push({
								title : item.productName,
								ids : [item.id]
							})
						}else{
							projectList.value[projectNameList.indexOf(item.productName)].ids.push(item.id)
						}
					})
				})
				
            }
		})
	}
	
	function getOrderPetByIdFN(){
		getOrderPetById(orderId.value)
		.then(res => {
			if(res.code == 200){
				res.data.forEach((n, i) => {
					fileList['pet' + i] = []
				})
				res.data.forEach((n, i) => {
					petList.value.push({
						title : n.name,
                        id : n.id,
					})
				})
			}
		})
	}
	
	
	function saveDraft(flag) {
	    // 将所有图片数组转换为逗号分隔的字符串
	    const params = {
	        // orderId: orderId.value,
			// itemOrderId : itemOrderID.value,
            itemDateId : checkId.value,
	        glovePhoto: fileList.glove?.map(item => item.url).join(',') || '',
	        shoeCoverPhoto: fileList.ShoeCover?.map(item => item.url).join(',') || '',
	        // 合并所有宠物照片
	        petPhoto: JSON.stringify(
                petList.value.map((pet, index) => {
                    return {
                        id : pet.id,
                        title : pet.title,
                        fileList: fileList['pet' + index]?.map(item => item.url).join(',') || ''
                    };
                })
            ),
	        workDogImage: JSON.stringify(
                projectList.value.map((pet, index) => {
                    return {
                        id : pet.id,
                        title : pet.title,
                        fileList: fileList['project' + index]?.map(item => item.url).join(',') || ''
                    };
                })
            ),
	        // 粮碗照片
	        grainBowlFront: fileList.foodA?.map(item => item.url).join(',') || '',
	        grainBowlAfter: fileList.foodB?.map(item => item.url).join(',') || '',
	        // 水碗照片
	        waterBowlFront: fileList.waterA?.map(item => item.url).join(',') || '',
	        waterBowlAfter: fileList.waterB?.map(item => item.url).join(',') || '',
	        // 猫砂盆/尿垫照片
	        basinFront: fileList.urinalA?.map(item => item.url).join(',') || '',
	        basinAfter: fileList.urinalB?.map(item => item.url).join(',') || '',
	        // 定制服务照片
	        // workDogImage: fileList.testa?.map(item => item.url).join(',') || '',
	        // workPalyImage: fileList.testb?.map(item => item.url).join(',') || '',
	        // 备注信息
	        notes: form.value.notes || '',
			submitFlag : 1,//草稿
	    }

        if(form.value.id) {
			params.id = form.value.id
		}

        if(flag) {
            params.submitFlag = 2
        }
	
	    appletOrderDateFrequencyCheck(params)
	    .then(res => {
	        if(res.code === 200) {
	            uni.showToast({
	                title: '提交成功',
	                icon: 'success'
	            })
	            // 如果是确认提交（非草稿），则返回上一页
                setTimeout(() => {
                    uni.navigateBack()
                }, 1500)
	        } else {
	            uni.showToast({
	                title: res.msg || '提交失败',
	                icon: 'none'
	            })
	        }
	    })
	    .catch(err => {
	        uni.showToast({
	            title: '提交失败',
	            icon: 'none'
	        })
	    })
	}

	function msg(content) {
		uni.showToast({
			title: content,
			icon: 'none'
		})
	}
	
</script>

<style scoped lang="scss">
	@import"index.scss"
</style>