<template>
	<view class="conte">
		<view class="header">
			<text class="title">{{userInfo.dept.dept}}
				<text class="red" v-if="otherData">
					(单 {{otherData.pathologyFormNum}}, 标 {{otherData.specimenNum}})
				</text>
			</text>
			<view class="filter" @click="filterClick">
				<text class="newicon newicon-shaixuan icon"></text>
			</view>
		</view>
		<view class="height-list"></view>
		<view class="list" @click="detail(item)" v-for="(item, index) in list" :key="index">
			<view class="df-list list-border">
				<view>{{item.applyCode}}</view>
				<view>{{item.status.name}}</view>
			</view>
			<view class="df-list">
				<view class="df-list-over-left">科室:{{item.patientDTO.department.dept}}</view>
				<view class="df-list-over">部位:{{item.takePart}}</view>
			</view>
			<view class="df-list">
				<view class="df-list-over-left">患者:{{item.patientName}}({{item.patientDTO.bedNum}}床)</view>
				<view class="df-list-over">住院号:{{item.patientDTO.patientCode}}</view>
			</view>
			<view class="df-list">
				<view class="df-list-over-left">离:{{yyTimeFilter(item.inVitroTime)}}</view>
				<view class="df-list-over">固:{{yyTimeFilter(item.fixationTime)}}</view>
			</view>
			<view class="list-content"></view>
		</view>
		<uni-drawer width="400px" :visible="isShowFilter" mode="right" :maskClick="false" @close="filterCacel()">
			<view class="execFilterMask" @touchmove.stop.prevent>
				<view class="execFilter">
					<radio-group @change="radioChange">
						<label class="df uni-list-cell uni-list-cell-pd" v-for="(item, index) in specimenData" :key="item.id">
							<view>
								<radio :value="item.id+''" :checked="index == current" />
							</view>
							<view>{{item.dept}}</view>
						</label>
					</radio-group>
					<view>
						<label class="df uni-list-cell uni-list-cell-pd">固定并存放标本间</label>
						<checkbox-group @change="checkChange">
							<label class="df uni-list-cell uni-list-cell-pd">
								<checkbox color="#49B856" value="1" :checked="depositCheck" />是否开启
							</label>
						</checkbox-group>
					</view>
					<view class="execFilterFooter">
						<view class="btn" @click="filterCacel()" v-if="isDept || specimenData.length==0">取消</view>
						<view class="btn" @click="filterOk()">确认</view>
					</view>
				</view>
			</view>
		</uni-drawer>
		<!-- PDA扫描 -->
		<scanner></scanner>
		<!-- apk自动更新 -->
		<appUpdata v-if="isApp && isUpdate" @getUpdate="isUpdate=false"></appUpdata>
	</view>
</template>

