<template>
	<view class="container">
		<up-navbar class="u-navbar-box" title="护理申请" auto-back placeholder bgColor="transparent"
			:title-style="{fontWeight:'bold'}">
		</up-navbar>
		<scroll-view scroll-y class="flex-column flex-1" style="overflow: hidden;background-color: #F6F8FD;">
			<view class="p-32 flex-column" style="width: 686rpx;">
				<view class="w-100p flex-column">
					<view class="flex-row align-center">
						<view style="width: 6rpx;height: 32rpx;background-color: #39A1FF;border-radius: 4rpx;"></view>
						<text class="font-xmd text-black3" style="margin-left: 14rpx;">申请人信息</text>
					</view>
					<view class="flex-column py-4 px-24 mt-24"
						style="background: linear-gradient( 180deg, #E8F4FF 0%, #FFFFFF 100%);border-radius: 16rpx;">
						<view class="flex-row align-center justify-between">
							<text class="font text-black2">人员来源</text>
							<text class="font text-black2" @click="chooseFrom">{{computeFromDesc}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">{{computeStreetCat}}</text>
							<text class="font text-black2" style="max-width: 400rpx;"
								@click="showPicker = true">{{chooseStreet.label}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">申请人</text>
							<text class="font text-black2" @click="goChoosePeople">{{formData.name}}</text>
						</view>
						<view v-if="chooseFromIndex === 1" class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">所在街道</text>
							<text class="font text-black2" style="max-width: 400rpx;">{{streetName || '未知'}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">是否残疾</text>
							<text class="font text-black2">{{formData.disability || '请先选择申请人'}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">护理需求</text>
							<view style="width: 440rpx;">
								<up-input placeholder="请输入护理需求" border="none" v-model.trim="formData.demand" clearable
									:maxlength="50" inputAlign="right"></up-input>
							</view>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">首选护理人员性别</text>
							<text class="font text-black2" @click="chooseGender">{{formData.sex === '1'?'女':'男'}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">所在医院</text>
							<text class="font text-black2" @click="goChooseHospital">{{formData.hospital}}</text>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">详细地址</text>
							<view style="width: 440rpx;">
								<u-input placeholder="请输入具体科室/楼层/房间/床号" border="none" v-model.trim="formData.address"
									clearable :maxlength="50" inputAlign="right"></u-input>
							</view>
						</view>
						<!-- <view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">出院时间</text>
							<text class="font text-black2"
								@click="showTimePicker = true">{{formData.leaveTime || '请选择出院时间'}}</text>
						</view> -->
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">备注</text>
							<view style="width: 440rpx;">
								<u-input placeholder="请输入备注" border="none" v-model.trim="formData.remark" clearable
									:maxlength="100" inputAlign="right"></u-input>
							</view>
						</view>
						<view class="flex-row align-center justify-between mt-4">
							<text class="font text-black2">护理申请书</text>
							<up-upload :fileList="fileList" :maxSize="1024 * 1024 * 1024" @afterRead="afterRead"
								@delete="deletePic" name="1" :maxCount="1" style="flex: 0;"></up-upload>
						</view>
					</view>
				</view>

				<view class="w-100p flex-row align-center justify-center mt-4"
					style="background-color: #39A1FF;height: 88rpx;border-radius: 50rpx;" @click="handleSubmit">
					<text class="font-md text-white">确认提交</text>
				</view>
			</view>
		</scroll-view>

		<up-picker v-model:show="showPicker" :defaultIndex="defaultIndex" closeOnClickOverlay :columns="streetList"
			keyName="label" valueName="id" @confirm="handlePickerConfirm"></up-picker>

		<!-- <view v-show="showTimePicker">
			<up-datetime-picker v-model:show="showTimePicker" mode="datetime" title="出院时间" :minDate="minDate"
				@cancel="showTimePicker = false" @confirm="handleTimeConfirm"></up-datetime-picker>
		</view> -->

	</view>
</template>

<script>
	import dayjs from 'dayjs'
	import {
		applyUrl,
		applyModifyUrl,
		getStreetListUrl,
		uploadAvatarUrl,
		uploadImgUrl
	} from '@/common/config/api.js';
	import {
		getCareInfo
	} from '@/common/config/application-api.js'
	import {
		route
	} from '@/uni_modules/uview-plus';
	export default {
		data() {
			return {
				fileList: [],
				minDate: dayjs().valueOf(),
				showTimePicker: false,
				showPicker: false,
				formId: '',
				fromList: [{
					label: '散居',
					id: 1,
				}, {
					label: '养老院',
					id: 2,
				}, {
					label: '失能中心',
					id: 3,
				}],
				defaultIndex: [1],
				chooseStreet: {
					id: -1,
					label: '请选择'
				},
				streetList: [
					[]
				],
				chooseFromIndex: 0,
				formData: {
					personId: '',
					name: '请选择申请人',
					disability: '',
					demand: '',
					sex: '0',
					hospital: '请选择所在医院',
					address: '',
					// dayCount: '',
					// leaveTime: '',
					remark: ''
				}
			}
		},
		onLoad(options) {

			if (options.id) {
				this.formId = options.id;
				this.getApplyInfo();
			} else {
				this.formId = '';
			}

			this.getStreetList();

			// 监听器
			uni.$on('personChoose', (e) => {
				console.log('e', e);
				this.formData.personId = e.id;
				this.formData.disability = e.disability === 'Y' ? '是' : '否';
				this.formData.name = e.name;
				this.streetName = e.deptName || '暂无'
			});

			uni.$on('hospitalChoose', (e) => {
				console.log(e);
				this.formData.hospital = e.name;
			})
		},
		onUnload() {
			uni.$off('personChoose');
			uni.$off('hospitalChoose');
		},
		computed: {
			computeStreetCat() {
				switch (this.chooseFromIndex) {
					case 0:
						return '所在街道'
					default:
					case 1:
						return '所在养老院'
					case 2:
						return '所在失能中心'
				}
			},
			computeFromDesc() {
				return this.fromList[this.chooseFromIndex].label
			}
		},
		methods: {
			deletePic(event) {
				this.fileList.splice(event.index, 1);
			},
			beforeRead(event) {
				console.log(event);
				return;
			},
			afterRead(event) {
				console.log(event);
				this.fileList = [{
					...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();
						this.fileList[0].status = 'success';
						this.fileList[0].message = '';
						this.fileList[0].url = uni.$u.http.config.baseURL + '/prod-api/' + res.fileName;
						this.fileList[0].name = res.fileName;
					})
					.catch(err => {
						uni.hideLoading()
						console.log('上传Err', err);
						this.fileList[0].status = 'failed';
						this.fileList[0].message = '上传失败';
					})
			},
			handleTimeConfirm(e) {
				console.log('e', e);
				if (e.value) {
					this.formData.leaveTime = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss')
				} else {
					this.formData.leaveTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
				}
				this.showTimePicker = false;
			},
			handlePickerConfirm(e) {
				console.log('e', e.value[0].id);
				this.chooseStreet = e.value[0];
			},
			getStreetList() {
				getStreetListUrl({
						params: {
							type: this.chooseFromIndex + 1
						}
					})
					.then(res => {
						// console.log(res);
						if (res.length > 0) {
							let temp = res.map(item => {
								return {
									label: item.deptName,
									id: item.deptId
								}
							})
							this.chooseStreet = temp[0];
							this.streetList = [temp];
							this.defaultIndex = [0];
						} else {
							this.streetList = [];
							this.defaultIndex = [0];
							this.streetName = '';
							this.chooseStreet = {}
						}
					})
					.catch(err => {
						console.log('街道信息err', err);
						this.streetList = [];
						this.defaultIndex = [0];
						this.streetName = '';
						this.chooseStreet = {};
					})
			},
			chooseFrom() {
				uni.showActionSheet({
					title: '人员来源',
					itemList: this.fromList.map(item => item.label),
					success: res => {
						if (this.chooseFromIndex === res.tapIndex) {
							return;
						}
						this.chooseFromIndex = res.tapIndex;
						// 获取街道/养老院/失能中心列表
						this.getStreetList();
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			getApplyInfo() {
				getCareInfo({
						id: this.formId
					})
					.then(res => {
						console.log('申请详情', res);
						this.formData = {
							personId: res.personId,
							name: res.personName,
							demand: res.careNeeds,
							sex: res.nurseGender,
							hospital: res.hospital,
							address: res.address,
							remark: res.remark,
							disability: res.disability === 'N' ? "否" : "是"
							// leaveTime: res.leaveTime
						}
						this.fileList = [];
						this.fileList.push({
							status: 'success',
							message: '',
							url: uni.$u.http.config.baseURL + '/prod-api/' + res.imgPath,
							name: res.imgPath
						})
					})
					.catch(err => {
						console.log('申请详情Err', err);
					})
			},
			goChooseHospital() {
				uni.navigateTo({
					url: '/pages/subpack/pages/choose-hospital/choose-hospital'
				})
			},
			goChoosePeople() {
				if (!this.chooseStreet.id || this.chooseStreet.id === -1) {
					return uni.$u.toast('人员来源异常')
				}
				route('/pages/subpack/pages/choose-people/choose-people', {
					deptId: this.chooseStreet.id
				});
			},
			chooseGender() {
				uni.showActionSheet({
					title: '首选护理人员性别',
					itemList: ['男', '女'],
					success: (res) => {
						this.formData.sex = res.tapIndex + '';
					},
					fail: (err) => {
						console.log('弹窗取消');
					}
				});
			},

			apply() {
				uni.showLoading();
				let params = {};
				if (this.formId) {
					params = {
						applyId: this.formId,
						address: this.formData.address,
						applyDate: dayjs().format('YYYY-MM-DD'),
						careNeeds: this.formData.demand,
						hospital: this.formData.hospital,
						nurseGender: this.formData.sex,
						personId: this.formData.personId,
						personName: this.formData.name,
						remark: this.formData.remark,
						imgPath: this.fileList[0].name
						// leaveTime: this.formData.leaveTime,
					}
					applyModifyUrl(params)
						.then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: `提交成功`,
								showCancel: false,
								confirmText: '返回',
								success: (e) => {
									if (e.confirm) {
										uni.navigateBack()
									}
								}
							})
						})
						.catch(err => {
							uni.hideLoading();
							console.log(err);
						})

				} else {
					params = {
						address: this.formData.address,
						applyDate: dayjs().format('YYYY-MM-DD'),
						// careDays: this.formData.dayCount,
						careNeeds: this.formData.demand,
						hospital: this.formData.hospital,
						nurseGender: this.formData.sex,
						personId: this.formData.personId,
						personName: this.formData.name,
						remark: this.formData.remark,
						imgPath: this.fileList[0].name
						// leaveTime: this.formData.leaveTime,
					}
					applyUrl(params)
						.then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: `提交成功`,
								showCancel: false,
								confirmText: '返回',
								success: (e) => {
									if (e.confirm) {
										uni.navigateBack()
									}
								}
							})
						})
						.catch(err => {
							uni.hideLoading();
							console.log(err);
						})
				}

			},

			handleSubmit() {

				if (this.formData.name === '请选择申请人' || !this.formData.name) {
					return uni.$u.toast('请选择申请人')
				}

				if (!this.formData.demand) {
					return uni.$u.toast('请输入护理需求')
				}

				if (this.formData.hospital === '请选择所在医院' || !this.formData.hospital) {
					return uni.$u.toast('请选择所在医院')
				}

				if (!this.formData.address) {
					return uni.$u.toast('请输入详情地址')
				}

				if (!this.fileList[0]?.url.startsWith('http')) {
					return uni.$u.toast('请上传护理申请书')
				}

				// if (!this.formData.leaveTime) {
				// 	return uni.$u.toast('请选择出院时间')
				// }

				uni.showModal({
					title: '提示',
					content: `确定提交此次申请吗?`,
					showCancel: true,
					success: (e) => {
						if (e.confirm) {
							this.apply();
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-datetime-picker {
		flex: 0
	}

	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

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