<template>
  <view class="transferWorkOrder">
    <!-- <mSearch class="search" :mode="2" button="inside" placeholder="请搜索患者名称、住院号" @search="doSearch()" v-model="keyword" searchButtonType="icon" searchButtonName="newicon-saoma"></mSearch> -->
    <scroll-view scroll-y class="list">
      <view class="item tac"><text class="green">患者回科清单</text></view>
      <view class="item" v-for="(item, index) in listComputed" :key="item.id" @click="selectItem(item)">
        <view>{{item.patientName}}({{item.bedNum}})-{{item.patientCode}}</view>
        <text class="right-icon newicon newicon-lajitong" @click="deleteIt(item, index)"></text>
      </view>
    </scroll-view >
    <view class="footer">
      <template v-if="list.length">
        <view class="primaryButton btn gray" hover-class="seimin-btn-hover" @click="tagClick()" v-if="!config.batchPatientCheckType">确认回科</view>
        <template v-if="config.batchPatientCheckType == 1 || config.batchPatientCheckType == 2">
          <view class="primaryButton btn gray" hover-class="seimin-btn-hover" @click="scanCode()">扫一扫</view>
          <view class="primaryButton btn gray" hover-class="seimin-btn-hover" @click="fillInManually(2)" v-if="isNumberKey && config.batchPatientDynamicKey == 1">动态密钥</view>
        </template>
        <view class="primaryButton btn gray" hover-class="seimin-btn-hover" @click="fillInManually(1)" v-if="config.batchPatientCheckType == 3">工号确认</view>
      </template>
      <view class="btn gray" hover-class="seimin-btn-hover" @click="goBack()">返回</view>
    </view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content" :operate="models.operate" @ok="ok" @cancel="cancel"></showModel>
    <!-- 弹窗 -->
    <showModel :title="models1.title" :icon="models1.icon" :disjunctor="models1.disjunctor" :content="models1.content" :operate="models1.operate" @ok="ok1" @cancel="cancel1"></showModel>
    
    <!-- 动态密钥 -->
    <numberKeyModel v-if="showKey" :keyArr="keyArr" @cancel="showKey = false" @confirm="confirmKey($event)"></numberKeyModel>
    
    <!-- 填写交接人工号弹窗 -->
    <selectAccount @click.stop.native v-if="hosModels.disjunctor" :disjunctor="hosModels.disjunctor" @ok="hosOk" @cancel="hosCancel"></selectAccount>
  </view>
</template>