<script>
	import {
		get,
		post
	} from "../../http/http.js";
	import scanner from "../../components/scanner/scanner.vue";
	import appUpdata from "../../components/appUpdata/appUpdata.vue";
	export default {
		data() {
			return {
				list: [],
				idx: 0,
				isDept:null,
				userInfo:uni.getStorageSync('userData').user,
				hosId: uni.getStorageSync('userData').user.currentHospital.id,
				specimenData: [],
				isShowFilter: false,
				current: null,
				deptId:null,
				totalNum:0,
				hasMore:true,
				SMFlag:true,
				otherData:null,
				isApp:false,
				isUpdate:false,
				depositCheck:false,
			}
		},
		components: {
			scanner,
			appUpdata
		},
		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}`;
			},
			// 选择check
			checkChange(e){
				let values = e.detail.value;
				if(values[0]=='1'){
					this.depositCheck = true
				}else{
					this.depositCheck = false
				}
			},
			// 打开科室选择
			filterClick() {
				this.isShowFilter = true
				this.$nextTick(_=>{
					let userInfo = uni.getStorageSync('userData').user
					if(this.isDept){
						for (let i = 0; i < this.specimenData.length; i++) {
							if (this.specimenData[i].id == userInfo.dept.id) {
								this.current = i;
								this.deptId = userInfo.dept.id;
								break;
							}
						}
					}
				})
			},
			// 关闭科室弹框
			filterCacel() {
				this.isShowFilter = false
			},
			// 确定关联科室
			filterOk() {
				let userInfo = uni.getStorageSync('userData').user
				if(!this.isDept){
					if(!this.deptId){
						uni.showToast({
							title: '请选择科室',
							duration: 1000,
							icon:'none'
						});
						return
					}
				}
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				let query = {
					user: {
						dept:{
							id:this.deptId?this.deptId:userInfo.dept.id
						},
						id:userInfo.id,
						fixedStoredSpecimenRoom:this.depositCheck ? 1 : 0
					},
				}
				post('/data/updData/user', query).then(res => {
					uni.hideLoading();
					this.filterCacel();
					this.getCurrentUserNow()
					this.idx = 0
					this.getList()
				});
			},
			// getNewDept(){
			// 	let postData = {
			// 	  currentHosId: this.hosId,
			// 	  loginType: "Wechat",
			// 	};
			// 	post('/auth/changeHospital',postData).then((result) => {
			// 	  if (result.status == 200) {
			// 			this.getCurrentUserNow();
			// 	  }
			// 	});
			// },
			// 获取当前用户信息
			getCurrentUserNow() {
			  get('/user/data/getCurrentUser').then((data) => {
			    if (data["status"] == 200) {
						this.loginUser = data.data 
			      let user = uni.getStorageSync('userData');
			      user.user.dept = data["data"].dept;
			      user.user.currentHospital = data["data"].currentHospital;
						this.userInfo.dept.dept = data["data"].dept.dept;
						user.user.fixedStoredSpecimenRoom = data["data"].fixedStoredSpecimenRoom;
						uni.setStorageSync('userData',user)
						let userInfo = uni.getStorageSync('userData').user
						this.isDept = this.specimenData.find(i=>i.id == userInfo.dept.id)
						if(userInfo.fixedStoredSpecimenRoom!=null){
							this.depositCheck = userInfo.fixedStoredSpecimenRoom == 1 ? true : false
						}
			    }
			  });
			},
			// 选择科室
			radioChange(evt) {
				this.deptId = evt.detail.value
				for (let i = 0; i < this.specimenData.length; i++) {
					if (this.specimenData[i].id == evt.detail.value) {
						this.current = i;
						break;
					}
				}
			},
			// 查看详情
			detail(item){
				// this.padChange('862420344832\n')
				uni.navigateTo({
				  url: `/pages/specimenPort/detail?detailId=${item.id}`
				});
			},
			// 获取标本间科室
			getDept(backType) {
				post('/common/common/getDictionary', {
					key: "dept_type",
					type: "list"
				}).then((res2) => {
					let item2 = res2.find(i => i.name == '标本间科室')
					let query = {
						idx: 0,
						sum: 9999,
						department: {
							hospital: {
								id: this.hosId || ""
							},
							type: {
								id: item2.id || ""
							},
						},
					};
			
					post('/data/fetchDataList/department', query).then((res) => {
							this.specimenData = res.list
							if(!backType){
								this.isShowFilter = true
							}
							let userInfo = uni.getStorageSync('userData').user
							if(userInfo.fixedStoredSpecimenRoom!=null){
								this.depositCheck = userInfo.fixedStoredSpecimenRoom == 1 ? true : false
							}
							this.isDept = this.specimenData.find(i=>i.id == userInfo.dept.id)
							this.$nextTick(_=>{
								if(this.isDept){
									for (let i = 0; i < this.specimenData.length; i++) {
										if (this.specimenData[i].id === userInfo.dept.id) {
											this.current = i;
											break;
										}
									}
								}
							})
							if(this.isDept){
								this.getList()
							}
						});
				});
			},
			// 分页数据
			getList() {
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				let query = {
					idx: this.idx,
					pathologyForm: {
						detailsType: "specimenDept",
						keyWords: "",
						hosId: this.hosId,
					},
					sum: 20
				}
				post('/data/fetchDataList/pathologyForm', query).then(res => {
					uni.hideLoading();
					if(res.list.length){
						this.hasMore = true;
						this.list = this.idx === 0 ? res.list : this.list.concat(res.list);
						this.otherData = res.otherData
					}else{
						if(this.idx == 0){
							this.list = []
						}
						this.hasMore = false;
					}
					this.totalNum = res.totalNum;
				});
			},
			// PDA扫描
			padChange(scannerCode){
				scannerCode = scannerCode.replace('\n','')
				if (!this.SMFlag) {
				  return;
				}
				this.SMFlag = false;
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				post("/pathology/scanCode", {
					barcode:scannerCode,
					platform:"app"
				}).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)
						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("用户点击取消");
						    }
						  },
						});
					}
				})
			},
		},
		onReachBottom() {
			this.idx++;
			if (this.hasMore) {
				this.getList(); // 当触底时加载更多数据
			}
		},
		onBackPress(e) {
			// backbutton:物理按键返回
			if (e.from === 'backbutton') {
				uni.navigateTo({
				  url: `/pages/homePage/homePage`
				});
				return true 
			}
		},
		onShow() {
			let that = this
			// #ifdef APP-PLUS
			this.isUpdate = true
			this.isApp = true
			uni.$off('scan') // 每次进来先 移除全局自定义事件监听器
			uni.$on('scan', function(data) {
				that.padChange(data)
			})
			// #endif
		},
		onLoad(option) {
			let backType = option.backType ? option.backType : null
			this.getDept(backType)
			// #ifdef APP-PLUS
			this.isUpdate = true
			this.isApp = true
			// #endif

		}
	}
</script>

<style lang="less" scoped>
	page {
		background: #F7F7F7;
	}

	.conte {
		.header {
			height: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			position: fixed;
			width: 100%;
			background: #F7F7F7;

			.title {
				color: #57BC63;
				font-size: 32rpx;
				font-weight: 500;
				.red{
					color: red;
					margin-left: 10px;
				}
			}

			.filter {
				position: absolute;
				right: 15rpx;
				top: 24rpx;
				.icon{
					font-size: 34rpx;
				}
			}
		}

		.height-list {
			height: 44px;
		}

		.list {
			// margin-bottom: 20rpx;
			background: #fff;

			.df-list {
				display: flex;
				justify-content: space-between;
				padding: 14rpx 20rpx;
				font-size: 28rpx;
				color: #555555;
				.df-list-over-left{
					overflow: hidden;
					flex: 1;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				.df-list-over{
					overflow: hidden;
					flex: 1;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-left: 20rpx;
				}
			}

			.list-border {
				border-bottom: 1px solid #D2D2D2;
				height: 46rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 32rpx !important;
				font-weight: 500;
				color: #000;
			}
			.list-content{
				height: 22rpx;
				background: #F7F7F7;
			}
		}

		.df {
			display: flex;
			height: 80rpx;
			align-items: center;
			padding: 0 20rpx;
			border-bottom: 1px solid #D2D2D2;
		}
		.execFilterMask{
		  .execFilter{
		    position: relative;
		    background-color: #fff;
		    height: 100vh;
		    border-radius: 100rpx 100rpx 0 0;
				
		    /deep/ .uni-radio-input-checked {
		      background-color: #49b856 !important;
		      border-color: #49b856 !important;
		    }
		    .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;
		            border-radius: 80rpx;
		            &.active{
		              color: #fff;
		              background-color: #49b856;
		            }
		          }
		          
		          .deptName {
		            height: 80rpx;
		            background-color: #f6f6f6;
		            border-radius: 20rpx;
		            padding: 0 20rpx;
								width: 100%;
		          }
		        }
		      }
		    }
		    
		    .execFilterFooter {
		      position: absolute;
		      bottom: 0;
		      right: 0;
		      left: 0;
		      line-height: 66rpx;
		      height: 100rpx;
		      display: flex;
		      justify-content: space-between;
		    
		      .btn {
		        height: 66rpx;
		        flex: 1;
		        margin: 0 1%;
		        background-image: linear-gradient(to right, #72c172, #3bb197);
		        color: #fff;
		        border-radius: 8rpx;
		        font-size: 28rpx;
		        margin-top: 16rpx;
		        text-align: center;
		      }
		    }
		  }
		}
	}
</style>