<template>
  <view class="checkAfterScanning">
    <view class="checkAfterScanning_title">标本核对</view>
    <view class="page_item_cont">
      <view class="page_item_cont_T">
        <view class="page_item_cont_title">
          <view> 工单单号 </view>
          <view class="text_big">{{info.gdCode}}</view>
        </view>
        <view class="page_item_cont_title">
          <view class="text_title"> 科室名称 </view>
          <view class="text_big">{{info.LCDept}}</view>
        </view>
        <view class="page_item_cont_title">
          <view> 扫描标本数量 </view>
          <view class="text_big" @click="goToSpeDetail()"><text class="underline">{{info.total}}</text>只</view>
        </view>
        <view class="page_item_cont_title2">
          检验科室标本数量：
        </view>
        <view class="page_item_cont_title" v-for="(item, i) in info.data" :key="i">
          <template v-if="taskTypeConfig.speExpandTube == 1">
            <uni-collapse :border="false">
              <uni-collapse-item titleBorder="none" :open="taskTypeConfig.speDefaultExpandTube == 1">
                <template v-slot:title>
                  <view class="page_item_cont_title_coll">
                    <view>{{item.deptName}}</view>
                    <view class="text_big" style="padding-right: 20rpx;" @click.stop="goToSpeDetail(item.deptName,item.deptQrCode)"><text class="underline">{{item.speCount}}</text>只</view>
                  </view>
                </template>
                <view class="content">
                  <view class="list" v-for="x in item.tubeTypeData" :key="x.id" @click="viewSpe(item.deptName,item.deptQrCode,x.tubeTypeId)">
                    {{x.tubeTypeName}}：<text class="underline-item">{{x.speCount}}</text>
                  </view>
                </view>
              </uni-collapse-item>
            </uni-collapse>
          </template>
          <template v-else>
            <view class="page_item_cont_title_coll" style="width: 100%;">
            	<view>{{item.deptName}}</view>
            	<view class="text_big" @click.stop="goToSpeDetail(item.deptName,item.deptQrCode)"><text class="underline">{{item.speCount}}</text>只</view>
            </view>
          </template>
        </view>
      </view>
    </view>
		<view class="foot_btn_spe" v-if="enterDynamicDigitalKey==0">
		  <view class="btn1" @click="Scanning_complete('scan')">核对完成</view>
		  <view class="btn3" @click="goBack">返回</view>
		</view>
		<view class="foot_btn_spe" v-if="enterDynamicDigitalKey==1">
			<view class="btn1" @click="Scanning_complete('scan')">扫码交接</view>
		  <view class="btn1" @click="isShowKey()">数字交接</view>
		  <view class="btn3" @click="goBack">返回</view>
		</view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      @ok="ok" @cancel="cancel" :operate="models.operate"></showModel>
    <!-- 弹窗 -->
    <showModel :title="models2.title" :icon="models2.icon" :disjunctor="models2.disjunctor" :content="models2.content"
      @ok="ok2" @know="know2" @cancel="cancel2" :operate="models2.operate"></showModel>
		<!-- 动态密钥 -->
		<numberKeyModel v-if="showKey" :keyArr="keyArr" @cancel="showKey = false" @confirm="confirmKey($event)"></numberKeyModel>
	</view>
