<template>
  <view class="Scanning_Result">
    <view class="Scanning_top">
      <view class="Scanning_top_icon">
        <text class="cubeic-ok newicon newicon-duigou"></text>
      </view>
      <view class="ScanTips">扫描成功</view>
    </view>

    <view class="Scanning_cont">
      <scroll-view scroll-y class="scrollContent">
        <view class="column">
          <view class="name">打包单号：</view>
          <view class="value">{{specimenPackageDTO.packCode}}</view>
        </view>
        <view class="column">
          <view class="name">打包科室：</view>
          <view class="value">{{specimenPackageDTO.packDeptDTO ? specimenPackageDTO.packDeptDTO.dept : ''}}</view>
        </view>
        <view class="column">
          <view class="name">终点科室：</view>
          <view class="value">{{specimenPackageDTO.targetDeptDTO ? specimenPackageDTO.targetDeptDTO.dept : ''}}</view>
        </view>
        <view class="column">
          <view class="name">检验科室：</view>
          <view class="value">
            <template v-if="specimenPackageDTO.endDeptList">
              <view class="valueBlock" v-for="item of specimenPackageDTO.endDeptList" :key="item.id">
                {{item.dept}}
              </view>
            </template>
          </view>
        </view>
        <view class="column">
          <view class="name">标本数：</view>
          <view class="value">{{specimenPackageDTO.specimenNum}}</view>
        </view>
        <view class="column">
          <view class="name">试管类型：</view>
          <view class="value">
            <view class="valueBlock" v-for="tube2 of tube" :key="tube2.id">
              <view class="valueItem" v-for="item of tube2" :key="item.id">{{item.name}}：{{item.size}}</view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="foot_btn_spe" v-if="config.id">
      <view class="column">
        <!-- 需要核对 -->
        <template v-if="(queryObj.type === 'build' || queryObj.type === 'receive') && (config.drugsCreateSign === 1 || config.drugsReceiveSign === 1) && config.drugsStartCheck === 1">
          <!-- 两个按钮-样式 设计如此，别BB -->
          <template v-if="!config.drugsStartManual">
            <view class="btn" @click="goIndex()">返回</view>
            <view class="btn" @click="createOrBuildOrder(undefined, 'scan')" v-if="queryObj.type === 'build' && config.drugsCreateSign === 1">建单签到扫一扫</view>
            <view class="btn" @click="createOrBuildOrder(undefined, 'hand')" v-if="queryObj.type === 'build' && config.drugsCreateSign === 1 && config.drugsStartManual">建单签到{{config.drugsStartManual.name}}</view>
            <view class="btn" @click="createOrBuildOrder(orderId, 'scan')" v-if="queryObj.type === 'receive' && config.drugsReceiveSign === 1">接单签到扫一扫</view>
            <view class="btn" @click="createOrBuildOrder(orderId, 'hand')" v-if="queryObj.type === 'receive' && config.drugsReceiveSign === 1 && config.drugsStartManual">接单签到{{config.drugsStartManual.name}}</view>
          </template>
          
          <!-- 三个按钮-样式 设计如此，别BB -->
          <template v-else>
            <view class="btn" @click="createOrBuildOrder(undefined, 'scan')" v-if="queryObj.type === 'build' && config.drugsCreateSign === 1">建单签到扫一扫</view>
            <view class="btn" @click="createOrBuildOrder(undefined, 'hand')" v-if="queryObj.type === 'build' && config.drugsCreateSign === 1 && config.drugsStartManual">建单签到{{config.drugsStartManual.name}}</view>
            <view class="btn" @click="createOrBuildOrder(orderId, 'scan')" v-if="queryObj.type === 'receive' && config.drugsReceiveSign === 1">接单签到扫一扫</view>
            <view class="btn" @click="createOrBuildOrder(orderId, 'hand')" v-if="queryObj.type === 'receive' && config.drugsReceiveSign === 1 && config.drugsStartManual">接单签到{{config.drugsStartManual.name}}</view>
            <view class="btnW100 grayBg" @click="goIndex()">返回</view>
          </template>
        </template>
        <!-- 不需要核对 -->
        <template  v-if="(queryObj.type === 'build' || queryObj.type === 'receive') && config.drugsStartCheck !== 1">
          <view :class="((queryObj.type === 'build' && config.drugsCreateSign === 1) || (queryObj.type === 'receive' && config.drugsReceiveSign === 1)) ? 'btn' : 'btnW100'" @click="goIndex()">返回</view>
          <view class="btn" @click="createOrBuildOrder()" v-if="queryObj.type === 'build' && config.drugsCreateSign === 1">建单并签到</view>
          <view class="btn" @click="createOrBuildOrder(orderId)" v-if="queryObj.type === 'receive' && config.drugsReceiveSign === 1">接单并签到</view>
        </template>
        <!-- 查看 -->
        <template v-if="queryObj.type === 'view'">
          <view class="btnW100" @click="goIndex()">返回</view>
        </template>
        <!-- 终点科室核对 -->
        <template v-if="queryObj.type === 'end'">
          <view class="btn" @click="goIndex()">返回</view>
          <view class="btn" @click="toCheckPage()">批量交接</view>
        </template>
        
      </view>
    </view>
    <!-- 填写交接人工号弹窗 -->
    <selectAccount @click.stop.native v-if="hosModels.disjunctor" :disjunctor="hosModels.disjunctor" @ok="hosOk"
      @cancel="hosCancel">
    </selectAccount>
    <!-- 动态密钥 -->
    <numberKeyModel v-if="showKey" :keyArr="keyArr" @cancel="showKey = false" @confirm="confirmKey($event)"></numberKeyModel>
  </view>