<script>
  import { get, post, SM, webHandle } from "../../http/http.js";
  import mSearch from "@/components/mehaotian-search-revision/mehaotian-search-revision.vue";
  import numberKeyModel from "@/components/numberKeyModel/numberKeyModel.vue";
  export default {
    onShow() {
      this.SMFlag = true;
    },
    onLoad(options) {
      console.log('options', options);
      this.options = options || {};
      this.deptId = +options.deptId;
      this.list = JSON.parse(options.patientList);
      console.log(this.list);
      this.getConfig();
      this.getConfig1();
    },
    components: {
      //引用mSearch组件，如不需要删除即可
      mSearch,
      numberKeyModel,
    },
    data() {
      return {
        // 填写交接人工号弹窗model
        hosModels: {
          disjunctor: false,
        },
        showKey:false,
        keyNum:4, //密钥位数
        isNumberKey:false, //是否开启动态密钥
        keyArr: [],
        SMFlag: true,
        keyword: '',
        hosId: uni.getStorageSync('userData').user.currentHospital.id,
        list: [],
        patientInspectLogDTOIndex: undefined,
        deptId: undefined,
        options: {},
        config: {},
        // 弹窗model
        models: {
          disjunctor: false,
        },
        // 弹窗model1
        models1: {
          disjunctor: false,
        },
				handover: null ,//交接人id
				handoverId: null //交接人id
      };
    },
    computed: {
      listComputed() {
        if(this.keyword){
          return this.list.filter( v => v.patientName.includes(this.keyword) || v.residenceNo.includes(this.keyword))
        }else{
          return this.list;
        }
      }
    },
    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){
				let id = JSON.parse(JSON.stringify(data))
				id = id.split('||')
				this.handoverId = id[id.length-1]
      	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;
        this.tagClick(accountId);
      },
      // 扫一扫交接
      scanCode(){
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((content) => {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
					let id = JSON.parse(JSON.stringify(content))
					id = id.split('||')
					this.handoverId = id[id.length-1]
          this.bigScan(content);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      // 扫码
      bigScan(content){
        let postData = {
          type: 'patientDept', //根据患者所在科室，对比扫码科室校验
          deptId: this.deptId,
          scanCode: content,
        }
      
        post("/workerOrder/scanCheck", postData)
          .then((res) => {
            this.SMFlag = true;
            uni.hideLoading();
            if (res.state == 200) {
              this.tagClick();
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败！",
              });
            }
          });
      },
      // 标记回科
      tagClick(handover){
        this.handover = handover;
        this.models1 = {
          disjunctor: true,
          title: "提示",
          content: `是否确定批量回科？`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      //确定
      ok1() {
        this.models1.disjunctor = false;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/nurse/patientInspect/setPatientInspectBackDept", {
          pilIds: this.list.map(v => v.id).toString(),
          handover: this.handover?this.handover:this.handoverId,
        }).then((res) => {
          uni.hideLoading();
          if (res.state == 200) {
            uni.showToast({
              icon: "none",
              mask: true,
              title: "操作成功！",
            });
            setTimeout(() => {
               uni.navigateTo({
                 url: `/pages/patientInspectLog/patientInspectLogList`,
               });
            },300)
          } else {
            uni.showToast({
              icon: 'none',
              title: res.msg || '请求数据失败！'
            });
          }
        })
      },
      //取消
      cancel1() {
        this.models1.disjunctor = false;
      },
      // 返回
      goBack() {
        uni.navigateBack();
      },
      getConfig1(){
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        const postData = {
          "idx":0,
          "sum":1,
          "taskTypeConfig":{
            "taskTypeDTO":{
              "hosId": {"id": this.hosId},
              "associationType": {
                "key": "association_types",
                "value":"inspect",
              },
            },
          },
        };
        post("/simple/data/fetchDataList/taskTypeConfig", postData).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            let list = res.list || [];
            if(list.length){
              this.config = res.list[0];
            }else{
              this.config = {};
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 移除
      deleteIt(patientInspectLogDTO, index){
        this.patientInspectLogDTOIndex = index;
        this.models = {
          disjunctor: true,
          content: `您确认将<b style='color:red'>${patientInspectLogDTO.patientName}</b>移除吗？`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      // 确定
      ok() {
        this.models.disjunctor = false;
        this.list.splice(this.patientInspectLogDTOIndex, 1);
      },
      // 取消
      cancel() {
        this.models.disjunctor = false;
      },
      doSearch(){
        // 扫码
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((content) => {
          this.keyword = content;
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      toTransferWorkOrderUser() {
        uni.redirectTo({
          url: `/pages/transferWorkOrder/transferWorkOrderUser`,
        });
      },
      selectItem(patient){
        this.list.forEach(v => {
          if(v.id === patient.id){
            v.checked ? this.$set(v, 'checked', false) : this.$set(v, 'checked', true)
          }
        })
      },
    }
  }
</script>

<style lang="less" scoped>
.right-icon{
  color: #888;
  font-size: 44rpx;
}
.transferWorkOrder{
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  /deep/ uni-checkbox:not([disabled]) .uni-checkbox-input:hover{
    border-color: #49B856!important;
  }
  .green{
    color: #49B856;
    font-size: 36rpx;
    font-weight: bold;
  }
  .search{
    padding: 10rpx 24rpx;
  }
  .list{
    flex: 1;
    min-height: 0;
    background-color: #fff;
    .item{
      height: 100rpx;
      line-height: 100rpx;
      font-size: 28rpx;
      border-bottom: 1rpx solid #D5D5D5;
      padding: 0 32rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &.tac{
        justify-content: center;
      }
    }
  }
  .footer{
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    line-height: 80rpx;
    height: 80rpx;
    background: #fff;
    display: flex;
    align-items: center;
    .btn {
      height: 80rpx;
      flex: 1;
      margin: 0 24rpx 0 0;
      background-color: #49B856;
      color: #fff;
      border-radius: 8rpx;
      font-size: 34rpx;
      text-align: center;
      &:first-of-type{
        margin-left: 24rpx;
      }
      &.gray{
        background-color: #8F939C;
      }
    }
  }
}

</style>
