<template>
	<view>
		  <view class="container book-main">
		    <view class="form-box">
		      <view class="form-box-label">选择科室</view>
		      <view class="form-box-content" @click="selectDep">
		        <view class="form-box-content-text" v-if="!dep.title">请选择</view>
				<view class="form-box-content-text" v-if="dep.title">{{dep.title}}</view>
		        <image src="../../images/xiangyou-xiao.png"></image>
		      </view>
		    </view>
		    <view class="form-box">
		      <view class="form-box-label">联系人 <text class="text-red">*</text></view>
		      <view class="form-box-content">
		        <input type="text" v-model="contact" placeholder="请填写" />
		      </view>
		    </view>
			<view class="form-box">
			  <view class="form-box-label">联系手机号 <text class="text-red">*</text></view>
			  <view class="form-box-content">
			    <input type="tel" v-model="phone" placeholder="请填写" />
			  </view>
			</view>
			
			<view class="form-box">
			  <view class="form-box-label">选择服务 <text class="text-red">*</text></view>
			  <view class="form-box-content" @click="selectCate">
			    <view class="form-box-content-text" v-if="!cate.title">请选择</view>
				<view class="form-box-content-text" v-if="cate.title">{{cate.title}}</view>
			    <image src="../../images/xiangyou-xiao.png"></image>
			  </view>
			</view>
		    
		    <view class="form-box form-box2">
		      <view class="form-box-label">被陪护人信息</view>
			  <view class="form-box-sub">
			    <view class="form-box-label">姓名<text class="text-red">*</text></view>
			    <view class="form-box-content">
			      <input type="text" placeholder="请填写" v-model="name" />
			    </view>
			  </view>
			  <view class="form-box-sub">
			    <view class="form-box-label">性别<text class="text-red">*</text></view>
			    <view class="form-box-content" @click="selectGender">
			      <view class="form-box-content-text">{{gender.title}}</view>
				  <image src="../../images/xiangyou-xiao.png"></image>
			    </view>
			  </view>
			  <view class="form-box-sub">
			    <view class="form-box-label">年龄<text class="text-red">*</text></view>
			    <view class="form-box-content">
			      <input type="number" placeholder="请填写"  v-model="age" />
			    </view>
			  </view>
			  <view class="form-box-sub">
			    <view class="form-box-label">床号<text class="text-red">*</text></view>
			    <view class="form-box-content">
			      <input type="text" placeholder="请填写" v-model="bed" />
			    </view>
			  </view>
		      <view class="form-box-sub">
		        <view class="form-box-label">所患疾病<text class="text-red">*</text></view>
		        <view class="form-box-content">
		          <input type="text" placeholder="请填写" v-model="ill" />
		        </view>
		      </view>
		    </view>
			
			<view class="form-box">
			  <view class="form-box-label">预约时间<text class="text-red">*</text></view>
			  <view class="form-box-content">
				<view class="form-box-content" @click="selectStart">
				  <view class="form-box-content-text" v-if="!start">请选择</view>
				  <view class="form-box-content-text" v-if="start">{{start}}</view>
				  <image src="../../images/xiangyou-xiao.png"></image>
				</view>
			  </view>
			</view>
			
			<view class="form-box form-box2">
			  <view class="form-box-label">备注</view>
			  <view class="form-box-textarea">
			    <textarea style="height:120rpx;" v-model="remark" placeholder="请填写" />
			  </view>
			</view>
		
		    <view class="book-btn" @click="saveBtn()">提交</view>
		  </view>
		  
		  <view class="protocol-box" v-if="showProtocol">
			  <view v-html="protocol"></view>
			  <view class="protocol-btn" @click="qrProtocolBtn()">同 意</view>
		  </view>
		  
			<view class="sign-box" v-if="showSign">
				<spsignboard
				  ref="signBoardRef"
				  sid="sign-board"
				  bgColor="#ffffff"
				  :showMark="false"
				  :mark-text="markText"
				  :horizontal="false"
				  :penStyle="{ lineWidth: 4, color: '#000000' }"
				  :expFile="{ fileType: 'jpg', quality: 0.7 }"
				  @cancel="onCancel()"
				  @confirm="onConfirmBoard()"
				  @reset="reset"
				  @firstTouchStart="firstTouchStart"
				></spsignboard>
		      
			  <!-- <view class="sign-up-btn">上传签名</view> -->
			</view>
		  
		  <cpicker v-if="genders.length > 0" :list="genders" :show.sync="genderShow" :did="gender.id" @confirm="selectedGenderVal"></cpicker>
		  <cpicker v-if="deps.length > 0" :list="deps" :show.sync="depShow" :did="dep.id" @confirm="selectedDepVal"></cpicker>
			<w-picker
				:visible.sync="startVisible"
				mode="date" 
				startYear="2021" 
				endYear="5000"
				themeColor="#006489"
				:value="start"
				:current="true"
				fields="minute"
				@confirm="onConfirm($event,'date')"
				:disabled-after="false"
				ref="date" 
			></w-picker>
			<cpicker v-if="cates.length > 0" :list="cates" :show.sync="cateShow" :did="cate.id" @confirm="selectedCateVal"></cpicker>
	</view>