</template>
<script>
  import numberKeyModel from "@/components/numberKeyModel/numberKeyModel.vue";
  import {
    get,
    post,
    SM,
    webHandle
  } from "@/http/http.js";
  import chunk from 'lodash-es/chunk'
  export default {
    data() {
      return {
        queryObj: {}, //路由传递过来的数据
        specimenPackageDTO: {}, //标本包信息
        config: {}, //药品的业务流程配置
        orderId: undefined, //根据药包查询到的工单ID
        tube: [],//试管类型
        SMFlag: true, //控制扫码
        workOrder: {}, //工单信息
        // 填写交接人工号弹窗model
        hosModels: {
          disjunctor: false,
        },
        showKey:false,
        keyNum:4, //密钥位数
        isNumberKey:false, //是否开启动态密钥
        keyArr: [],
      };
    },
    components: {
    	numberKeyModel,
    },
    onShow() {
      this.SMFlag = true;
    },
    methods: {
      // 返回
      goIndex(){
       uni.redirectTo({
         url: `/pages/receiptpage/receiptpage`,
       });
      },
      // 批量交接
      toCheckPage(){
       uni.redirectTo({
         url: `/pages/specimenPackage/checkPage/checkPage?packageType=${this.queryObj.packageType}&packageId=${this.queryObj.packageId}&orderId=${this.queryObj.orderId}`,
       });
      },
      // 根据配置跳转页面
      pageNavigateByConfig(config, responseData, queryObj, checkType){
        let packageType = queryObj.packageType;
        let orderId = responseData.orderId;
        let packageId = queryObj.packageId;
        let orderStateValue = responseData.orderStateValue;
        if(config.spePackageModel === 1){
          // 一单一包
          if(responseData.orderStateValue == 4){
            // 待到达
            if(config.drugsStartCheck === 1){
              // 起点科室支持核对
              if(checkType === 'scan'){
                // 扫码
                this.scanCode();
              }else if(checkType === 'hand'){
                // 手动输入
                this.fillInManually(config.drugsStartManual.value);
              }
            }else{
              // 起点科室不支持核对
              this.completeOrder(responseData, queryObj);
            }
          }
        }
      },
      // 扫一扫交接
      scanCode(){
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((content) => {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
      
          this.bigScan(content);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      // 扫码
      bigScan(content){
        let postData = {
          type: this.queryObj.packageType,
          orderStateValue: this.workOrder.gdState.value,
          code: content,
          orderId: this.workOrder.id,
        }
      
        post("/transflow/bigScan", postData)
          .then((res) => {
            this.SMFlag = true;
            uni.hideLoading();
            if (res.codeBean) {
              if(res.codeBean.valid){
                this.pageCheckNavigateByConfig(this.config, this.workOrder, this.queryObj, res.codeBean.userDTO, res.codeBean.departmentDTO);
              }else{
                uni.showToast({
                  icon: "none",
                  title: res.codeBean.msg || "接口获取数据失败！",
                });
              }
            } else {
              uni.showToast({
                icon: "none",
                title: "接口获取数据失败！",
              });
            }
          });
      },
      // 获取配置
      getConfig() {
        let postData = {
          idx: 0,
          sum: 9999,
      		hospitalConfig:{
      			hosId:this.hosId,
      			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
      					})
      				}
      				console.log(444,this.keyArr)
            }
          });
      },
      confirmKey(data){
      	this.padChange(data)
      	this.showKey = false
      },
      isShowKey(){
      	this.showKey = true
      },
      padChange(scannerCode){
        if(!this.isNumberKey){
        	scannerCode = scannerCode.replace('\n','')
        }
        this.bigScan(scannerCode);
      },
      // 手动填写
      fillInManually(value){
        if(value == 1){
          // 填写工号
          this.showSelectAccount();
        }else if(value == 2){
          // 动态密钥
          this.isShowKey();
        }
      },
      // 填写交接人工号-确认
      hosOk(data) {
        console.log(data);
        const {
          accountName,
          account,
          accountId
        } = data;
        if (!accountName && !account) {
          //没有填写交接人
          uni.showModal({
            title: "提示",
            content: "请填写交接人工号！",
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          return;
        } else if ((!accountName && account) || (accountName && !account)) {
          //没有填写交接人
          uni.showModal({
            title: "提示",
            content: "请填写正确的交接人工号！",
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          return;
        }
        this.hosModels.disjunctor = false;
        this.validateAccount(data);
      },
      // 填写交接人工号-取消
      hosCancel() {
        this.hosModels.disjunctor = false;
        this.flag = true;
      },
      // 填写交接人工号弹窗
      showSelectAccount() {
        this.hosModels = {
          disjunctor: true,
        };
      },
      // 手动填写工号校验
      validateAccount(accountObj){
        const {
          accountName,
          account,
          accountId
        } = accountObj;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
      
        let postData = {
          extraType: 'inputAccountValid',
          type: this.queryObj.packageType,
          orderStateValue: this.workOrder.gdState.value,
          userId: accountId,
          orderId: this.workOrder.id,
        }
      
        post("/transflow/extra", postData)
          .then((res) => {
            uni.hideLoading();
            if(res.state == 200){
              if(res.data){
                if (res.data.codeBean) {
                  if(res.data.codeBean.valid){
                    this.pageCheckNavigateByConfig(this.config, this.workOrder, this.queryObj, { id: accountId, name: accountName }, res.data.codeBean.departmentDTO);
                  }else{
                    uni.showToast({
                      icon: "none",
                      title: res.data.codeBean.msg || "接口获取数据失败！",
                    });
                  }
                } else {
                  uni.showToast({
                    icon: "none",
                    title: "接口获取数据失败！",
                  });
                }
              }else{
                uni.showToast({
                  icon: "none",
                  title: "接口获取数据失败！",
                });
              }
            }else{
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败！",
              });
            }
          });
      },
      // 核对-根据配置跳转页面
      pageCheckNavigateByConfig(config, workOrder, queryObj, accountObj, departmentDTO){
        console.log(accountObj, departmentDTO);
        let packageType = queryObj.packageType;
        let orderId = workOrder.id;
        this.completeCheckOrder(workOrder, queryObj, accountObj);
      },
      // 核对-工单完成
      completeCheckOrder(workOrder, queryObj, accountObj){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          "type": queryObj.packageType,
          "orderId": workOrder.id,
          "packageId": +this.queryObj.packageId,
          "handover": accountObj ? accountObj.id : undefined,
        };
        post('/transflow/checkComplete', postData).then(res => {
          uni.hideLoading();
          if(res.state == 200){
            uni.showToast({
              icon: "none",
              title: workOrder.gdState.value == 4 ? "交接成功，请尽快送达科室！" : (workOrder.gdState.value == 5 ? "交接成功，完成配送！" : ""),
              duration: 60000,
              mask: true,
              complete(){
                setTimeout(() => {
                  uni.hideToast();
                  uni.redirectTo({
                    url: `/pages/receiptpage/receiptpage`,
                  });
                }, 2000)
              }
            });
          }else{
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 工单完成
      completeOrder(responseData, queryObj){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          "type": queryObj.packageType,
          "packageId": +this.queryObj.packageId,
          "orderId": responseData.orderId,
        };
        post('/transflow/checkComplete', postData).then(res => {
          uni.hideLoading();
          if(res.state == 200){
            uni.showToast({
              icon: "none",
              title: responseData.orderStateValue == 4 ? "交接成功，请尽快送达科室！" : (responseData.orderStateValue == 5 ? "交接成功，完成配送！" : ""),
              duration: 60000,
              mask: true,
              complete(){
                setTimeout(() => {
                  uni.hideToast();
                  uni.redirectTo({
                    url: `/pages/receiptpage/receiptpage`,
                  });
                }, 2000)
              }
            });
          }else{
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 建单并签到/接单并签到-orderId
      // 扫码scan/手动hand-checkType
      createOrBuildOrder(orderId, checkType){
        uni.showModal({
          title: "提示",
          content: `请确认是否${orderId ? '接' : '建'}单并签到？`,
          success: (result) => {
            if (result.confirm) {
              console.log("用户点击确定");
              let postData = {
                type: this.queryObj.packageType,
                id: +this.queryObj.packageId,
                orderId,
              };
              uni.showLoading({
                title: "加载中",
                mask: true,
              });
              post(`/transflow/createOrTakeOrder`, postData).then((ress) => {
                uni.hideLoading();
                if (ress.state == 200) {
                  if(ress.data.msg){
                    if(ress.data.state == 502){
                      // 工单已建单，返回列表
                      uni.showToast({
                        icon: "none",
                        mask: true,
                        title: ress.data.msg,
                      });
                      setTimeout(() => {
                        uni.redirectTo({
                          url: `/pages/receiptpage/receiptpage`,
                        });
                      },300)
                    }else{
                      uni.showToast({
                        icon: "none",
                        title: ress.data.msg || "接口获取数据失败！",
                      });
                    }
                  }else{
                    this.workOrder = {
                      id: ress.data.orderId,
                      gdState: {
                        value: ress.data.orderStateValue,
                      },
                    };
                    console.log('workOrder', this.workOrder);
                    this.pageNavigateByConfig(this.config, ress.data, this.queryObj, checkType);
                  }
                } else {
                  uni.showToast({
                    icon: "none",
                    title: ress.msg || "接口获取数据失败！",
                  });
                }
              });
            } else if (result.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      },
      //获取页面信息
      getInfo(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });

        post(`/transflow/scanInfo`, {type: this.queryObj.packageType, id: +this.queryObj.packageId, orderStateValue: this.queryObj.type === 'end' ? '5' : '4'}).then(res => {
          uni.hideLoading();
          if(res.state == 200){
            if(res.data){
              this.specimenPackageDTO = res.data.dto || {};
              this.orderId = this.queryObj.orderId;
              this.config = res.data.taskTypeConfig || {};
              let tube = res.data.tube || [];
              this.tube = chunk(tube, 2);
            }
          }else{
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
    },
    onLoad(options) {
      console.log(options, "options");
      this.queryObj = options;
      this.getInfo();
      this.getConfig();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
  };
</script>
<style lang="less" scoped>
  .Scanning_Result {
    background: #FAFBFD;
    padding: 0 48rpx;
    display: flex;
    flex-direction: column;
    height: 100vh;

    .Scanning_top {
      margin: 50rpx auto 64rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .Scanning_top_icon {
        width: 128rpx;
        height: 128rpx;
        border-radius: 50%;

        .cubeic-ok {
          font-size: 128rpx;
          color: #35b34a;
        }
      }
      .ScanTips{
        margin-top: 34rpx;
        font-size: 38rpx;
        font-weight: bold;
      }
    }

    .Scanning_cont {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
      .scrollContent{
        flex: 1;
        min-height: 0;
      }
      .column{
        display: flex;
        justify-content: center;
        font-size: 30rpx;
        margin-bottom: 32rpx;
        .name{
          font-weight: bold;
          word-break: break-all;
          flex-shrink: 0;
        }
        .value{
          word-break: break-all;
          flex: 1;
          .valueBlock{
            margin-top: 16rpx;
            display: flex;
            &:first-of-type{
              margin-top: 0;
            }
            .valueItem{
              flex: 1;
            }
          }
        }
      }
    }

    .foot_btn_spe {
      margin: 24rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 24rpx;
      font-weight: bold;

      .column{
        width: 100%;
        display: flex;
        justify-content: space-between;
        gap: 24rpx;
        flex-wrap: wrap;
        
        .grayBg{
          background: #8F939C!important;
        }

        .btn {
          height: 78rpx;
          width: calc(50% - 24rpx);
          background: linear-gradient( 90deg, #6FC073 0%, #3DB197 100%);
          color: #fff;
          border-radius: 4rpx;
          font-size: 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .btnW100 {
          height: 78rpx;
          width: 100%;
          background: linear-gradient( 90deg, #6FC073 0%, #3DB197 100%);
          color: #fff;
          border-radius: 4rpx;
          font-size: 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
</style>
