<template>
	<!-- 订单页面容器 -->
	<view class="order-box">
		<view class="hospital-box">
			<image :src="hospitalInfo.logoUrl" mode="aspectFill"></image>
			<view class="hospital-info">
				<view class="hospital-name">{{hospitalInfo.name || '-'}}</view>
				<view class="hospital-address">
					<u-icon name="map-fill" color="#999999" size="14"></u-icon>
					<span class="address">{{hospitalInfo.address || '-'}}</span>
					</span>
				</view>
				<!-- <view class="hospital-area">所在区:{{hospitalInfo.areaName || '-'}}</view> -->
			</view>
		</view>
		<view class="hospital-form">
			<!-- 用u-form写一个表单，包括所在科室（为一个选择器，内容为1,2,3）,房床号，订单备注，就诊人，服务产品，期望时间，下单数量 -->
			<u--form labelWidth="150rpx" :model="form" :rules="rules" ref="uForm" :error-type="errorType">
				<view class="form-item">
					<u-form-item label="所在科室" prop="department" @click="showDepartment = true;" required borderBottom>
						<u--input :border="none" disabled v-model="form.department" disabledColor="#ffffff"
							placeholder="请选择" inputAlign="right" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="房床号" prop="roomNumber" required borderBottom>
						<u--input v-model="form.roomNumber" placeholder="请输入房号与床号" :border="none" inputAlign="right" />
					</u-form-item>
					<u-form-item label="订单备注" prop="remarks" style="margin: 20rpx 0;" labelPosition="top">
						<u-textarea ref="textarea" count maxlength="50" v-model="form.remarks"
							placeholder="请输入客户或订单特殊情况，可留空"></u-textarea>
					</u-form-item>
				</view>
				<view class="form-item">
					<u-form-item label="就诊人" prop="patient" @click="toPage" required>
						<u--input :border="none" disabled v-model="form.patient" disabledColor="#ffffff"
							placeholder="请选择" inputAlign="right" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</view>
				<view class="form-item">
					<u-form-item label="服务产品" prop="serviceName" @click="toServicePage" required borderBottom>
						<u--input :border="none" disabled v-model="form.serviceName" disabledColor="#ffffff"
							placeholder="请选择" inputAlign="right" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="期望时间" prop="expectedTimeFormat" @click="showTimePicker = true;" borderBottom
						required>
						<u--input :border="none" disabled v-model="form.expectedTimeFormat" disabledColor="#ffffff"
							placeholder="请选择服务开始时间" inputAlign="right" />
						<u-icon slot="right" name="arrow-right"></u-icon>
						<u-datetime-picker :show="showTimePicker" v-model="form.expectedTime" mode="datetime"
							@confirm=selectTime @cancel="showTimePicker = false"></u-datetime-picker>

					</u-form-item>
					<u-form-item label="下单数量" prop="orderNum" required>
						<view class="flex-box-r">
							<u-number-box v-model="form.orderNum" @change="valChange" :max="999"></u-number-box>
							<span style="margin-left: 20rpx;">{{getUnitTxt(unitName) || ''}}</span>
						</view>
					</u-form-item>
				</view>
			</u--form>

			<u-action-sheet :show="showDepartment" :actions="actions" title="请选择科室" description="必选项"
				@close="showDepartment = false" @select="departmentSelect">
			</u-action-sheet>

		</view>
		<!-- 多选框的服务协议 -->
		<view class="agreement-box">
			<u-checkbox-group v-model="checked" @change="checkboxChange">
				<u-checkbox size="16" shape="square" labelSize="12" active-color="#4B91D1" label="我已阅读并同意" la
					labelColor="#999999" name="true"></u-checkbox>
			</u-checkbox-group>
			<view class="agreement" @click="toPrivacy('service_protocol')">《服务协议》</view>
		</view>
		<view class="tips flex-box-cloum">
			<span>润康优护服务公司为您提供服务</span>
		</view>

		<view class="submit-box flex-box-c-b">
			<view class="price-box">
				<span class="txt">金额：</span>
				<span class="price">￥{{price}}</span>
			</view>
			<view class="submit-btn" @click="submit">确认下单</view>
		</view>

		<u-popup :overlayStyle="{'touch-action':'none'}" closeable mode="bottom" :show="popShow" @close="popClose"
			@open="open" :round="20">
			<view class="pop-box">
				<view class="title-box">
					服务协议
				</view>
				<scroll-view class="scroll-content" scroll-y @scroll="handleScroll">
					<view v-html="agreementContent"></view>
				</scroll-view>
				<view class="line-progress">
					<u-line-progress height="12" :percentage="percentage" activeColor="#4B91D1"></u-line-progress>
				</view>
				<view class="btn-box">
					<span class="btn" :class="readed?'active':''" @click="confirm">我已确认</span>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		addOrder,
		getDepartmentList,
		getPrivacy,
		getServiceUnit,
		getDefaultPatient
	} from '@/api/order.js'
	import {
		getHospitalInfo
	} from '@/api/home.js'
	export default {
		data() {
			return {
				percentage: 0,
				agreement: '',
				popShow: false,
				checked: false,
				// 表单数据
				form: {
					hospitalId: '',
					department: '',
					hospitalDepartmentId: '',
					roomNumber: '',
					remarks: '',
					patient: '',
					patientId: '',
					serviceName: '',
					serviceId: '',
					expectedTime: Number(new Date()),
					orderNum: 1
				},
				price: '0.00',
				// 表单验证规则
				rules: {
					department: [{
						required: true,
						message: '请选择所在科室',
						trigger: ['change', 'blur']
					}],
					roomNumber: [{
						required: true,
						message: '请输入房床号',
						trigger: ['change', 'blur']
					}],
					// remarks: [{
					// 	required: true,
					// 	message: '请输入订单备注',
					// 	trigger: ['change', 'blur']
					// }],
					patient: [{
						required: true,
						message: '请选择就诊人',
						trigger: ['change', 'blur']
					}],
					serviceName: [{
						required: true,
						message: '请选择服务产品',
						trigger: ['change', 'blur']
					}],
					expectedTimeFormat: [{
						required: true,
						message: '请输入期望时间',
						trigger: ['change', 'blur']
					}],
					// orderNum: [{
					// 	required: true,
					// 	message: '请输入下单数量',
					// 	trigger: ['change']
					// }]
				},
				errorType: ['toast'],
				showDepartment: false,
				showTimePicker: false,
				actions: [],

				hospitalInfo: {},
				readed: false,
				agreementContent: '',
				unitName: null,
				unitList: [],

			};
		},

		onLoad(option) {
			let that = this;
			if (option.id) {
				this.getHospitalInfo(option.id)
			}
			this.getServiceUnit();
			this.getDefaultInfo();
			uni.$on('returnService', function(data) {
				that.form.serviceName = data.name;
				that.form.serviceId = data.id;
				that.price = data.sellingPrice;
				that.unitName = data.serviceUnit;
			});

			uni.$on('returnPatient', function(data) {
				that.form.patient = data.name;
				that.form.patientId = data.id;
			});

		},


		onReady() {
			let that = this;
			that.$refs.uForm.setRules(this.rules);
			// 如果需要兼容微信小程序的话，需要用此写法
			that.$refs.textarea.setFormatter((value) => {
				if (value.length >= 50) {
					return value.substr(0, 50)
				} else {
					return value
				}
			})
		},

		methods: {
			//获取医院详情
			getHospitalInfo(id) {
				let that = this;
				getHospitalInfo(id).then(res => {
					if (res.code == 200) {
						that.hospitalInfo = res.data;
						that.form.hospitalId = that.hospitalInfo.id
						that.getDepartmentList()
					}
				})
			},

			//获取默认就诊人
			getDefaultInfo() {
				let that = this;
				getDefaultPatient().then(res => {
					if (res.code == 200) {
						let data = res.data;
						that.form.patient = data.name+ '(' +  data.mobile +')';
						that.form.patientId = data.id;
					}
				})
			},

			//滚动协议
			handleScroll(e) {
				//根据。agreement-content 的滚动条的进度，设置百分比
				let scrollHeight = e.detail.scrollHeight;
				let scrollTop = e.detail.scrollTop;
				this.percentage = ((scrollTop / (scrollHeight - 400)) * 100).toFixed(0);
				if (this.percentage >= 100) {
					this.readed = true
				} else {
					this.readed = false
				}
			},
			getUnitTxt(value) {
				let obj = this.unitList.find(item => item.code == value);;
				return obj ? obj.value : ''
			},
			//查询订单状态
			getServiceUnit() {
				let that = this;
				getServiceUnit().then(res => {
						if (res.code == 200) {
							this.unitList = res.data.serviceUnit;
						}
					})
					.catch((err) => {
						console.log(err);
					})

			},
			//获取科室列表
			getDepartmentList() {
				let that = this;
				let param = {
					hospitalId: that.form.hospitalId
				};
				getDepartmentList(param).then(res => {
					if (res.code == 200) {
						this.actions = res.data
					}
				})
			},
			// 提交表单
			submit() {
				let that = this;
				if (!that.checked) {
					uni.showToast({
						title: '请先阅读并同意服务协议',
						icon: 'none'
					})
					return
				}
				this.$refs.uForm.validate().then((res) => {
					if (res) {
						// 提交表单
						that.open();
					} else {
						console.log('表单验证失败');
					}
				})
			},
			confirm() {
				addOrder(this.form).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '下单成功',
							icon: 'success'
						})
						setTimeout(() => {
							this.popShow = false;
							//跳转订单页面传递参数
							getApp().globalData.switchTabParams = {
								reload: 'reload'
							};
							uni.switchTab({
								url: '/pages/tabBar/order',
							})
						}, 1000)
					}
				})

			},
			//选择时间
			selectTime(e) {
				this.form.expectedTime = e.value
				this.form.expectedTimeFormat = this.$utils.mFormatDate(e.value, 'yyyy-MM-dd HH:mm')
				this.showTimePicker = false
			},
			//选择科室
			departmentSelect(e) {
				this.form.department = e.name;
				this.form.hospitalDepartmentId = e.id;
				this.showDepartment = false;
				this.$refs.uForm.validateField('hospitalDepartmentId')
			},
			//数量
			valChange(e) {
				this.form.orderNum = e.value
			},

			//选择同意协议
			checkboxChange(e) {
				console.log('当前值为: ' + e)
				if (e) {
					this.checked = true
				} else {
					this.checked = false
				}
			},

			//去选择服务
			toServicePage() {
				uni.navigateTo({
					url: '/pages/order/chooseService'
				})
			},
			//去就诊人页面
			toPage() {
				uni.setStorageSync('patientType', 'order')
				uni.navigateTo({
					url: '/pages/mine/patient/patient'
				})
			},
			// 打开协议弹窗
			open() {
				let that = this;
				that.popShow = true;
				getPrivacy({
					code: 'service_protocol'
				}).then(res => {
					if (res.code == 200) {
						that.agreementContent = res.data.protocolContent.replace(/\<img/gi,
							'<img style="max-width:100%;height:auto" ');
					}
				})
			},

			toPrivacy(type) {
				uni.navigateTo({
					url: '/pages/mine/agreement?type=service_protocol'
				})
			},

			popClose() {
				this.percentage = 0;
				this.popShow = false;
			},

		},
		onUnload() {
			uni.$off('returnService');
			uni.$off('returnPatient');
		},
	}
