<template>
	<view class="content">
		<view class="info">
			<view class="header">
				<view class="center" :class="list.length < infoData.specimenNum?'par-top1':'par-top2'">
					<view class="sign red">{{specimenNum}}/{{list.length}}</view>
				</view>
				<view class="tip" v-if="list.length < infoData.specimenNum">请继续扫描标本！</view>
				<view class="title">申请单共有<span class="red">{{totalNum}}</span>份，已固定<span class="red">{{fixationNum}}</span>份还需固定<span class="red">{{specimenNum}}</span>份</view>
			</view>
			<view>
				<view class="list" v-for="(item, index) in list" :key="index">
					<view class="df-list">
						<view class="list-title">标本名称：</view>
						<view class="no-center">{{item.specimenName}}</view>
					</view>
					<view class="df-list">
						<view class="list-title">条码号：</view>
						<view class="no-center">{{item.specimenCode}}</view>
					</view>
				</view>
			</view>
			<view class="list list-top" v-if="infoData">
				<view class="df-list">
					<view class="list-title">患者姓名：</view>
					<view class="no-center">{{infoData.patientName}}({{infoData.patientDTO.bedNum}}床)</view>
				</view>
				<view class="df-list">
					<view class="list-title">住院号：</view>
					<view class="no-center">{{infoData.patientDTO.patientCode}}</view>
				</view>
				<view class="df-list">
					<view class="list-title">科室名称：</view>
					<view class="no-center">{{infoData.patientDTO.department.dept}}</view>
				</view>
				<view class="df-list">
					<view class="list-title">申请单号：</view>
					<view class="no-center">{{infoData.applyCode}}</view>
				</view>
			</view>
		</view>
