<template>
	<view class="page4-warp">
		<u-navbar class="u-navbar-box" :title="computePageTitle" placeholder bgColor="transparent" autoBack />
		<view class="page4-form">
			<up-form labelPosition="top" :model="formData" :rules="formRule" ref="formRef">
				<up-form-item v-if="submitType === '0'" label="护理时间" labelWidth="auto" labelPosition="left" required
					prop="nursingTime">
					<up-input v-model="formData.nursingTime" disabled disabledColor="#ffffff" border="none"
						placeholder="请选择打卡时间" />
				</up-form-item>
				<up-form-item v-else label="死亡时间" labelWidth="auto" labelPosition="left" required prop="dieTime"
					@click="showTime = true">
					<up-input v-model="formData.dieTime" disabled disabledColor="#ffffff" border="none"
						placeholder="请选择死亡时间" />
				</up-form-item>
				<up-form-item :label="submitType==='0'?`护理打卡(最少上传${imgNum}张图片)`:'死亡证明'" labelWidth="auto" prop="img"
					required>
					<view class="flex-row justify-between align-center" style="width: 100%;">
						<up-upload :fileList="fileList" multiple :sizeType="['compressed']" :capture="['camera']"
							:maxCount="submitType==='0'?imgNum:1" @afterRead="afterRead" @delete="deletePic" />
					</view>
				</up-form-item>
				<up-form-item v-if="submitType==='0'" label="备注" labelWidth="auto">
					<up-textarea v-model="formData.remark" placeholder="请输入您的打卡备注" count />
				</up-form-item>
			</up-form>
		</view>

		<u-datetime-picker ref="datetimePicker" :show="showTime" v-model="timeValue" mode="date" closeOnClickOverlay
			@cancel="showTime = false" @close="showTime = false" @confirm="timeConfirm" :formatter="formatter" />
		<view class="btn-box">
			<view class="flex-row ">
				<up-button class="up-button" type="primary" @tap="checkTap">{{submitType==='0'?'确定打卡':'确定'}}</up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';
	import {
		useStore
	} from 'vuex';
	import {
		onLoad,
		onUnload,
		onReady
	} from "@dcloudio/uni-app"
	import {
		getImgNumber,
		addCareClocks,
		addDieRecord,
		uploadImgUrl,
		uploadImg
	} from '@/common/config/application-api.js'

	import dayjs from 'dayjs';

	const applyId = ref('');
	const submitType = ref('');


	const store = useStore();
	const props = defineProps({
		item: {
			type: Object,
			default () {
				return {}
			}
		}
	})

	const showTime = ref(false);
	const timeValue = ref(new Date().getTime());
	const formRef = ref(null);
	const fileList = ref([]);
	const formData = reactive({
		img: [],
		remark: '', //意见
		nursingTime: '', //护理时间
	})
	const formRule = reactive({
		nursingTime: [{
			required: true,
			message: '请选择护理时间',
			trigger: ['blur', 'change']
		}],
		dieTime: [{
			required: true,
			message: '请选择死亡时间',
			trigger: ['blur', 'change']
		}],
		img: [{
			validator: (rule, value, callback) => {
				return value.length >= imgNum.value;
			},
			message: '请上传指定数量的图片',
			trigger: ['change', 'blur'],
		}]
	})

	onLoad((options) => {
		console.log('options', options);
		applyId.value = options.id;
		submitType.value = options.type;
		// 获取需上传的图片数量
		getNumber();
		// 默认打卡时间，不再选择
		formData.nursingTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
	})


	const computePageTitle = computed(() => {
		switch (submitType.value) {
			case '0':
				return '护理打卡';
			case '1':
				return '死亡记录';
			case '2':
				return '结束护理';
			default:
				break;
		}
	})

	//点击打卡
	function checkTap() {
		// console.log('1=>', fileList.value);
		formData.img = [];
		fileList.value.map(file => {
			formData.img.push(file.url.replace(new RegExp(uni.$u.http.config.baseURL, 'g'), ''));
		});
		formRef.value.validate().then(res => {
			if (res) {
				formData.imgPaths = formData.img.join(',');
				formData.imgNum = formData.img.length;
				delete formData.img;
				if (submitType.value === '0') {
					addClocks();
				} else {
					submitDie();
				}
			}
		})
	}

	const submitDie = () => {
		let params = {};
		console.log('formData', formData);
		addDieRecord({
				applyId: applyId.value,
				dieTime: formData.dieTime + ' 00:00:00',
				imgPaths: formData.imgPaths
			})
			.then(res => {
				console.log('死亡记录res', res);
				uni.navigateBack({
					delta: 2
				});
			})
			.catch(err => {
				console.log('死亡记录err', err);
			})
	}

	//点击打卡 --新增打卡记录
	function addClocks() {
		let reqClockParams = {
			applyId: applyId.value,
			nursingRecordId: applyId.value,
			...formData
		}
		console.log('reqClockParams', reqClockParams);
		addCareClocks(reqClockParams)
			.then(res => {
				console.log('打卡res', res);
				uni.$u.toast('打卡成功!');
				uni.$emit('reloadLine');
				uni.navigateBack();
			})
			.catch(error => {
				console.log('打卡error', error);
				uni.$u.toast('打卡失败!')
			});
	}

	const datetimePicker = ref();
	onReady(() => {
		datetimePicker.value.setFormatter(formatter);
	})

	function formatter(type, value) {
		if (type === 'year') {
			return `${value}年`
		}
		if (type === 'month') {
			return `${value}月`
		}
		if (type === 'day') {
			return `${value}日`
		}
		if (type === 'hour') {
			return `${value}时`
		}
		if (type === 'minute') {
			return `${value}分`
		}
		return value
	}

	function timeConfirm(e) {
		console.log('timeConfirm=>', e);
		timeValue.value = e.value;
		formData.dieTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
		showTime.value = false;
	}

	//删除图片
	function deletePic(event) {
		fileList.value.splice(event.index, 1);
	}

	//新增图片
	async function afterRead(event) {
		console.log('event', event);
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.forEach((item) => {
			let {
				url,
				size
			} = item;
			console.log('url: ', url);
			if (url.toLowerCase().endsWith('png') || url.toLowerCase().endsWith('jpg') || url
				.toLowerCase().endsWith('jpeg') || url
				.toLowerCase().endsWith('gif') || url
				.toLowerCase().endsWith('bmp')) {
				if (item.size < 1024 * 1024 * 10) {
					fileList.value.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				} else {
					uni.showToast({
						title: '请选择10M以内的图片',
						icon: 'none'
					})
				}
			} else {
				uni.showToast({
					title: '请上传JPG,PNG,JPEG,GIF,BMP格式的图片',
					icon: 'none'
				})
			}
		})
		for (let i = 0; i < lists.length; i++) {
			// 如果大于10M
			if (lists[i].size > 1024 * 1024 * 10) {
				continue;
			}
			try {
				console.log('applyId', applyId.value);
				const result = await uploadImg({
					filePath: lists[i].url,
					name: 'file',
					formData: {
						applyId: applyId.value
					},
					custom: {
						catch: true
					}
				})
				// console.log('result: ', result);
				let item = fileList.value[fileListLen]
				fileList.value.splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: uni.$u.http.config.baseURL + result.imgUrl,
					// fileName: result.fileName
				}))
				// console.log(fileList);
				fileListLen++
			} catch (e) {
				// uni.$u.toast(JSON.stringify(e))
				//TODO handle the exception
				console.log('e: ', e);
				let item = fileList.value[fileListLen]
				fileList.value.splice(fileListLen, 1, Object.assign(item, {
					status: 'failed',
					message: '上传失败',
					url: item.url
				}))
				fileListLen++
			}
		}
	}

	//获取打卡图片数量
	const imgNum = ref(0);

	function getNumber() {
		if (submitType.value === '1') {
			return imgNum.value = 1
		}
		getImgNumber({
			params: {
				key: 'need_img_num'
			}
		}).then(res => {
			imgNum.value = res.number;
		})
	}
</script>

<style lang="scss" scoped>
	:deep(.u-navbar__content__title) {
		font-weight: bold;
		font-size: 36rpx;
		color: #222222;
	}

	.u-navbar-box {
		background: radial-gradient(circle at left, #FFE5E4 0%, #EEF2F5 40%, #DBEEFB 100%);
	}

	.page4-form {
		padding: 30rpx;
		border-radius: 10rpx;
		background-color: #fff;
	}

	.btn-box {
		padding: 20rpx 36rpx;
		background-color: #fff;
		position: fixed;
		bottom: 10rpx;
		left: 0;
		width: 690rpx;
	}
</style>