</template>
<script>
  import {
    get,
    post,
    SM,
    webHandle
  } from "../../http/http.js";
	import numberKeyModel from "../../components/numberKeyModel/numberKeyModel.vue";
  export default {
    data() {
      return {
        taskTypeConfig: {},
        handoverId: undefined,
        handoverDeptId: undefined,
        info: {},
        wcFlag: false,
        queryObj: {}, //路由传递过来的数据
        // 弹窗model
        models: {
          disjunctor: false,
        },
        // 完成扫描弹窗model1
        models2: {
          disjunctor: false,
        },
				showKey:false,
				keyNum:4, //密钥位数
				isNumberKey:false, //是否开启动态密钥
				keyArr: [],
				enterDynamicDigitalKey:null,
				keyType:null,
				contentData:null,
      };
    },
		components: {
			numberKeyModel
		},
    methods: {
			viewSpe(deptName, qrCode, id){
				uni.navigateTo({
				  url: `../viewSpe/viewSpe?deptName=${deptName}&workOrderId=${encodeURIComponent(JSON.stringify([this.queryObj.id]))}&deptCode=${qrCode}&tubeTypeId=${id}&isScan=1&specimensCheck=1`,
				});
			},
			confirmKey(data){
				this.Scanning_complete('key')
				this.contentData = data
				this.showKey = false
			},
			isShowKey(){
				this.showKey = true
			},
			// 获取配置
			getConfig() {
				// 判断开关
				const userData = uni.getStorageSync("userData");
				let postData = {
					idx: 0,
					sum: 9999,
					hospitalConfig:{
						hosId:userData.user.currentHospital.id,
						model:"all"
					}
				};

				post("/simple/data/fetchDataList/hospitalConfig",postData).then((result) => {
						if (result.status == 200) {
							this.keyArr = []
							for(let i of result.list){
								if(i.key=='digitalSecretKey'){
									if(i.value==1){
										this.isNumberKey = true
									}else{
										this.isNumberKey = false
									}
								}else if(i.key=='numberDigitalSecretKey'){
									this.keyNum = Number(i.value)
								}
							}
							for(let i = 0; i < this.keyNum; i++){
								this.keyArr.push({
									value:null
								})
							}
						}
					});

			  uni.showLoading({
			    title: "加载中",
			    mask: true,
			  });
			  // 查询标本配送业务
			  post("/simple/data/fetchDataList/taskType",{
			      "idx": 0,
			      "sum": 10,
			      "taskType": {
			          "simpleQuery": true,
			          "hosId": {
			              "id": userData.user.currentHospital.id
			          },
			          "associationType": {
			              "key": "association_types",
			              "value": "specimen"
			          }
			      }
			  }).then((res) => {
			    if (res.status == 200) {
			      let taskTypeDTO = res.list[0];
			  		if(taskTypeDTO){
			        // 查询业务页面控制-标本
			        post("/simple/data/fetchDataList/taskTypeConfig",{
			            "idx": 0,
			            "sum": 10,
			            "taskTypeConfig": {
			              taskTypeDTO,
			            }
			        }).then((res) => {
			          if (res.status == 200) {
			            let data = res.list[0];
									uni.hideLoading();
			        		if(data){
                    this.taskTypeConfig = data || {};
										// 输入动态数字密钥
			              this.enterDynamicDigitalKey = data.enterDynamicDigitalKey
										console.log(55555,this.enterDynamicDigitalKey)
			            }
			          } else {
			            uni.hideLoading();
			            uni.showToast({
			              icon: "none",
			              title: res.msg || "接口获取数据失败！",
			            });
			          }
			        });
			      }else{
			        uni.hideLoading();
			      }
			    } else {
			      uni.hideLoading();
			      uni.showToast({
			        icon: "none",
			        title: res.msg || "接口获取数据失败！",
			      });
			    }
			  });
			},
      // 获取核对信息
      getInfo(gdId){
        uni.showLoading({
          title: '加载中',
          mask: true
        });
        post("/api/specimensCheck", {gdIds:gdId}).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            console.log(res)
            res.LCDept = res.LCDept.join('，');
            this.info = res;
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 返回
      goBack() {
        uni.navigateBack();
      },
      // 业务页面控制-标本-收取时需扫描二维码
      beforeScanning(fn) {
        this.handoverId = undefined;//扫动态码或静态码，后端会返回交接人，核对完成接口传过去
        this.handoverDeptId = undefined;//扫动态码或静态码，后端会返回科室，核对完成接口传过去
        // 判断开关
        const userData = uni.getStorageSync("userData");
        console.log('userData', userData);
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        // 查询标本配送业务
        post("/simple/data/fetchDataList/taskType",{
            "idx": 0,
            "sum": 10,
            "taskType": {
                "simpleQuery": true,
                "hosId": {
                    "id": userData.user.currentHospital.id
                },
                "associationType": {
                    "key": "association_types",
                    "value": "specimen"
                }
            }
        }).then((res) => {
          if (res.status == 200) {
            let taskTypeDTO = res.list[0];
        		if(taskTypeDTO){
              // 查询业务页面控制-标本
              post("/simple/data/fetchDataList/taskTypeConfig",{
                  "idx": 0,
                  "sum": 10,
                  "taskTypeConfig": {
                    taskTypeDTO,
                  }
              }).then((res) => {
                if (res.status == 200) {
                  let data = res.list[0];
              		if(data){
                    // 收取时需扫描二维码
                    if(data.arriveScanCode == 1){
                      // 扫描科室二维码
                      uni.hideLoading();
											if(this.keyType=='key'){
												let postData = {
													code: this.contentData,
													type: 'specimen',
													hosId: userData.user.currentHospital.id,
													orderId: +this.queryObj.id,
												};
												console.log(postData)
												uni.showLoading({
													title: "加载中",
													mask: true,
												});
												post("/workerOrder/arriveScanCheck", postData).then((res) => {
													uni.hideLoading();
													if (res.state == 200) {
														this.handoverId = res.handover;//扫动态码或静态码，后端会返回交接人，核对完成接口传过去
														this.handoverDeptId = res.handoverDeptId;//扫动态码或静态码，后端会返回科室，核对完成接口传过去
														fn();
													} else {
														uni.showToast({
															icon: "none",
															title: res.msg || "接口获取数据失败！",
														});
													}
												})
											}else{
												SM().then((content) => {
												  let postData = {
												    code: content,
												    type: 'specimen',
												    hosId: userData.user.currentHospital.id,
												    orderId: +this.queryObj.id,
												  };
												  console.log(postData)
												  uni.showLoading({
												    title: "加载中",
												    mask: true,
												  });
												  post("/workerOrder/arriveScanCheck", postData).then((res) => {
												    uni.hideLoading();
												    if (res.state == 200) {
												      this.handoverId = res.handover;//扫动态码或静态码，后端会返回交接人，核对完成接口传过去
												      this.handoverDeptId = res.handoverDeptId;//扫动态码或静态码，后端会返回科室，核对完成接口传过去
												      fn();
												    } else {
												      uni.showToast({
												        icon: "none",
												        title: res.msg || "接口获取数据失败！",
												      });
												    }
												  })
												}).catch(err => {

												});
											}
                    }else{
                      uni.hideLoading();
                      fn();
                    }
                  }else{
                    uni.hideLoading();
                    fn();
                  }
                } else {
                  uni.hideLoading();
                  uni.showToast({
                    icon: "none",
                    title: res.msg || "接口获取数据失败！",
                  });
                }
              });
            }else{
              uni.hideLoading();
              uni.showToast({
                icon: "none",
                title: "未查询到标本配送业务！",
              });
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });



      },
      // 完成核对
      Scanning_complete(type) {
				this.keyType = type
        this.beforeScanning(() => {
          if (
            this.queryObj.type1 == "plan-spe-ddd-2" ||
            this.queryObj.type1 == "spe-ddd-2"
          ) {
            this.wcFlag = true;
            this.models = {
              disjunctor: true,
              title: "提示",
              content: "是否确定标本已核对完成？",
              icon: "warn",
              operate: {
                ok: "确定",
                cancel: "取消",
              },
            };
          } else if (
            this.queryObj.type1 == "plan-spe-dsd-2" ||
            this.queryObj.type1 == "plan-spe-dsd-3" ||
            this.queryObj.type1 == "spe-dsd-2" ||
            this.queryObj.type1 == "spe-dsd-3"
          ) {
            this.wcFlag = false;
            this.models = {
              disjunctor: true,
              title: "提示",
              content: "是否确定标本已核对完成？",
              icon: "warn",
              operate: {
                ok: "确定",
                cancel: "取消",
              },
            };
          } else {
            this.gotoOver();
          }
        });
      },
      // 跳转完成工单页面
      gotoOver() {
        uni.navigateTo({
          url: `../scanning/scanning?type=${this.queryObj.type}&type1=${
            this.queryObj.type1
          }&id=${encodeURIComponent(JSON.stringify([this.queryObj.id]))}&deptCode=${
            this.queryObj.deptCode
          }&dept=${this.queryObj.dept}&speNum=${this.queryObj.speNum}&content=${this.queryObj.content}`,
        });
      },
      // 确定
      ok() {
        this.models.disjunctor = false;
        let postData = {
          ids: [this.queryObj.id],
          sign: true,
          deptQrCode: this.queryObj.deptCode
        };
        uni.showLoading({
          title: '加载中',
          mask: true
        });
        post("/workerOrder/expectedAndActual", postData).then((ress) => {
          uni.hideLoading();
          if (ress.status == 200) {
            if (this.wcFlag) {
              //正常完成扫描
              this.overFinish()
            } else {
              this.gotoOver();
            }
          } else if (ress.status == 1000035) {
            let content = '';
            if (this.queryObj.type1 === 'spe-ddd-2' || this.queryObj.type1 === 'plan-spe-ddd-2') {
              //待到达
              content =
                `系统内预计标本<strong class="red">${ress.expectReceiveNum}</strong>只，您扫描收取标本<strong class="red">${ress.actualReceiveNum}</strong>只，其中<strong class="red">${ress.notReceiveNum}</strong>只未扫描；`;
            } else {
              //待送达
              this.content =
                `本工单已签到<strong class="red">${ress.scanSet?ress.scanSet.join('、'):''}</strong>，剩余需签到科室<strong class="red">${ress.notScanSet?ress.notScanSet.join('、'):''}</strong>，总签收<strong class="red">${ress.totalAcceptance}</strong>只，剩余<strong class="red">${ress.notAcceptance}</strong>只未签收，您确定完成工单吗？`;
              content =
                `您在<strong class="red">${ress.deptName}</strong>检验科扫描了<strong class="red">${ress.deptScanNum}</strong>个标本，还需扫描<strong class="red">${ress.deptNotScanNum}</strong>标本。`;
            }
            // 取消弹窗 2022年10月10日
            this.ok2();
            // this.models2 = {
            //   disjunctor: true,
            //   title: "提示",
            //   content,
            //   icon: "warn",
            //   operate: {
            //     ok: "确定",
            //     cancel: "取消",
            //   },
            // };
          } else {
            uni.showToast({
              icon: "none",
              title: ress.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 取消
      cancel() {
        this.models.disjunctor = false;
      },
      // 确定
      ok2() {
        this.models2.disjunctor = false;
        let postData = {
          ids: [this.queryObj.id],
          deptQrCode: this.queryObj.deptCode
        };
        uni.showLoading({
          title: '加载中',
          mask: true
        });
        post("/workerOrder/expectedAndActual", postData).then((ress) => {
          uni.hideLoading();
          if (ress.status == 200) {
            if (this.wcFlag) {
              this.overFinish()
            } else {
              this.gotoOver();
            }
          } else {
            uni.showToast({
              icon: "none",
              title: ress.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 取消
      cancel2() {
        this.models2.disjunctor = false;
      },
      know2() {
        this.models2.disjunctor = false;
        uni.navigateTo({
          url: "../receiptpage/receiptpage",
        });
      },
      // 正常完成扫描
      overFinish() {
        let data = {
          type: this.queryObj.type1,
          ids: [this.queryObj.id],
        };
        //只要是标本轮巡1对多或者多对多
        // plan-spe-dsd-2  1对多
        // plan-spe-dsd-3  多对多
        if (
          this.queryObj.type1 === "plan-spe-ddd-2" ||
          this.queryObj.type1 === "plan-spe-dsd-2" ||
          this.queryObj.type1 === "plan-spe-dsd-3"
        ) {
          post("/workerOrder/finishPlanSpes", data).then((res) => {
            // uni.hideLoading()
            if (res.status == 200) {
              this.models2 = {
                disjunctor: true,
                title: "提示",
                content: `完成扫描成功`,
                icon: "success",
                operate: {
                  know: "返回",
                },
              };
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败！",
              });
            }
          });
        } else {
          data.handover = this.handoverId || undefined;
          data.handoverDeptId = this.handoverDeptId || undefined;
          post("/workerOrder/finishSpes", data).then((res) => {
            // uni.hideLoading()
            if (res.status == 200) {
              uni.navigateTo({
                url: "../receiptpage/receiptpage",
              });
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败！",
              });
            }
          });
        }
      },
      // 跳转到已扫描标本详情页
      goToSpeDetail(deptName='', qrCode=''){
        uni.navigateTo({
          url: `../noScanSpecimen/noScanSpecimen?deptName=${deptName}&workOrderId=${encodeURIComponent(JSON.stringify([this.queryObj.id]))}&deptCode=${qrCode}&isScan=1&specimensCheck=1`,
        });
      }
    },
    onLoad(options) {
      console.log(options);
      this.queryObj = options;
      this.getInfo(this.queryObj.id);
			this.getConfig();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
  };
</script>
<style lang="less" scoped>
	/deep/ .uni-collapse-item--border{
		border-bottom-color: #fff !important;
	}

	/deep/ .uni-collapse-item__title-arrow{
		margin-right: 0 !important;
	}

  .checkAfterScanning {
    .checkAfterScanning_title {
      padding: 50rpx 0;
      font-size: 46rpx;
      font-weight: 550;
      text-align: center;
      // border-bottom: 1px solid #ccc;
    }

    .page_item_cont {
      height: 73vh;
			overflow-y: auto;
      padding: 0 20rpx;
      text-align: left;
      position: relative;

      .text_title{
        flex-shrink: 0;
        margin-right: 16rpx;
      }

      .text_big {
        font-size: 32rpx;
        font-weight: 700;
        // margin-top: 10rpx;
      }

			.underline{
			  text-decoration: underline;
			}

			.underline-item{
				// text-decoration: underline;
				// margin-right: 40rpx;
			}

      .page_item_cont_T {
        padding-top: 28rpx;
        padding-bottom: 28rpx;
        font-size: 28rpx;
				background: #fff;
				border: 1px solid #CBCBCB;
				border-radius: 10rpx;
				padding: 20rpx;

        .page_item_cont_title {
          height: 100%;
          font-size: 32rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 10rpx;
					.content{
						display: flex;
						flex-wrap: wrap;
						.list{
							font-size: 28rpx;
							height: 60rpx;
							line-height: 60rpx;
							width: 50%;
							border-bottom: 1rpx solid #E6E6E6;
						}
					}
        }
        .page_item_cont_title2{
          margin-top: 36rpx;
          margin-bottom: 18rpx;
          height: 100%;
          font-size: 32rpx;
          font-weight: bold;
          display: flex;
          align-items: center;
        }
      }

			.page_item_cont_title_coll{
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-right: 8rpx;
			}

      .page_item_cont_B {
        padding-top: 28rpx;
        margin-bottom: 28rpx;

        .page_item_cont_title {
          font-size: 32rpx;
          display: flex;
          justify-content: space-between;
        }

        .page_item_cont_title1 {
          height: 60rpx;
          line-height: 60rpx;
          font-size: 32rpx;
          padding-left: 64rpx;
        }
      }
    }

    .foot_btn {
      line-height: 88rpx;
      height: 100rpx;
      margin-top: 40rpx;
      display: flex;
      justify-content: center;

      .btn1,
      .btn2,
      .btn3 {
        height: 88rpx;
        flex: 1;
        margin: 0 1%;
        background-image: linear-gradient(to right, #72c172, #3bb197);
        color: #fff;
        border-radius: 8rpx;
        font-size: 32rpx;
        margin-top: 16rpx;
        text-align: center;
      }
    }

    .foot_btn_spe {
      line-height: 88rpx;
      height: 100rpx;
      margin-top: 40rpx;
      text-align: center;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      &::after {
        content: '';
        flex: 1;
      }

      view {
        height: 88rpx;
        width: 48%;
        margin: 0 1%;
        background-image: linear-gradient(to right, #72c172, #3bb197);
        color: #fff;
        border-radius: 8rpx;
        font-size: 32rpx;
        margin-top: 16rpx;
      }
    }
  }
</style>
