<template>
	<view class="page">
		<view class="" style="background-color: #FFBF60;width: 100%;height: 20rpx;">
			
		</view>
		
		<!-- style="margin: 20rpx;border-radius: 20rpx;" -->
		
		<view class="tips color-ffb size-22">
			注意:这段内容将会在您的喂养员个人主页，做为"服务案例”展示，并开放给其他铲屎官查看，请认真编辑哟！
		</view>
		<view class="li bg-fff">
			<view class="title">
				服务类型
				<text class="size-22 color-999 ml10">可多选</text>
			</view>
			<up-checkbox-group v-model="form.serviceType">
				<view class="flex-between mt40" style="width: 100%;">
					<up-checkbox shape="circle" class="mr10" :customStyle="{marginBottom: '8px'}"
						v-for="item in petTypeOptions" :key="`serviceType-${item.id}`" :label="item.title" :name="item.id" activeColor="#FFBF60">
					</up-checkbox>
				</view>
			</up-checkbox-group>
		</view>

		<view class="li bg-fff">
			<view class="title">
				服务时间
			</view>
			<view class="flex-between mt16">
				<text class="size-28 color-999">选择服务时间</text>
				<view class="flex-rowr" @click="openTimePicker">
					<view class="t-r size-28 mr10" :class="[form.serviceTime ? 'highlight' : '']">{{ serveTimeDesc }}</view>
					<up-icon name="arrow-right" color="#999999" size="27rpx"></up-icon>
				</view>
			</view>
			<up-datetime-picker
				v-model="form.serviceTime"
				:show="showTimePicker"
				mode="date"
				:closeOnClickOverlay="true"
				@close="closeTimePicker"
				@cancel="closeTimePicker"
				@confirm="closeTimePicker"
			></up-datetime-picker>
		</view>

		<view class="li bg-fff">
			<view class="title">
				服务地点
			</view>
			<view class="flex-between mt16">
				<text class="size-28 color-999">选择服务地点</text>
				<view class="flex-rowr" @click="selectAddr">
					<view class="t-r size-28 mr10" :class="[form.serviceSpot ? 'highlight' : '']">{{ form.serviceSpot || '请选择' }}</view>
					<up-icon name="arrow-right" color="#999999" size="27rpx"></up-icon>
				</view>
			</view>
		</view>

		<view class="li bg-fff">
			<view class="title">
				文字记录
			</view>
			<textarea class="text"
				v-model="form.text"
				placeholder="请输入文字记录，可简单描述服务过程中发生的趣事，或夸奖一下服务宠物吧，10-100字"
			></textarea>
		</view>

		<view class="li bg-fff">
			<view class="title">
				图片记录
			</view>
			<view class="size-28 color-999 mt16">
				请选择具有代表性的2-3张服务宠物图片，服务过程图片或视频截图，让铲屎官感受到您对毛孩子的爱吧
			</view>
			<view style="margin-top: 34rpx;">
				<up-upload
					:fileList="form.fileList"
					@afterRead="afterRead"
					@delete="deletePic"
					multiple
				>
					<image src="../static/list/icon-upload.png" style="width: 144rpx;height: 144rpx;"></image>
				</up-upload>
			</view>
		</view>

		<view class="footer-btn">
			<view class="btn" @click="onSave">
				立即上传
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, computed } from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { useStore } from 'vuex'
	import dayjs from 'dayjs'
	import { ossUpload } from '@/utils/oss-upload/oss/index.js'
	import { insertServiceLog, udpateServiceLog } from '@/api/serviceLog'
	import { serviceLogList, deleteServiceLog } from '@/api/serviceLog'

	const store = useStore()

	const id = ref(0)

	const form = reactive({
		serviceType: [],
		serviceTime: null,
		serviceSpot: null,
		latitude: null,
		longitude: null,
		text: null,
		fileList: [],
	})

	const fetchServiceLogDetail = async () => {
		try {

			const data = (await serviceLogList({ id: id.value }))?.[0]
			// const data = uni.getStorageSync('serviceLogData')

			const {
				serviceType,
				serviceTime,
				serviceSpot,
				text,
				image,
			} = data

			form.serviceType = serviceType?.split?.(',').map(item => parseInt(item)) || []
			form.serviceTime = serviceTime
			form.serviceSpot = serviceSpot
			form.text = text
			form.fileList = image?.split?.(',').map(url => ({ url })) || []

		} catch (err) {
			console.error(err);
		}
	}
	
	const petTypeOptions = computed(() => {
		return store.getters.petTypeOptions
	})

	const showTimePicker = ref(false)
	const openTimePicker = () => {
		showTimePicker.value = true
	}
	const closeTimePicker = () => {
		showTimePicker.value = false
	}
	const serveTimeDesc = computed(() => {
		if (!form.serviceTime) {
			return '请选择'
		}

		return dayjs(form.serviceTime).format('YYYY/MM/DD')
	})

	const setAddress = (res) => {
		//经纬度信息
		form.latitude = res.latitude
		form.longitude = res.longitude

		if (!res.address && res.name) { //用户直接选择城市的逻辑
			return form.serviceSpot = res.name
		}
		if (res.address || res.name) {
			return form.serviceSpot = res.address + res.name
		}
		form.serviceSpot = '' //用户啥都没选就点击勾选
	}

	const selectAddr = () => {
		uni.chooseLocation({
			success: function(res) {
				setAddress(res)
			}
		})
	}
	
	const afterRead = (event) => {
		event.file.forEach(n => {
			ossUpload(n.url)
				.then(url => {
					form.fileList.push({
						url
					})
				})
		})
	};
	const deletePic = (event) => {
		form.fileList.splice(event.index, 1);
	};

	const onSave = async () => {
		try {
			const {
				serviceType,
				serviceTime,
				serviceSpot,
				text,
				fileList,
			} = form

			// 表单验证
			if (!serviceType || serviceType.length === 0) {
				return uni.showToast({
					title: '请选择服务类型',
					icon: 'none'
				})
			}

			if (!serviceTime) {
				return uni.showToast({
					title: '请选择服务时间',
					icon: 'none'
				})
			}

			if (!serviceSpot) {
				return uni.showToast({
					title: '请选择服务地点',
					icon: 'none'
				})
			}

			if (!text) {
				return uni.showToast({
					title: '请输入服务描述',
					icon: 'none'
				})
			}

			if (!fileList || fileList.length === 0) {
				return uni.showToast({
					title: '请上传服务图片',
					icon: 'none'
				})
			}

			const data = {
				userId: store.getters.userInfo.userId,
				serviceType: serviceType.join(','),
				serviceTime: dayjs(serviceTime).format('YYYY-MM-DD HH:mm:ss'),
				serviceSpot,
				text,
				image: fileList.map(item => item.url).join(',')
			}

			if (id.value) {
				data.id = id.value
				await udpateServiceLog(data)
			} else {
				await insertServiceLog(data)
			}
			
			uni.showToast({
				title: '上传成功!',
				icon: "none"
			})

			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
		} catch (err) {
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none'
			})
		}
	}

	onLoad((option) => {
		store.dispatch('fetchPetTypeOptions')

		id.value = option.id
		

		if (id.value) {
			fetchServiceLogDetail()
		}
	})
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		padding-bottom: 144rpx;
	}

	.text {
		padding: 16rpx;
		background-color: #F3F3F3;
		font-size: 28rpx;
		margin-top: 16rpx;
		border-radius: 20rpx;
	}

	.tips {
		padding: 8rpx 16rpx;
		background-color: #FFFAF2;
		color: #FFBF60;
	}

	.li {
		margin: 20rpx;
		border-radius: 20rpx;
		padding: 24rpx 36rpx;
	}

	.title {
		font-size: 30rpx;
		font-weight: 700;
		display: flex;
		align-items: center;

		&:before {
			display: block;
			content: "";
			width: 10rpx;
			border-radius: 10rpx;
			height: 34rpx;
			background-color: #FFBF60;
			margin-right: 15rpx;
		}
	}

	.highlight {
		color: #FFBF60;
	}

	.footer-btn {
		z-index: 4;
	}
</style>