</script>

<style lang="scss" scoped>
	.order-box {
		background-color: #f6f6f6;
		padding: 20rpx 20rpx 200rpx;

		.hospital-box {
			display: flex;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 10rpx;

			image {
				width: 180rpx;
				height: 172rpx;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}

			.hospital-info {
				flex: 1;

				.hospital-name {
					word-break: break-all;
					font-size: 28rpx;
					font-weight: bold;
				}

				.hospital-address {
					display: flex;
					justify-content: flex-start;
					align-items: flex-start;
					width: 100%;
					font-size: 26rpx;
					color: #666;
					margin-top: 20rpx;
					font-weight: 500;
					line-height: 35rpx;
					overflow: hidden; //超出的文本隐藏
					text-overflow: ellipsis; //溢出用省略号显示
					white-space: normal; //处理元素中的 空白
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					display: -moz-box;
					-moz-line-clamp: 2;
					-moz-box-orient: vertical;
					overflow-wrap: break-word;
					word-break: break-all;

					::v-deep .u-icon {
						display: inline-block;
					}

					.address {
						font-size: 28rpx;
						margin-left: 5rpx;
						color: #999999;
					}
				}

				.hospital-area {
					font-size: 24rpx;
					color: #999;
				}
			}
		}

		.hospital-form {
			margin-top: 20rpx;
			border-radius: 10rpx;

			.form-item {
				padding: 20rpx 30rpx;
				margin-bottom: 20rpx;
				background-color: #fff;
				border-radius: 10rpx;
			}

		}

		.agreement-box {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 20rpx;

			.agreement {
				font-size: 22rpx;
				margin-left: 10rpx;
				color: #2979ff;
			}
		}

		.tips {
			margin-top: 20rpx;
			color: #666666;
			font-size: 22rpx;
		}

		.pop-box {
			padding: 0 40rpx;

			.title-box {
				padding: 30rpx 0;
				width: 100%;
				text-align: center;
			}

			.scroll-content {
				padding: 20rpx;
				width: 100%;
				box-sizing: border-box;
				height: 400px;
				border: 1rpx solid #f6f6f6;


			}

			.line-progress {
				padding: 20rpx 0;
			}

			.btn-box {
				margin-bottom: 40rpx;

				.btn {
					display: block;
					width: 100%;
					height: 72rpx;
					text-align: center;
					line-height: 72rpx;
					background-color: #999;
					color: #fff;
					border-radius: 40rpx;
				}

				.active {
					background-color: #4B91D1;
				}
			}
		}

		.submit-box {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 40rpx 20rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);

			.price-box {
				font-size: 32rpx;

				.txt {
					color: #666;
				}

				.price {
					color: #ff0000;
				}
			}


			.submit-btn {
				padding: 20rpx 40rpx;
				background-color: #2979ff;
				color: #fff;
				width: 200rpx;
				border-radius: 40rpx;
				text-align: center;
				font-size: 24rpx;
			}
		}

		::v-deep .u-textarea {
			margin-top: 20rpx;
		}
	}
</style>