<template>
  <view class="Scanning_Result">
    <view class="Scanning_top">
      <view class="Scanning_top_icon">
        <text :class="{ red: workOrder.gdState && workOrder.gdState.value == 4 }">{{workOrder.startDept ? workOrder.startDept.dept : ''}}</text>
        <text class="newicon newicon-arrow-right-full"></text>
        <text :class="{ red: workOrder.gdState && workOrder.gdState.value == 5 }">{{workOrder.endDeptNames || ''}}</text>
      </view>
    </view>

    <view class="Scanning_cont">
      <view class="column head">
        <view class="value1">单号<text class="red">（{{drugsBagList.length}}）</text></view>
        <view class="value2" v-if="config.showDrugsBagTypeCount == 1">种类数</view>
        <view class="value3" v-if="config.showDrugsBagTypeCount == 1">总数</view>
      </view>
      <scroll-view scroll-y class="scrollContent">
        <view class="column" v-for="item in drugsBagList" :key="item.id" @click="toDetail(item.id)">
          <view class="value1">{{item.packid}}</view>
          <view class="value2" v-if="config.showDrugsBagTypeCount == 1">{{item.drugsTypeCount}}</view>
          <view class="value3" v-if="config.showDrugsBagTypeCount == 1">{{item.drugsCount}}</view>
        </view>
      </scroll-view>
    </view>

    <view class="foot_btn_spe">
      <view class="column">
				<view v-if="config.drugsStartCheck==0 && workOrder.gdState.value == 4" class="btn" @click="checkSubmit()">确认交接</view>
        <view v-if="workOrder.gdState.value == 4 && config.drugsStartCheck==1" class="btn" @click="scanCode()">扫一扫交接</view>
				<view v-if="workOrder.gdState.value == 5 && config.drugsEndCheck==1" class="btn" @click="scanCode()">扫一扫交接</view>
				<view class="btn" @click="fillInManually(config.drugsStartManual.value)" v-if="workOrder.gdState && workOrder.gdState.value == 4 && config.drugsStartManual">{{config.drugsStartManual.name}}</view>
        <view class="btn" @click="fillInManually(config.drugsEndManual.value)" v-if="workOrder.gdState && workOrder.gdState.value == 5 && config.drugsEndManual">{{config.drugsEndManual.name}}</view>
      </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>
		<!-- 核对交接 -->
		<uni-popup ref="alertDialog" type="dialog" :mask-click="false">
			<uni-popup-dialog type="info" cancelText="取消" confirmText="确定" title="提示" content="是否核对完成？" @confirm="dialogConfirm"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</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,
        drugsBagList: [], //药包列表
        queryObj: {}, //路由传递过来的数据
        workOrder: {}, //工单信息
        config: {}, //配置
        SMFlag: true, //控制扫码
        // 填写交接人工号弹窗model
        hosModels: {
          disjunctor: false,
        },
        showKey:false,
        keyNum:4, //密钥位数
        isNumberKey:false, //是否开启动态密钥
        keyArr: [],
				checkDialog:false
      };
    },
    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.drugsBagType,
          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, type){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          "type": queryObj.drugsBagType,
          "orderId": workOrder.id,
          "handover": accountObj ? accountObj.id : undefined,
        };
        post('/transflow/checkComplete', postData).then(res => {
          uni.hideLoading();
          if(res.state == 200){
						if(type=='check'){
							this.$refs.alertDialog.close()
						}
            uni.showToast({
              icon: "none",
              title: workOrder.gdState.value == 4 ? "交接成功，请尽快送达科室！" : (workOrder.gdState.value == 5 ? "交接成功，完成配送！" : "交接成功"),
              duration: 2000,
              mask: true,
            });
						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 drugsBagType = queryObj.drugsBagType;
        let orderId = workOrder.id;
        if(workOrder.gdState.value == 4){
          // 待到达
          if(config.drugsStartPhoto === 1){
            // 起点科室支持拍照留存
            uni.navigateTo({
              url: `/pages/newDrug/photoRetention/photoRetention?drugsBagType=${drugsBagType}&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?drugsBagType=${drugsBagType}&orderId=${orderId}&accountId=${accountObj ? accountObj.id : ''}&accountName=${accountObj ? accountObj.name : ''}&accountDeptName=${departmentDTO ? departmentDTO.dept : ''}`,
            });
          }else{
            // 起点科室不支持拍照留存
            this.completeOrder(workOrder, queryObj, accountObj, "");
          }
        }
      },
			// 核对交接
			checkSubmit(){
				this.$refs.alertDialog.open()
			},
			// 确定核对交接
			dialogConfirm(){
				this.completeOrder(this.workOrder, this.queryObj, "", "check")
			},
			// 取消核对交接
			dialogClose(){
				this.$refs.alertDialog.close()
			},
      // 扫一扫交接
      scanCode(){
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((content) => {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });

          this.bigScan(content);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      // 详情
      toDetail(drugsBagId){
        uni.navigateTo({
          url: `/pages/newDrug/detail?drugsBagType=${this.queryObj.drugsBagType}&drugsBagId=${drugsBagId}`,
        });
      },
      // 扫码
      bigScan(content){
        let postData = {
          type: this.queryObj.drugsBagType,
          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: "接口获取数据失败！",
              });
            }
          });
      },
      // 初始化
      init(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });

        let info$ = post(`/transflow/extra`, {type: this.queryObj.drugsBagType, 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.drugsBagType
                    }
                }
            }
        });

        Promise.all([info$, config$]).then(result => {
          uni.hideLoading();
          let [info, config] = result || [];

          if(info.state == 200){
            if(info.data){
              this.drugsBagList = info.data.drugsBagList || [];
              if(Array.isArray(info.data.workOrder.endDepts)){
                info.data.workOrder.endDeptNames = info.data.workOrder.endDepts.map(v => v.dept).join();
              }
              this.workOrder = info.data.workOrder || {};
            }
          }else{
            uni.showToast({
              icon: "none",
              title: info.msg || "接口获取数据失败！",
            });
          }

          if(config.status == 200){
            let list  = config.list || [];
            this.config = list.length ? list[0] : {};
          }else{
            uni.showToast({
              icon: "none",
              title: config.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: 30rpx;
        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{
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        padding: 32rpx 24rpx;
        color: #565656;
        border-bottom: 1rpx solid #D9D9D9;
        gap: 8rpx;
        &.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%;
        height: 78rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 24rpx;

        .btn {
          height: 100%;
          flex: 1;
          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>
