<template>
  <view class="Scanning_Result">
    <view class="Scanning_top">
      <view class="Scanning_top_icon">
        <text v-if="workOrder.endDepts">{{workOrder.endDepts[0].dept}}签到—{{scanNum}}/{{totalNum}}</text>
      </view>
    </view>

    <view class="Scanning_cont">
      <scroll-view scroll-y class="scrollContent">
        <view class="column" v-for="item in specimenPackageList" :key="item.id">
          <view class="row bd">
            <view class="name">{{item.deptName}}</view>
            <view class="value" :class="[ item.sacnState === 0 ? 'red' : 'green']">{{item.sacnState === 0 ? '未扫描' : '已扫描'}}</view>
          </view>
          <view class="row">
            <view class="name">{{item.pack_code}}</view>
            <view class="value">{{item.count}}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="foot_btn_spe">
      <view class="column">
        <template v-if="!config.drugsEndManual">
          <view class="btnW100" v-if="scanNum != totalNum" @click="Scanning_again()">继续扫描</view>
          <view class="btnW100" v-if="scanNum == totalNum" @click="scanCode()">扫一扫交接</view>
        </template>

        <!-- 三个按钮-样式 -->
        <template v-else-if="config.drugsEndManual">
          <view class="btn" v-if="scanNum == totalNum" @click="scanCode()">扫一扫交接</view>
          <view class="btn" v-if="scanNum == totalNum" @click="fillInManually(config.drugsEndManual.value)">{{config.drugsEndManual.name}}交接</view>
          <view class="btnW100" v-if="scanNum != totalNum"  @click="Scanning_again()">继续扫描</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";
  export default {
    data() {
      return {
        hosId: uni.getStorageSync('userData').user.currentHospital.id,
        specimenPackageList: [], //标本包列表
        queryObj: {}, //路由传递过来的数据
        workOrder: {}, //工单信息
        config: {}, //配置
        SMFlag: true, //控制扫码
        // 填写交接人工号弹窗model
        hosModels: {
          disjunctor: false,
        },
        showKey:false,
        keyNum:4, //密钥位数
        isNumberKey:false, //是否开启动态密钥
        keyArr: [],
        totalNum: 0,//总数量
        scanNum: 0,//已扫描
      };
    },
    components: {
    	numberKeyModel,
    },
    onShow() {
      this.SMFlag = true;
    },
    methods: {
      // 获取配置
      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.pageNavigateByConfig(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 || "接口获取数据失败！",
              });
            }
          });
      },
      // 工单完成
      completeOrder(workOrder, queryObj, accountObj){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          "orderId": -1,
          "type": queryObj.packageType,
          "packageIds": this.specimenPackageList.map(v => v.packageId).toString(),
          "handover": accountObj ? accountObj.id : undefined,
        };
        post('/transflow/complete', 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 || "接口获取数据失败！",
            });
          }
        })
      },
      // 根据配置跳转页面
      pageNavigateByConfig(config, workOrder, queryObj, accountObj, departmentDTO){
        console.log(accountObj, departmentDTO);
        let packageType = queryObj.packageType;
        let orderId = workOrder.id;
        if(workOrder.gdState.value == 4){
          // 待到达
          if(config.drugsStartPhoto === 1){
            // 起点科室支持拍照留存
            uni.navigateTo({
              url: `/pages/newDrug/photoRetention/photoRetention?packageType=${packageType}&orderId=${orderId}&accountId=${accountObj ? accountObj.id : ''}&accountName=${accountObj ? accountObj.name : ''}&accountDeptName=${departmentDTO ? departmentDTO.dept : ''}`,
            });
          }else{
            // 起点科室不支持拍照留存
            this.completeOrder(workOrder, queryObj, accountObj);
          }
        }else if(workOrder.gdState.value == 5){
          // 待送达
          if(config.drugsEndPhoto === 1){
            // 起点科室支持拍照留存
            uni.navigateTo({
              url: `/pages/newDrug/photoRetention/photoRetention?packageType=${packageType}&orderId=${orderId}&accountId=${accountObj ? accountObj.id : ''}&accountName=${accountObj ? accountObj.name : ''}&accountDeptName=${departmentDTO ? departmentDTO.dept : ''}`,
            });
          }else{
            // 起点科室不支持拍照留存
            this.completeOrder(workOrder, queryObj, accountObj);
          }
        }
      },
      // 扫一扫交接
      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.pageNavigateByConfig(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: "接口获取数据失败！",
              });
            }
          });
      },
      // 继续扫描
      Scanning_again(isFlag = false) {
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((ress1) => {
          this.hand_scanning_common(ress1, 'scan', isFlag);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      // 手动输入和扫码公共方法
      hand_scanning_common(ress1, type, isFlag = false) {
        // ----------------
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        //检验二维码的有效性
        post("/dept/scanning", {
          content: ress1,
        }).then((result) => {
          this.SMFlag = true;
          if (result.state == 200 || result.state == 201) {
            let codes = result.code;
            if (codes) {
              this.input_common(ress1, type, isFlag);
            } else {
              uni.hideLoading();
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: result.info || "接口获取数据失败！",
            });
          }
        });
        // ------------------------------
      },
      // 录入到工单
      input_common(ress1, type, isFlag = false){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/transflow/scanBind", { type: this.queryObj.packageType, orderId: this.queryObj.orderId, code: ress1 }).then((ress) => {
          uni.hideLoading();
          if (ress.state == 200) {
            if(ress.data.msg){
              uni.showToast({
                icon: "none",
                title: ress.data.msg || "接口获取数据失败！",
              });
            }else{
              uni.redirectTo({
                url: `/pages/specimenPackage/checkPage/checkPage?packageType=${this.queryObj.packageType}&packageId=${ress.data.dto.id}&orderId=${this.queryObj.orderId}&scanOrHand=${type}`,
              });
            }
          } else {
            uni.showToast({
              icon: "none",
              title: ress.msg || "接口获取数据失败！",
            });
          }
        });
      },
      // 初始化
      init(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });

        let info$ = post(`/transflow/extra`, {type: this.queryObj.packageType, extraType: 'orderInfo', orderId: +this.queryObj.orderId, checkComplete: '1'});
        let config$ = post(`/simple/data/fetchDataList/taskTypeConfig`, {
            "idx": 0,
            "sum": 1,
            "taskTypeConfig": {
                "taskTypeDTO": {
                    "hosId": {
                        "id": this.hosId
                    },
                    "ordinaryField": {
                        "key": "ordinary_field",
                        "value": this.queryObj.packageType
                    }
                }
            }
        });

        Promise.all([info$, config$]).then(result => {

          let [info, config] = result || [];

          if(info.state == 200){
            if(info.data){
              this.workOrder = info.data.workOrder || {};
            }
          }else{
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: info.msg || "接口获取数据失败！",
            });
          }

          if(config.status == 200){
            let list  = config.list || [];
            this.config = list.length ? list[0] : {};
          }else{
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: config.msg || "接口获取数据失败！",
            });
          }

          post(`/nurse/specimen/getSpePackageScanCount`, {endDeptId: this.workOrder.endDepts[0].id}).then((ress) => {
            uni.hideLoading();
            if(ress.state == 200){
              this.specimenPackageList = ress.data || [];
              this.scanNum = this.specimenPackageList.filter(v => v.sacnState !== 0).length;
              this.totalNum = this.specimenPackageList.length;
            }else{
              uni.showToast({
                icon: "none",
                title: ress.msg || "接口获取数据失败！",
              });
            }
          });
        })
      },
    },
    onLoad(options) {
      console.log(options, "options");
      this.queryObj = options;
      this.init();
      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 24rpx;
    display: flex;
    flex-direction: column;
    height: 100vh;

    .Scanning_top {
      margin: 24rpx auto;
      .Scanning_top_icon {
        font-size: 38rpx;
        font-weight: bold;
        .newicon{
          margin: 0 32rpx;
        }
      }
    }

    .Scanning_cont {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
      .scrollContent{
        flex: 1;
        min-height: 0;
      }
      .column{
        font-size: 30rpx;
        padding: 24rpx;
        background: #FAFBFD;
        border: 1rpx solid #E1E1E1;
        margin-top: 16rpx;
        border-radius: 8rpx;
        .row{
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 24rpx;
          &:first-of-type{
            margin-top: 0;
          }
        }
        .bd{
          font-weight: bold;
        }
        &:first-of-type{
          margin-top: 0;
        }
        &.head{
          font-size: 30rpx;
          color: #000000;
          border: 1rpx solid #D9D9D9;
          box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0,0,0,0.16);
          background: #FBFCFE;
        }
        .value1{
          flex: 2;
          text-align: left;
          word-break: break-all;
          flex-shrink: 0;
        }
        .value2,.value3{
          flex: 1;
          text-align: center;
          word-break: break-all;
          flex-shrink: 0;
        }
      }
    }

    .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;

        .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>