</template>

<script>
	var app = getApp();
	import cpicker from "../../components/cpicker/cpicker.vue";
	import wpicker from "../../components/w-picker/w-picker.vue";
	import spsignboard from "../../components/sp-sign-board/components/sp-sign-board/sp-sign-board.vue";
	export default {
		components: {
			cpicker,
			wpicker,
			spsignboard
		},
		data() {
			return {
				signBase64: "",
				signTempimg: "",
				markText: "陪护",
				showProtocol: false,
				isProtocol: false,
				protocol: "", // 协议内容
				showSign: false,
				isSign: false,
				signPath: "", // 签名上传路径
				flag: false,
				start:'',
				startVisible:false,
				contact: '',
				name: '',
				phone: '',
				ill: '',
				age: '',
				bed: '',
				gender: {
					id: 1,
					title: '男'
				},
				genderShow: false,
				genders:[{"id":1,"title":"男"},{"id":2,"title":"女"}],
				dep: {
					id: 0,
					title: ''
				},
				depShow: false,
				deps:[],
				remark: '',
				cate: {
					id: 0,
					title: ''
				},
				cates:[],
				cateShow: false,
				wx: null,
			}
		},
		onLoad(option) {
			var that = this;
			var orgId = this.getUrlCode('orgId');
			if(orgId){
				uni.setStorageSync(app.globalData.storagePre+'orgId',orgId);
				app.globalData.userinfo.orgId = orgId;
			}else{
				orgId = uni.getStorageSync(app.globalData.storagePre+'orgId');
				if(orgId){
					app.globalData.userinfo.orgId = orgId;
				}else{
					uni.showToast({
						title: '参数错误',
						icon: 'none',
						duration: 2000
					})
				}
			}
			
			if (this.$wechat && this.$wechat.isWechat()) {//获取定位经纬度
				this.$wechat.getWx(function (res) {
					console.log(res)
					that.wx = res;
				});
			}
			
			// 生成水印内容
			this.refreshMark()
		},
		onShow() {
			var that = this;
			app.ajaxReadyCallback = res => {  //各个接口统一回调方法
				var apiname = res.data.apiname;
				console.log(res);
				if(apiname == 'dep'){
					that.deps = res.data.data;
				}else if(apiname == 'cates'){
					that.cates = res.data.data;
				}else if(apiname == 'protocol'){
					that.protocol = res.data.data.content;
				} else if(apiname == 'order'){
					var payId = res.data.data.payId;
					if(payId <= 0){
						uni.navigateTo({
						    url: '/pages/index/success'
						});
					}else{
						that.getPayParam(payId);
					}
				}else if(apiname == 'pay'){
					if(that.wx){
						that.wx.chooseWXPay({
							timestamp: res.data.data.timestamp,
							nonceStr: res.data.data.nonceStr,
							package: res.data.data.package,
							signType: res.data.data.signType,
							paySign: res.data.data.paySign,
							success: function (r) {
								// 支付成功后的回调函数
								if (r.errMsg == "chooseWXPay:ok") {
									uni.navigateTo({
									    url: '/pages/index/success'
									});
								} else {
									uni.navigateTo({
									    url: '/pages/index/fail'
									});
								}
							},
							cancel: function(r) {},
							fail:function(r){
								// uni.showToast({
								// 	title: '支付失败',
								// 	icon: 'none',
								// 	duration: 2000
								// })
								uni.navigateTo({
								    url: '/pages/index/fail'
								});
							}
						});
					}else{
						// uni.showToast({
						// 	title: '支付调用失败，请刷新重试',
						// 	icon: 'none',
						// 	duration: 2000
						// })
						uni.navigateTo({
						    url: '/pages/index/fail'
						});
					}
				}
			}
			
			this.getDep();
			this.getCate();
			this.getProtocol();
			
			// 监听一次
			uni.$on('getSignImg', (e) => {
			  console.log('getSignImg', e)
			  // 多签名场景下可根据 sid 区分不同签名
			  if (e.sid == 'sign-board') {
			    that.signBase64 = e.base64
			    that.signTempimg = e.path
				that.isSign = true;
				this.showSign = false;
				this.saveBtn();
				
			  }
			  // 一定注意不能确认签字完成后立马关闭弹窗，否则签字板会销毁，无法获取签名。需要等签名正确获取到之后再关闭弹窗
			  // this.close()
			})
		
		},
		methods: {
			getUrlCode (name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
			},
			selectGender(){
				this.genderShow = true;
			},
			selectedGenderVal(obj){
				console.log(obj)
				this.gender = obj;
			},
			selectDep(){
				this.depShow = true;
			},
			selectedDepVal(obj){
				console.log(obj)
				this.dep = obj;
			},
			selectCate(){
				this.cateShow = true;
			},
			selectedCateVal(obj){
				console.log(obj)
				this.cate = obj;
			},
			getProtocol(){
				app.ajax({
					url: app.globalData.serverUrl + 'common/phprotocol',
					type: 'POST',
					apiname: 'protocol',
				});
			},
			getDep(){
				app.ajax({
					url: app.globalData.serverUrl + 'common/dep',
					type: 'POST',
					apiname: 'dep',
				});
			},
			getCate(){
				app.ajax({
					url: app.globalData.serverUrl + 'Worker/cates',
					type: 'POST',
					apiname: 'cates',
				});
			},
			getPayParam(payId){
				app.ajax({
					url: app.globalData.serverUrl + 'PhOrders/pay',
					type: 'POST',
					apiname: 'pay',
					data: {
						payId: payId
					}
				});
			},
			onConfirm(e,type){
				this.start = e.result;
			},
			onCancel(){
				console.log("onCancel");
				this.showSign = false;
			},
			onConfirmBoard(){
				console.log("onConfirmBoard");
				this.showSign = false;
				this.saveBtn();
			},
			selectStart(){
				this.startVisible = true;
			},
			
			qrProtocolBtn(){
				this.showProtocol = false;
				this.isProtocol = true;
				this.saveBtn();
			},
			
			refreshMark() {
			  // const currentDate = new Date()
			  // const year = currentDate.getFullYear()
			  // const month = String(currentDate.getMonth() + 1).padStart(2, '0')
			  // const day = String(currentDate.getDate()).padStart(2, '0')
			  // const hours = String(currentDate.getHours()).padStart(2, '0')
			  // const minutes = String(currentDate.getMinutes()).padStart(2, '0')
			  // const seconds = String(currentDate.getSeconds()).padStart(2, '0')
			
			  this.markText = ["陪护"];
			},
			firstTouchStart() {
			  // 在第一次开始触碰时，更新一下时间水印，防止滞留时间太长造成时间误差（非必要）
			  this.refreshMark()
			  // 手动调用组件内绘制水印方法重新绘制
			  this.$refs.signBoardRef.drawMark(this.markText)
			},
			reset() {
			  this.refreshMark()
			},
			
			saveBtn(){
				if(!this.contact){
					uni.showToast({
						title: '请输入联系人',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.phone){
					uni.showToast({
						title: '请输入手机号',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.cate || this.cate.id <= 0){
					uni.showToast({
						title: '请输入选择服务',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.name){
					uni.showToast({
						title: '请输入姓名',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.age){
					uni.showToast({
						title: '请输入年龄',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.bed){
					uni.showToast({
						title: '请输入床号',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.ill){
					uni.showToast({
						title: '请输入所患疾病',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.start){
					uni.showToast({
						title: '请选择预约时间',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if(!this.isProtocol){
					this.showProtocol = true;
					return false;
				}
				if(!this.isSign || !this.signBase64){
					this.showSign = true;
					return false;
				}
				let param = {
					contact: this.contact,
					phone: this.phone,
					name: this.name,
					gender: this.gender.id,
					age: this.age,
					bed: this.bed,
					ill: this.ill,
					start: this.start,
					remark: this.remark,
					depId: this.dep.id,
					cateId: this.cate.id,
					sign: this.signBase64
				}
				app.ajax({
					url: app.globalData.serverUrl + 'worker/order',
					type: 'POST',
					apiname: 'order',
					data: param
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.navbg{
	    width: 100%;
	    height: 300rpx;
	}
	.book-main{
	    width: 710rpx;
	    // position: absolute;
	    // z-index: 10;
	    // top: 300rpx;
	    // left: 0;
	    // bottom: 0;
	    // overflow: auto;
		overflow-y: auto;
		overflow-x: hidden;
	}
	
	
	.book-btn{
	    width: 710rpx;
	    height: 90rpx;
	    line-height: 90rpx;
	    background-color: var(--themeColor);
	    color: #ffffff;
	    font-size: 34rpx;
	    font-weight: bold;
	    text-align: center;
	    border-radius: 10rpx;
	}
	.protocol-box{
		position: fixed;
		z-index: 10000;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #ffffff;
		padding: 20rpx;
		overflow: auto;
	}
	
	.protocol-btn{
		position: fixed;
		z-index: 10001;
		left: 20rpx;
		right: 20rpx;
		bottom: 10rpx;
		background-color: var(--themeColor);
		height: 90rpx;
		line-height: 90rpx;
		color: #ffffff;
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
		border-radius: 10rpx;
	}
	
	.sign-box{
		position: fixed;
		z-index: 100000;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #ffffff;
		padding: 20rpx;
	}
	.sign-canvas{
		width: 750rpx;
		height: 400rpx;
	}
	.sign-up-btn{
		position: fixed;
		z-index: 100001;
		left: 20rpx;
		right: 20rpx;
		bottom: 10rpx;
		background-color: var(--themeColor);
		height: 90rpx;
		line-height: 90rpx;
		color: #ffffff;
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
		border-radius: 10rpx;
	}
	
	.protocol-box image{
		max-width: 100%;
	}
	
</style>