<!-- 		<view class="btn-view" v-if="list.length < infoData.specimenNum">
			<button class="back-btn" @click="back">返回</button>
		</view> -->
		<view class="btn-view df-sb">
			<button class="back-btn2" @click="back">返回</button>
			<button class="back-btn3" @click="fixation">标本固定存放</button>
		</view>
		<!-- PDA扫描 -->
		<scanner></scanner>
		<!-- 标本固定 -->
		<uni-popup ref="popup" type="dialog" background-color="#fff" :mask-click="false">
			<view class="pop-content">
				<view class="pop-title">提示</view>
				<view class="pop-tip">您标本已扫描完成，请填写固定信息。</view>
				<uni-forms ref="baseForm" :model="form" label-width="110px">
					<uni-forms-item label="工号" required>
						<uni-easyinput v-model="form.code" :clearable="false" @input="inputChange" primaryColor='#49b856' placeholder="请输入工号" />
					</uni-forms-item>
					<uni-forms-item label="姓名" required>
						<view class="text-left">{{form.name}}</view>
					</uni-forms-item>
					<uni-forms-item label="固定液类型" required class="select">
						<uni-data-picker placeholder="请选择固定液类型" :clear-icon="false" :localdata="fixedData" v-model="form.fixative"
						 :map="{text:'name',value:'id'}">
						</uni-data-picker>
					</uni-forms-item>
					<uni-forms-item label="固定时间" required class="time">
						<uni-datetime-picker type="datetime" :clear-icon="false" placeholder="请选择固定时间" v-model="form.fixationTime"/>
					</uni-forms-item>
				</uni-forms>
				<view class="pou-btn">
					<view class="btn border-right" @click="fixationClose">取消</view>
					<view class="btn confirm" @click="dialogConfirm">固定标本</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		get,
		post
	} from "../../http/http.js";
	import scanner from "../../components/scanner/scanner.vue";
	export default {
		data(){
			return{
				infoData:null,
				list:[],
				SMFlag:true,
				fixationModal:false,
				fixedData:[],
				styles:{
					borderColor: '#49b856',
				},
				userInfo:uni.getStorageSync('userData').user,
				hosId: uni.getStorageSync('userData').user.currentHospital.id,
				form:{
					name:'',
					code:'',
					fixationTime:'',
					fixative:'',
					handoverUserId:''
				},
				pathologyFormId:null,
				fixationNum:null,
				specimenNum:null, 
				totalNum:null, 
			}
		},
		components: {
			scanner
		},
		methods:{
			// 时间格式化
			yyTimeFilter(timestamp) {
			  var date = new Date(timestamp); // 时间戳为毫秒级别
				var year = date.getFullYear();
				var month = date.getMonth() + 1;
				var day = date.getDate();
				var hours = date.getHours();
				var minutes = date.getMinutes();
				var seconds = date.getSeconds();
			 
				// 格式化月份、日期、小时、分钟、秒
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				hours = hours < 10 ? '0' + hours : hours;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				seconds = seconds < 10 ? '0' + seconds : seconds;
			 
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			inputChange(e){
				console.log(e)
				if(e.length < 3) {
					return
				}
				let query = {
				  account: e
				};
				post('/data/isRepeat',query).then((data) => {
						if(data.status==200){
							this.form.name = data.userName;
							this.form.handoverUserId = data.userId
						}else{
							this.form.name = '';
							this.form.handoverUserId =null
						}
				  });
			},
			back(){
				// this.padChange('86386627710976\n')
				this.cancelSpecimenModal()
				uni.setStorageSync('pathologyFormId', null)
				uni.navigateTo({
				  url: `/pages/specimenPort/specimenPort?backType=detail`
				});
			},
			// 标本重置
			cancelSpecimenModal(){
				let ids = []
				for(let i of this.list){
					ids.push(i.id)
				}
				let data = {
					pathologySpecimenIds:ids.join(',')
				}
				post('/pathology/cancel', data).then((res) => {
					
				});

			},
			// 标本固定
			fixation(){
				this.form={
					name:'',
					code:'',
					fixationTime: Date.now() - 2*24*1000,
					fixative:this.fixedData[0].id,
					handoverUserId:''
				}
				// this.form.fixationTime = Date.now() - 2*24*1000
				this.$refs.popup.open()
			},
			// 获取固定液类型
			getFixation(){
				post('/common/common/getDictionary', {
					key: "fixing_liquid_type",
					type: "list"
				}).then((res) => {
					this.fixedData = res
				});
			},
			fixationClose(){
				this.$refs.popup.close()
			},
			// 确定固定标本
			dialogConfirm(){
				if(!this.form.code){
					uni.showToast({
						title: '工号不能为空',
						duration: 1000,
						icon:'none'
					});
					return
				}
				if(!this.form.name){
					uni.showToast({
						title: '姓名不能为空',
						duration: 1000,
						icon:'none'
					});
					return
				}
				if(!this.form.fixative){
					uni.showToast({
						title: '固定液类型不能为空',
						duration: 1000,
						icon:'none'
					});
					return
				}
				if(!this.form.fixationTime){
					uni.showToast({
						title: '固定时间不能为空',
						duration: 1000,
						icon:'none'
					});
					return
				}
				let time = null
				if(Number.isInteger(this.form.fixationTime) && this.form.fixationTime > 0){
					time = this.yyTimeFilter(this.form.fixationTime)
				}else{
					time = this.form.fixationTime
				}
				let str = this.list.map(i=>{
					return i.specimenCode
				})
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				let query={
					hosId:this.hosId,
					id:this.infoData.id,
					specimenFixingLiquid:{
						id:this.form.fixative
					},
					specimenCodes:str.join(','),
					handoverUserId:this.form.handoverUserId,
					fixationTime:time,
					specimenDeptId:this.userInfo.dept.id,
					operationType:'pda'
				}
				post('/simple/data/addData/pathologyForm',query).then((res) => {
					uni.hideLoading();
					this.$refs.popup.close()
					uni.showToast({
						title: '固定成功',
						duration: 1000
					});
					setTimeout(_=>{
						this.back()
					},1000)
				});
			},
			// PDA扫描
			padChange(scannerCode){
				scannerCode = scannerCode.replace('\n','')
				if (!this.SMFlag) {
				  return;
				}
				this.SMFlag = false;
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				this.pathologyFormId = uni.getStorageSync('pathologyFormId');
				let query={
					barcode:scannerCode,
					pathologyFormId:this.pathologyFormId,
					platform:"app"
				}
				if(!this.pathologyFormId){
					delete query.pathologyFormId
				}
				post("/pathology/scanCode", query).then((res) => {
					this.SMFlag = true
					uni.hideLoading();
					if(res.status==200){
						let data = res.data[0]
						let item = null
						let str = null
						if(scannerCode.indexOf(':')!=-1){
							str = scannerCode.split(':')
							item = data.pathologySpecimenDTOList.find(i=>i.specimenCode == str[1])
						}else{
							item = data.pathologySpecimenDTOList.find(i=>i.specimenCode == scannerCode)
						}
						// let item = data.pathologySpecimenDTOList.find(i=>i.specimenCode == scannerCode)
						uni.setStorageSync('pathologyFormId', data.id);
						if(!item.fixationTime && data.pathologyFormType==0){
							if(data.status.value==2 || data.status.value==3 ||
							data.status.value==4){
								uni.navigateTo({
								  url: `/pages/specimenPort/scan?data=${JSON.stringify(data)}&type=${res.type}`
								});
							}else{
								uni.showToast({
									title: '查询到标本申请单信息',
									duration: 1000,
									icon:'none'
								});
								setTimeout(_=>{
									uni.navigateTo({
									  url: `/pages/specimenPort/detail?detailId=${data.id}`
									});
								},800)
							}
						}else if(item.fixationTime && data.pathologyFormType==0){
							uni.showToast({
								title: '查询到标本申请单信息',
								duration: 1000,
								icon:'none'
							});
							setTimeout(_=>{
								uni.navigateTo({
									url: `/pages/specimenPort/detail?detailId=${data.id}`
								});
							},800)
						}else{
							uni.showToast({
								title: '该申请单类型不是病理检查申请单',
								duration: 1000,
								icon:'none'
							});
						}
					}else{
						uni.showModal({
						  title: "提示",
						  content: `${res.msg} \n 扫描内容：${scannerCode}`,
							confirmColor:'#49b856',
						  success: (res) => {
						    if (res.confirm) {
						      console.log("用户点击确定");
						    } else if (res.cancel) {
						      console.log("用户点击取消");
						    }
						  },
						});
					}
				})
			},
			getSpecimenNum(){
				post(`/pathology/check/pathologyForm/${this.infoData.id}`, {
					operationType:'fixation'
				}).then(res=>{
					this.fixationNum = res.fixationNum
					this.specimenNum = res.specimenNum
					this.totalNum = res.totalNum
				})
			}
		},
		onBackPress(e) {
			// backbutton：物理按键返回
			if (e.from === 'backbutton') {
				this.back()
				return true 
			}
		},
		onShow() {
			let that = this
			// #ifdef APP-PLUS
			uni.$off('scan') // 每次进来先 移除全局自定义事件监听器
			uni.$on('scan', function(data) {
				that.padChange(data)
			})
			// #endif
		},
		onLoad(option){
			let data = JSON.parse(option.data)
			this.infoData = data
			this.getSpecimenNum()
			this.type = option.type
			this.list = data.pathologySpecimenDTOList?data.pathologySpecimenDTOList:[]
			// if(this.list.length == this.infoData.specimenNum){
			// 	uni.showToast({
			// 		title: '您标本已扫描完成，请填写固定信息',
			// 		duration: 2000,
			// 		icon:'none'
			// 	});
			// }
			this.getFixation()
		}
	}
</script>

<style scoped>
	>>>	.uni-forms-item__content{
		display: flex;
		align-items: center;
	}
	>>>.uni-easyinput__content-input,
	>>>.uni-input-wrapper,
	>>>.uni-input-placeholder{
		display: flex;
		align-items: center;
		line-height: 1;
		height: 35px;
	}
	.select >>>.dialog-close{
		/* display: flex !important; */
	}
	.select >>>.dialog-close-plus{
	}
	.select >>>.dialog-close-rotate{
		top: 20.8px;
		left: 14px;
	}
	.time >>>.dialog-close-rotate{
		top: 24px;
		left: 24.5px;
	}
</style>
<style lang="less" scoped>
	page {
		background: #F8F8F8;
	}
	.red{
		color: red;
	}
	.content {
		.header {
			width: 100%;
			height: 450rpx;
			text-align: center;
			.center{
				.sign{
					font-size: 70rpx;
					font-weight: bold;
				}
			}
			.title{
				font-weight: 500;
				font-size: 34rpx;
				padding: 0 20rpx;
			}
			.par-top1{
				padding-top: 100rpx;
			}
			.par-top2{
				padding-top: 150rpx;
			}
			.tip{
				font-size: 30rpx;
				font-weight: bold;
				padding: 40rpx 0;
			}
		}
		.info{
			// padding: 0 20rpx;
			// background: #fff;
			height: calc(100vh - 120rpx);
			overflow-y: auto;
			background: #F8F8F8;
			.info-list{
				padding: 14rpx 0;
				display: flex;
				font-size: 28rpx;
				color: #555555;
				.info-title{
					color: #000;
				}
				.info-content{
					flex: 1;
				}
			}
		}
		.height-list {
			height: 44px;
		}
		.list {
			background: #fff;
			border-bottom: 1px solid #D2D2D2;
			.df-list {
				display: flex;
				align-items: center;
				padding: 14rpx 20rpx;
				font-size: 28rpx;
				color: #555555;
				.no-center{
					align-items: baseline;
					line-height: 1;
				}
				.list-title{
					color: #000;
					line-height: 1;
				}
			}
		}
		.list-top{
			margin-top: 20rpx;
		}
		.info-log{
			background: #fff;
			height: calc(100vh - 80rpx);
		}
		.df {
			display: flex;
			height: 80rpx;
			align-items: center;
			padding: 0 20rpx;
			border-bottom: 1px solid #D2D2D2;
		}
		.execFilterMask{
		  .execFilter{
		    position: relative;
		    background-color: #fff;
		    height: calc(100vh - 80rpx);
		    
		    .execFilterHeader{
		      height: 70rpx;
		      display: flex;
		      justify-content: center;
		      align-items: center;
		      border-bottom: 2rpx solid #ccc;
		    }
		    
		    .execFilterBody{
		      .execFilterItem{
		        padding: 32rpx;
		        border-bottom: 2rpx dashed #ccc;
		        &:last-of-type{
		          border-bottom: none;
		        }
		        .execFilterItemHeader{}
		        .execFilterItemBody{
		          display: flex;
		          flex-wrap: wrap;
		          padding: 32rpx 0 0;
		          justify-content: space-between;
		          text-align: left;
		          
		          .execFilterItemBox{
		            width: 200rpx;
		            height: 80rpx;
		            text-align: center;
		            line-height: 80rpx;
		            background-color: #f6f6f6;
		            margin-bottom: 20rpx;
		            &.active{
		              color: #fff;
		              background-color: #49b856;
		            }
		          }
		          
		          .deptName {
		            height: 80rpx;
		            background-color: #f6f6f6;
		            padding: 0 20rpx;
								width: 100%;
		          }
		        }
		      }
		    }
		  }
		}
		.btn-view{
			width: 100%;
			bottom: 20rpx;
			position: fixed;
			.back-btn{
				background: #49B856;
				border-radius: 10rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
				line-height: 80rpx;
				width: 95%;
			}
			.back-btn2{
				background: #8F939C;
				border-radius: 10rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
				line-height: 80rpx;
				width: 45%;
			}
			.back-btn3{
				background: #49B856;
				border-radius: 10rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
				line-height: 80rpx;
				width: 45%;
			}
		}
		.df-sb{
			display: flex;
			justify-content: space-between;
		}
		.pop-content{
			text-align: center;
			.pop-title{
				font-size: 32rpx;
				color: #000;
				margin-top: 20rpx;
			}
			.pop-tip{
				font-size: 28rpx;
				color: #6C6C6C;
				margin-top: 10rpx;
			}
			.uni-forms{
				padding: 20rpx 20rpx 0 20rpx;
			}
			.text-left{
				text-align: left;
			}
			.pou-btn{
				color: #000;
				font-size: 30rpx;
				border-top: 1px solid #E3E3E3;
				display: flex;
				padding: 0 20rpx;
				.btn{
					text-align: center;
					line-height: 80rpx;
					width: 50%;
				}
			}
			.border-right{
				border-right: 1px solid #E3E3E3;
			}
			.confirm{
				color: #49B856 !important;
			}
		}
	}
</style>