<template>
  <view class="smallScreen">
    <view class="smallScreen_scan" @click="getInspectAndPatientTransform(sData,sType)">
      <slot></slot>
    </view>
    <!-- 填写交接人工号弹窗 -->
    <selectAccount v-if="hosModels.disjunctor" :disjunctor="hosModels.disjunctor" @ok="hosOk"
      @cancel="hosCancel">
    </selectAccount>
    <!-- 弹窗 -->
    <showModel :title="models4.title" :icon="models4.icon" :disjunctor="models4.disjunctor"
      :radioInspectionDistanceItem="models4.radioInspectionDistanceItem" @ok="ok4" @cancel="cancel4" @radioChange="radioChange4" :operate="models4.operate">
    </showModel>
  </view>
</template>

<script>
  import showModel from "../../components/showModel/showModel.vue";
  import selectAccount from "../../components/selectAccount/selectAccount.vue";
  import {
    post,
    SM
  } from "../../http/http.js";
  export default {
    data() {
      return {
        selectRadio: [], //单选框选中的数据，第一项是qrcode，第二项是名称
        // 单选框弹窗model1
        models4: {
          disjunctor: false,
        },
        hosId: uni.getStorageSync("userData").user.currentHospital.id,
        currentCode: '', //当前小扫描的科室二维码
        currentData: {}, //当前小扫描的工单对象
        // 填写交接人工号弹窗model
        hosModels: {
          disjunctor: false,
        },
        SMFlag:true,
      }
    },
    props: {
      sData: {
        type: Object
      },
      sType: {
        type: Number
      }
    },
    methods: {
      // 获取是否需要选择陪检方式
      getInspectAndPatientTransform(sData,sType){
        console.log(this.sData,this.sType);
        // 患者陪检，患者其他服务，工单状态是待到达
        if((this.sData.taskType.associationType.value === 'inspect' || this.sData.taskType.associationType.value === 'patientTransport') && this.sData.gdState.value == 4){
          const postData = {
            "idx":0,
            "sum":1,
            "taskTypeConfig":{
              "taskTypeDTO":{
                "hosId": {"id": this.hosId},
                "associationType": {
                  "key": "association_types",
                  "value":"inspect",
                },
              },
            },
          };
          uni.showLoading({
            mask: true,
            title: '加载中'
          })
          post("/simple/data/fetchDataList/taskTypeConfig", postData).then((res) => {
            console.log(res)
            if (res.status == 200) {
              res.list = res.list || [];
              if(res.list[0] && res.list[0].signTypeIds){
                // 如果开启
                const postData = {
                  "idx":0,
                  "sum":9999,
                  "workOrderInspectScore":{
                    "hosId": this.hosId,
                  },
                };
                post("/simple/data/fetchDataList/workOrderInspectScore", postData).then((res) => {
                  console.log(res)
                  uni.hideLoading();
                  if (res.status == 200) {
                    res.list = res.list || [];
                    let radioInspectionDistanceItem = res.list.map(v => ({id: v.id + "__" + v.inspectMode, inspectMode: v.inspectMode}));
                    console.log(radioInspectionDistanceItem)
                    this.models4 = {
                      disjunctor: true,
                      title: "请选择陪检方式",
                      radioInspectionDistanceItem,
                      icon: "",
                      operate: {
                        ok: "确定",
                        cancel: "取消",
                      },
                    };
                  } else {
                    uni.showToast({
                      icon: "none",
                      title: res.msg || "接口获取数据失败！",
                    });
                  }
                })
              }else{
                uni.hideLoading();
                this.Scan_ss(sData,sType);
              }
            } else {
              uni.hideLoading();
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败！",
              });
            }
          })
        }else{
          this.Scan_ss(sData,sType);
        }
      },
      // 选中单选框
      radioChange4(item) {
        console.log(item);
        this.selectRadio = item.split("__");
      },
      // 确定
      ok4() {
        console.log(this.selectRadio);
        if (!this.selectRadio.length) {
          return;
        }
        this.models4.disjunctor = false;
        this.Scan_ss(this.sData,this.sType);
      },
      cancel4() {
        this.models4.disjunctor = false;
      },
      // 如果不是静配，药配，标本配送,标本轮巡
      // 科室签到（小扫描）
      nextDeptOrder_ss(data, accountObj) {
        console.log(this.currentCode);
        let isKs = 0;
        let ids = [];
        let id = data.id;
        ids.push(id);
        let list = {
          code: "",
          ids: ids,
        };
        let code = "";
        let type = "";
        if (this.currentCode) {
          let gdStateValue = data.gdState.value; //工单状态value
          let associationTypeValue = data.taskType.associationType.value; //关联类型value
          // 患者陪检，并且工单状态是待到达
          if (
            gdStateValue == "4" &&
            associationTypeValue == "inspect"
          ) {
            list.code = this.currentCode; //其他
            type = "handleIns";
          }
          // 其他临床服务，并且工单状态是待到达||工单状态待送达
          if (
            (associationTypeValue == "other" &&
              gdStateValue == "4") ||
            gdStateValue == "5"
          ) {
            code = this.currentCode;
            type = "orderSign/" + code;
            list = {
              ids
            };
            if (accountObj) {
              list.handover = [accountObj.accountId];
            }
            isKs = 1;
          }
          if (
            (gdStateValue == "5" &&
              associationTypeValue == "inspect") ||
            associationTypeValue == "patientTransport"
          ) {
            code = this.currentCode;
            type = "orderSign/" + code;
            list = {
              ids
            };
            if (accountObj) {
              list.handover = [accountObj.accountId];
            }
            isKs = 1;
          }
          if (gdStateValue == "8") {
            code = this.currentCode; //患者陪检--检查
            type = "orderSign/" + code;
            list = {
              ids
            };
            if (accountObj) {
              list.handover = [accountObj.accountId];
            }
            isKs = 1;
          }
          if (
            gdStateValue == "4" &&
            associationTypeValue == "patientTransport"
          ) {
            list = {
              code: this.currentCode, //患者转运--检查
              ids: ids,
            };
            type = "handleTrans";
          }
          if(gdStateValue == "4" && (associationTypeValue == "inspect" || associationTypeValue == "patientTransport")){
            console.log(this.selectRadio)
            list.inspectMode = this.selectRadio.length > 0 ? this.selectRadio[0] : undefined;
          }
					console.log('type=====>',type)
          post("/workerOrder/" + type, list).then((res) => {
            uni.hideLoading();
            if (res) {
              if (res.status == 200) {
								
                if (gdStateValue == "4" && associationTypeValue == "other") {
                  uni.navigateTo({
                    url: `../../pages/scanning_code/scanning_code?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
                  });
                }
                if (gdStateValue == "4" && associationTypeValue != "other") {
                  if(associationTypeValue == 'patientTransport'){
                    // 门诊服务点,有orderList
                    if(res.orderList){
                      uni.navigateTo({
                        url: `/pages/outpatient/outpatientStartSignIn/outpatientStartSignIn?model=${encodeURIComponent(JSON.stringify(res))}`,
                      });
                    }else{
                      uni.navigateTo({
                        url: `../../pages/scanning_Result/scanning_Result?type=${
                        associationTypeValue
                      }&type1=${res.type}&id=${data.id}&deptCode=${
                        list.code
                      }&patient=${res.patient}&patientCode=${
                        res.patientCode
                      }&deptName=${res.deptName}&bedNum=${
                        res.bedNum
                      }&status=${res.status}&msg=${
                        res.msg
                      }&taskTypeId=${data.taskType.id}&model=${
												encodeURIComponent(JSON.stringify(res))}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
                      });
                    }
                  }else{
                    uni.navigateTo({
                      url: `../../pages/scanning_Result/scanning_Result?type=${
                      associationTypeValue
                    }&type1=${res.type}&id=${data.id}&deptCode=${
                      list.code
                    }&patient=${res.patient}&patientCode=${
                      res.patientCode
                    }&deptName=${res.deptName}&bedNum=${
                      res.bedNum
                    }&status=${res.status}&msg=${
                      res.msg
                    }&taskTypeId=${data.taskType.id}&model=${
											encodeURIComponent(JSON.stringify(res))}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
                    });
                  }
                }
                if (gdStateValue == "8") {
                  uni.navigateTo({
                    url: `../../pages/scanning_code/scanning_code?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
                  });
                }
                if (gdStateValue == "5") {
                  uni.navigateTo({
                    url: `../../pages/scanning_code/scanning_code?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
                  });
                }
              } else {
                console.log(res, "扫描失败");
                if (res.type == "trans-ddd-1") {
                  //起点科室扫描腕带码失败
                  uni.navigateTo({
                    url: `../../pages/scanning_Result/scanning_Result?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&status=600&msg=${res.msg}&qrcode=${this.currentCode}`,
                  });
                } else {
                  uni.navigateTo({
                    url: `../../pages/scanning_Result/scanning_Result?type=${
                    associationTypeValue
                  }&type1=${res.type}&id=${data.id}&status=600&msg=${
                    res.msg
                  }&isKs=${isKs}&model=${encodeURIComponent(
                    JSON.stringify(res)
                  )}&qrcode=${this.currentCode}`,
                  });
                }
              }
            } else {
              uni.navigateTo({
                url: `../../pages/scanning_Result/scanning_Result?id=${data.id}&status=600&msg=扫码失败！请扫描正确的二维码！&isKs=${isKs}&qrcode=${this.currentCode}`,
              });
            }
          });
        }
      },
      // 如果不是患者陪检或患者转运或其他
      // 科室签到
      nextDeptOrder_s(data, accountObj) {
        console.log(this.currentCode);
        let ids = [];
        let id = data.id;
        ids.push(id);
        let code = "";
        let postData = {
          ids
        };
        if (accountObj) {
          postData.handover = [accountObj.accountId];
        }
        if (this.currentCode) {
          code = this.currentCode;
          // 科室签到
          post("/workerOrder/orderSign/" + code, postData).then((res) => {
            uni.hideLoading();
            if (res.status == 200) {
              // 跳转到扫描科室
              // type1: res.type, //type类型
              // id: data.id, //工单ID
              // deptCode: code, //二维码
              // dept: res.dept //科室名称
              console.log(data,'工单')
              let endDepts = data.endDepts.map(v=>v.id).toString();
              console.log(endDepts,'smallScreen');
              uni.navigateTo({
                url: `../../pages/scanning_code/scanning_code?type=${data.taskType.associationType.value}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}&deptId=${res.deptId}&endDepts=${endDepts}`,
              });
            } else {
              uni.navigateTo({
                url: `../../pages/scanning_Result/scanning_Result?type=${data.taskType.associationType.value}&type1=${res.type}&id=${data.id}&status=600&msg=${res.msg}&isKs=1&qrcode=${this.currentCode}`,
              });
            }
          });
        }
      },
      // type==1  如果不是静配，药配，标本配送,标本轮巡
      // type==2  如果不是患者陪检，患者转运，其他
      // 扫码（小扫描）
      Scan_ss(data, type) {
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        this.currentData = data;
        console.log(data, 'data');
				// let ress1 = '123456'
        SM().then((ress1) => {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
          //检验二维码的有效性
          post("/dept/scanning", {
            content: ress1,
            taskTypeId: data.taskType.id,
            gdState: data.gdState.id,
          }).then((result) => {
            this.SMFlag = true;
            this.currentCode = result.code;
            if (result.state == 200 || result.state == 201) {
              if (result.account) {
                if (type == 1) {
                  this.isOpenTransportationProcessRemarks(this.currentData, {
                    account: result.account,
                    accountName: result.name,
                    accountId: result.id,
                  }, 'nextDeptOrder_ss');
                } else if (type == 2) {
                  this.nextDeptOrder_s(this.currentData, {
                    account: result.account,
                    accountName: result.name,
                    accountId: result.id,
                  });
                }
              } else {
                if (type == 1) {
                  this.isOpenTransportationProcessRemarks(this.currentData, undefined, 'nextDeptOrder_ss');
                } else if (type == 2) {
                  this.nextDeptOrder_s(this.currentData);
                }
              }
            } else if (result.state == '0000') {
              uni.hideLoading();
              this.showSelectAccount(); //yeye
            } else {
              uni.hideLoading();
              uni.showToast({
                icon: "none",
                title: result.info || "接口获取数据失败！",
              });
            }
          });
        }).catch(err=>{
          this.SMFlag = true;
        });
      },
      // 填写交接人工号-确认
      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;
        let associationTypeValue = this.currentData.taskType.associationType.value;
        console.log(associationTypeValue)
        if (
          associationTypeValue !== "patientTransport" &&
          associationTypeValue !== "inspect" &&
          associationTypeValue !== "other"
        ) {
          this.nextDeptOrder_s(this.currentData, data);
        }
        if (
          associationTypeValue !== "jPBag" &&
          associationTypeValue !== "drugsBag" &&
          associationTypeValue !== "specimen" &&
          associationTypeValue !== "specimenPlan"
        ) {
          this.isOpenTransportationProcessRemarks(this.currentData, data, 'nextDeptOrder_ss');
        }
      },
      // 填写交接人工号-取消
      hosCancel() {
        this.hosModels.disjunctor = false;
      },
      // 填写交接人工号弹窗
      showSelectAccount() {
        this.hosModels = {
          disjunctor: true,
        }
      },
      // 其他临床服务-运输过程-终点科室是否开通备注填写
      isOpenTransportationProcessRemarks(data, accountObj, funName){
        const tasktype = data.taskType;
        console.log(tasktype, data);
        if(tasktype.associationType.value === 'other' && tasktype.carryingCourses[1].logSwitch && data.gdState.value == 5){
          uni.navigateTo({
            url: `../../pages/transportationProcessRemarks/transportationProcessRemarks?data=${data ? encodeURIComponent(JSON.stringify(data)) : ''}&accountObj=${accountObj ? encodeURIComponent(JSON.stringify(accountObj)) : ''}&currentCode=${this.currentCode}&funName=${funName}&actions=${this.actions ? encodeURIComponent(JSON.stringify(this.actions)) : ''}&imageValue=${this.imageValue ? encodeURIComponent(JSON.stringify(this.imageValue)) : ''}`
          })
        }else{
          this[funName](data, accountObj);
        }
      },
    },
    components: {
      selectAccount
    },
    onShow(){
      this.SMFlag = true;
    },
  };
</script>

<style lang="less">
  .smallScreen {
    width: 100%;
    height: 100%;

    .smallScreen_scan {
      width: 100%;
      height: 100%;
    }
  }
</style>
