<template>
	<view class="page4-warp">
		<u-navbar class="u-navbar-box" title="结束护理" placeholder bgColor="transparent" autoBack />
		<view class="page4-form">
			<up-form labelPosition="top" :model="formData" :rules="formRule" ref="formRef">
				<up-form-item label="出院时间" labelWidth="auto" labelPosition="left" required prop="leaveTime"
					@click="showTime = true">
					<up-input v-model="formData.leaveTime" disabled disabledColor="#ffffff" border="none"
						placeholder="请选择出院时间" />
				</up-form-item>
				<up-form-item label="出院证明" labelWidth="auto" prop="leaveImg" required>
					<view class="flex-row justify-between align-center" style="width: 100%;">
						<up-upload :fileList="fileList" :sizeType="['compressed']" :maxCount="1" @afterRead="afterRead"
							@delete="deletePic" />
					</view>
				</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">确定</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,
		endCareRequest,
		uploadImg
	} from '@/common/config/application-api.js'
	import {
		uploadImgUrl
	} from '@/common/config/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({
		leaveImg: '',
		leaveTime: ''
	})
	const formRule = reactive({
		leaveTime: [{
			required: true,
			message: '请选择出院时间',
			trigger: ['blur', 'change']
		}],
		leaveImg: [{
			required: true,
			message: '请上传指定出院证明图片',
			trigger: ['change', 'blur'],
		}]
	})

	onLoad((options) => {
		console.log('options', options);
		applyId.value = options.id;
	})


	//点击打卡
	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) {
				submitEnd();
				// formData.imgPaths = formData.img.join(',');
				// formData.imgNum = formData.img.length;
				// delete formData.img;
				// if (submitType.value === '0') {
				// 	addClocks();
				// } else {
				// 	submitDie();
				// }
			}
		})
	}

	const submitEnd = () => {
		let params = {};
		console.log('formData', formData);
		endCareRequest({
				applyId: applyId.value,
				leaveTime: formData.leaveTime + ' 00:00:00',
				leaveImg: formData.leaveImg,
				dealStatus: 'wait_complete',
				payStatus: 'dis_pay'
			})
			.then(res => {
				console.log('出院res', res);
				uni.showToast({
					title: '提交成功',
					icon: 'none'
				})
				uni.$emit('renderApplyList')
				uni.navigateBack({
					delta: 2
				});
			})
			.catch(err => {
				uni.showToast({
					title: '提交失败',
					icon: 'none'
				})
				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.leaveTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
		showTime.value = false;
	}

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

	//新增图片
	const afterRead = (event) => {
		console.log(event);
		fileList.value = [{
			...event.file,
			status: 'uploading',
			message: '上传中',
		}]
		uploadImgUrl({
				filePath: event.file.url,
				name: 'file',
				custom: {
					catch: true
				}
			})
			.then(res => {
				console.log('res', res);
				uni.$u.toast('上传成功');
				// getUserInfo();
				fileList.value[0].status = 'success';
				fileList.value[0].message = '';
				fileList.value[0].url = uni.$u.http.config.baseURL + '/prod-api/' + res.fileName;
				fileList.value[0].name = res.fileName;
				formData.leaveImg = res.fileName;
			})
			.catch(err => {
				uni.hideLoading()
				console.log('上传Err', err);
				fileList[0].value.status = 'failed';
				fileList[0].value.message = '上传失败';
			})
	}

	//获取打卡图片数量
	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>