<template>
  <view class="patientInformationList">
    <view class="page_tab">
      <view class="page_tab_bar active">
        <view class="tab_dept" @click="changeDept">
          {{ currenDept.dept}}
          <text class="newicon newicon-weibiaoti2010104"></text>
        </view>
      </view>
      <view class="search-box">
        <mSearch class="search" :mode="2" button="inside" placeholder="请输入关键字" @input="changeInp" v-model="keyword"></mSearch>
      </view>
    </view>
    <view v-if="zxzData.length == 0" class="zwsj">
      <image class="zwsj-img" mode="widthFix" src="../../static/img/zanwushuju.png"></image>
      <view class="zwsj-txt">暂无数据</view>
    </view>
    <view v-if="zxzData.length" class="page_items">
      <scroll-view class="page_items_scroll" scroll-y :refresher-enabled="scroll_refresher_enabled"
        :refresher-triggered="triggered" @refresherrefresh="refresherrefresh" @refresherrestore="refresherrestore"
        @scrolltolower="scrolltolower" :scroll-top="scroll_top" @refresherabort="refresherabort" @scroll="scroll"
        refresher-background="transport">
        <view class="page_item_wrap" v-for="(item, index) of zxzData" :key="index">
          <view class="page_item">
            <view class="page_item_top">
              <view class="page_item_top_L">
                <text class="circleRed" v-if="!item.tripTypeDTO"></text>{{ item.patientName }}({{ item.residenceNo }})({{ item.bedNum }})
              </view>
              <view class="send_wrap">
                <template v-if="item.gender || item.age !== undefined">
                  {{item.gender ? item.gender.name: ''}} {{item.age !== undefined ? item.age + '岁': ''}}
                </template>
                <template v-else>--</template>
              </view>
            </view>
            <view class="page_item_cont">
              <view class="page_item_conts">
                <view class="page_item_conts_item">
                  <view class="column">
                    <text class="p_title">护理信息：</text>
                    <text class="p_info">
                      <text :class="{red:item.careLevel&&(item.careLevel.value==0||item.careLevel.value==1)}">{{item.careLevel ? item.careLevel.name : '' }}</text>(<text :class="{red:item.illnessState&&(item.illnessState.value==2||item.illnessState.value==3)}">{{item.illnessState ? item.illnessState.name : ''}}</text>)
                    </text>
                  </view>
                  <view class="column">
                    <text class="p_title">待检：</text>
                    <text class="p_info">{{ item.watingCount }}</text>
                  </view>
                </view>

                <view class="page_item_conts_item">
                  <view class="column">
                    <text class="p_title">陪检方式：</text>
                    <text class="p_info">{{ item.tripTypeDTO ? item.tripTypeDTO.inspectMode : '' }}</text>
                  </view>
                </view>

                <view class="page_item_conts_item">
                  <view class="column">
                    <text class="p_title">注意事项：</text>
                    <text class="p_info">{{ item.remark }}</text>
                  </view>
                </view>
                
                <view class="page_item_conts_item" v-if="item.inspects && item.inspects[0]">
                  <view class="column">
                    <text class="p_title">检查项目：</text>
                    <text class="p_info">{{ item.inspects[0].inspectName }}-{{ item.inspects[0].inspectCode }}</text>
                  </view>
                </view>
                
                <view class="page_item_conts_item" v-if="item.inspects && item.inspects[0]">
                  <view class="column">
                    <text class="p_title">检查科室：</text>
                    <text class="p_info">
                      <text>{{item.inspects[0].execDept ? item.inspects[0].execDept.dept : '' }}</text>
                    </text>
                  </view>
                  <view class="column" style="flex-shrink: 0;margin-left: 40rpx;">
                    <text class="p_info">{{ item.sortYytime | yyTimeFilter }}</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="page_item_btns">
              <view class="page_item_btn" hover-class="seimin-btn-hover" @click="itemInfo(item.patientCode)">患者详情</view>
              <view class="page_item_btn" hover-class="seimin-btn-hover" @click="scanDept(item)">送回病房</view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 底部扫一扫 -->
    <bigScreen></bigScreen>
    <!-- 送回病房弹窗 -->
    <showModel :title="models1.title" :icon="models1.icon" :disjunctor="models1.disjunctor" :content="models1.content"
      :operate="models1.operate" @ok="ok1" @cancel="cancel1"></showModel>
    <!-- 送回病房建单弹窗 -->
    <showModel :title="models2.title" :icon="models2.icon" :disjunctor="models2.disjunctor" :content="models2.content"
      :operate="models2.operate" @ok="ok2" @cancel="cancel2"></showModel>
    <!-- 送回病房建单弹窗-扫描科室 -->
    <showModel :title="models3.title" :icon="models3.icon" :disjunctor="models3.disjunctor" :content="models3.content"
      :operate="models3.operate" @ok="ok3" @cancel="cancel3"></showModel>
    <!-- 弹窗 -->
    <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 mSearch from "@/components/mehaotian-search-revision/mehaotian-search-revision.vue";
  import bigScreen from "../../components/bigScreen/bigScreen.vue";
  import dayjs from 'dayjs';
  import debounce from 'lodash-es/debounce';
  import {
    get,
    post,
    SM,
    deleteIt,
    webHandle
  } from "../../http/http.js";
  export default {
    data() {
      return {
        keyword: '',
        selectRadio: [], //单选框选中的数据，第一项是qrcode，第二项是名称
        // 单选框弹窗model
        models4: {
          disjunctor: false,
        },
        SMFlag:true,
        hosId: uni.getStorageSync("userData").user.currentHospital.id,
        // 选中的患者项
        currentItem: {},
        // 送回病房弹窗model
        models1: {
          disjunctor: false,
        },
        // 送回病房建单弹窗model
        models2: {
          disjunctor: false,
        },
        // 送回病房建单弹窗model-扫描科室
        models3: {
          disjunctor: false,
        },
        scrollYY: 0, //滚动条滚动的距离
        options: {},
        // wechatFocusSwitch: 0,
        //当前登录人所属科室
        currenDept: {},
        // 抢单的id
        qdId: "",
        //列表数据
        zxzData: [],
        //分页页码
        idx: 0,
        // 列表项总数
        totalNum: -1,
        triggered: false, //下拉刷新状态
        freshing: false, //上拉加载开关
        scroll_top: 0, //距离顶部的距离
        scroll_refresher_enabled: true, //是否开启自定义下拉刷新
        currentStartDept: {}, //扫描的起点科室
      };
    },
    components: {
      bigScreen,
      mSearch,
    },
    filters: {
      // 自定义管道 yyTime
      yyTimeFilter: function(data) {
        if (data) {
          let nDate = null;
          if (typeof data == 'string') {
            let arr = data.split(/[-:\s]/);
            nDate = new Date(
              arr[0] - 0,
              arr[1] - 1,
              arr[2] - 0,
              arr[3] - 0,
              arr[4] - 0,
              0
            );
          } else if (typeof data == 'number') {
            nDate = new Date(data);
          }
          const month = (nDate.getMonth() + 1).toString().padStart(2, 0);
          const date = nDate.getDate().toString().padStart(2, 0);
          const hour = nDate.getHours().toString().padStart(2, 0);
          const minute = nDate.getMinutes().toString().padStart(2, 0);
          return `${month}-${date} ${hour}:${minute}`;
        } else {
          return "";
        }
      }
    },
    methods: {
      handleSearch: debounce(function() {
        this.refresherrefresh();
      }, 500),
      //防抖搜索
      changeInp(event) {
        this.inputChange(event);
      },
      //监听输入
      inputChange(event) {
        this.keyword = event.detail ? event.detail.value : event;
        this.handleSearch();
      },
      // 获取是否需要选择陪检方式
      getInspectAndPatientTransformSend() {
        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
                  }));
                  this.models4 = {
                    disjunctor: true,
                    title: "请选择陪检方式",
                    radioInspectionDistanceItem,
                    icon: "",
                    operate: {
                      ok: "确定",
                      cancel: "取消",
                    },
                  };
                } else {
                  uni.showToast({
                    icon: "none",
                    title: res.msg || "接口获取数据失败！",
                  });
                }
              })
            } else {
              this.ok3Result();
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 选中单选框
      radioChange4(item) {
        console.log(item);
        this.selectRadio = item.split("__");
      },
      // 确定
      ok4() {
        console.log(this.selectRadio);
        if (!this.selectRadio.length) {
          return;
        }
        this.models4.disjunctor = false;
        this.ok3Result();
      },
      cancel4() {
        this.models4.disjunctor = false;
      },
      ok2() {
        this.models2.disjunctor = false;
        this.getInspectAndPatientTransformSend();
      },
      cancel2() {
        this.models2.disjunctor = false;
      },
      ok3Result() {
        console.log(this.currentItem)
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        let userId = uni.getStorageSync("userData").user.id;
        let postData = {
          "workOrder": [{
            sourceId: 4,
            "hosId": this.hosId,
            "startDept": {
              "id": this.options.did || this.currentStartDept.id
            },
            "createDept": this.options.did || this.currentStartDept.id,
            "patient": {
              "patientCode": this.currentItem.patientCode
            },
            "worker": {
              "id": userId
            },
          }],
          "inspectMode": this.selectRadio.length > 0 ? this.selectRadio[0] : undefined,
        };
        console.log(postData);
        // return;
        post("/workerOrder/returnSickRoom", postData).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            uni.showToast({
              icon: 'success',
              title: '建单成功',
            });
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      ok3() {
        this.models3.disjunctor = false;
        this.getInspectAndPatientTransformSend();
      },
      cancel3() {
        this.models3.disjunctor = false;
      },
      // 送回病房-建单
      sendBuild() {
        let currentItem = JSON.parse(this.options.currentItem);
        this.models2 = {
          disjunctor: true,
          title: "提示",
          content: `您选择的起点科室为【${this.options.ddept}】，您将从【${this.options.ddept}】把【${currentItem.patientName}】送回【${this.options.dept}】，如您确认请点击“确认建单”。`,
          icon: "warn",
          operate: {
            ok: "确认建单",
            cancel: "取消",
          },
        };
      },
      // 送回病房-扫描科室
      scanDept(item) {
        console.log(item)
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        this.currentItem = item;
        let code = "";
        SM().then((ress1) => {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
          //检验二维码的有效性
          post("/dept/scanning", {
            content: ress1,
          }).then((result) => {
            this.SMFlag = true;
            if (result.state == 200 || result.state == 201) {
              let ress = result.code;
              if (ress) {
                code = ress;
                // 科室扫描
                let postData = {
                  "type": "query",
                  "qrCode": code
                };
                post("/dept/scanChangeDept", postData).then((res) => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    if (res.data) {
                      if(res.data.deptDTO){
                        this.currentStartDept = res.data.deptDTO;
                      }else{
                        this.currentStartDept = res.data;
                      }
                      this.models3 = {
                        disjunctor: true,
                        title: "提示",
                        content: `您选择的起点科室为【${this.currentStartDept.dept}】，您将从【${this.currentStartDept.dept}】把【${this.currentItem.patientName}】送回【${this.currenDept.dept}】，如您确认请点击“确认建单”。`,
                        icon: "warn",
                        operate: {
                          ok: "确认建单",
                          cancel: "取消",
                        },
                      };
                    } else {
                      uni.hideLoading();
                      uni.showToast({
                        icon: "none",
                        title: "请扫描正确的科室码！",
                      });
                    }
                  } else {
                    uni.hideLoading();
                    uni.showToast({
                      icon: "none",
                      title: res.msg || "接口获取数据失败！",
                    });
                  }
                });
              }
            } else {
              uni.hideLoading();
              uni.showToast({
                icon: "none",
                title: result.info || "接口获取数据失败！",
              });
            }
          });
        }).catch(err=>{
          this.SMFlag = true;
        });
      },
      // 送回病房-选择起点科室
      sendBack(item) {
        console.log(item)
        this.currentItem = item;
        this.models1 = {
          disjunctor: true,
          title: "提示",
          content: `您好，您是要将【${item.patientName}】送回病房吗？如确认请您点击“选择起点科室”建立工单。`,
          icon: "warn",
          operate: {
            ok: "选择起点科室",
            cancel: "取消",
          },
        };
      },
      ok1() {
        this.models1.disjunctor = false;
        uni.navigateTo({
          url: `../search/search?type=sendBackPatientList&currentItem=${JSON.stringify(this.currentItem)}&cid=${this.currenDept.id}&cdept=${this.currenDept.dept}&scrollYY=${this.scrollYY}`,
        });
      },
      cancel1() {
        this.models1.disjunctor = false;
      },
      // 切换科室
      changeDept() {
        uni.navigateTo({
          url: `../search/search?type=patientInformationList`,
        });
      },
      // 进入详情页
      itemInfo(patientCode) {
        // #ifdef H5
        document.body.removeEventListener("touchmove", this.stop, {
          passive: false,
        });
        // #endif
        uni.navigateTo({
          url: `../patientInformationInfo/patientInformationInfo?patientCode=${patientCode}`,
        });
      },
      //患者列表数据获取
      waitingOrders(idx) {
        if (this.zxzData.length == this.totalNum) {
          uni.showToast({
            icon: "none",
            title: "没有更多数据了！",
          });
          this.freshing = true;
          return;
        }
        let data = {
          idx,
          sum: 99999,
          patient: {
            sortYytime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            keyWord: this.keyword || undefined,
            department: {
              id: this.currenDept.id,
            },
          },
        };
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        // 请求列表数据
        post("/nurse/fetchDataList/patient", data).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            this.triggered = false;
            this.freshing = true;
            this.totalNum = res.totalNum;
            if (idx === 0) {
              this.zxzData = res.list;
            } else {
              this.zxzData.push(...res.list);
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      //刷新
      refresherrefresh() {
        if (this.triggered) {
          return;
        }
        console.log("下拉刷新");
        this.triggered = true;
        this.idx = 0;
        this.totalNum = -1;
        this.waitingOrders(0);
      },
      // 下拉刷新复位
      refresherrestore() {
        this.triggered = false;
        console.log("下拉刷新复位");
      },
      //下拉刷新中止
      refresherabort() {
        this.triggered = false;
        console.log("下拉刷新中止");
      },
      //分页,上拉加载
      scrolltolower() {
        if (this.freshing) {
          console.log("上拉加载");
          this.freshing = false;
          this.waitingOrders(++this.idx);
        }
      },
      // 滚动
      scroll(e) {
        this.scrollYY = e.detail.scrollTop;
        if (e.detail.scrollTop < 20) {
          this.scroll_refresher_enabled = true;
        } else {
          this.scroll_refresher_enabled = false;
        }
      },
      // 阻止浏览器滑动
      stop(e) {
        e.preventDefault();
      },
    },
    onLoad(options) {
      console.log(options);
      this.options = options;
      //滚动条位置设置
      if (options.scrollYY !== undefined) {
        this.scroll_top = options.scrollYY;
      }
      if (options.did && options.ddept && options.currentItem) {
        this.sendBuild();
      }
      let patientCurrentDept = uni.getStorageSync("patientCurrentDept");
      if (options.id && options.dept) {
        let {
          id,
          dept
        } = options;
        this.currenDept.id = id;
        this.currenDept.dept = dept;
      } else if (patientCurrentDept) {
        this.currenDept.id = patientCurrentDept.id;
        this.currenDept.dept = patientCurrentDept.dept;
      } else {
        this.currenDept = uni.getStorageSync("userData").user.dept;
      }
      // this.getWechatFocusSwitch();
      this.waitingOrders(0);
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
    onShow() {
      this.SMFlag = true;
      // #ifdef H5
      document.body.addEventListener("touchmove", this.stop, {
        passive: false,
      });
      // #endif
    },
    onHide() {
      // #ifdef H5
      document.body.removeEventListener("touchmove", this.stop, {
        passive: false,
      });
      // #endif
    },
  };
</script>
<style lang="less" scoped>
  .toolbar {
    position: fixed;
    left: 0;
    bottom: var(--window-bottom);
    z-index: 99;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    border-radius: 4rpx;
    background-color: #E5E8ED;

    .toolbar-icon {
      font-size: 52rpx;
      margin-right: 16rpx;
      color: #49B856;
    }

    .toolbar-sao {
      font-size: 36rpx;
      color: #333;
    }
  }
  .column{
    display: flex!important;
  }
  .newicon-weibiaoti2010104 {
    font-size: 32rpx;
    padding-left: 5rpx;
    color: #8A8A8A;
    &.fz28{
      font-size: 28rpx;
    }
  }
  .patientInformationList {
    width: 100%;
    height: 100%;
    position: relative;

    .page_tab {
      width: 100%;
      height: 176rpx;
      position: fixed;
      left: 0;
      top: 0;
      z-index: 999;
      
      .search-box {
        background-color: rgb(242, 242, 242);
        .search{
          padding: 10rpx 24rpx;
        }
      }

      .page_tab_bar {
        height: 96rpx;
        flex: 1;
        font-size: 30rpx;
        background: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        &:after {
          content: "";
          position: absolute;
          left: 0;
          bottom: 0;
          height: 8rpx;
          width: 100%;
          background-color: transparent;
        }

        .tab_dept {
          position: relative;

          .changeDept {
            white-space: nowrap;
            margin: 0;
            position: absolute;
            right: 0;
            top: 50%;
            transform: translate(105%, -50%);
            padding: 0 0.5em;
            line-height: 2;
          }
        }

        &.active {
          color: #49b856;

          &:after {
            background-color: #49b856;
          }
        }
      }
    }

    .zwsj {
      position: absolute;
      left: 50%;
      top: 180rpx;
      transform: translateX(-50%);

      .zwsj-img {
        width: 560rpx;
      }

      .zwsj-txt {
        font-size: 36rpx;
        font-weight: 700;
        margin-top: 20rpx;
        text-align: center;
      }
    }

    .page_items {
      height: calc(100vh - 164rpx - 80rpx);
      padding-top: 170rpx;

      .page_items_scroll {
        height: 100%;

        .page_item_wrap {
          position: relative;
          margin-top: 8rpx;
          &:last-of-type{
            padding-bottom: 24rpx;
          }

          .page_item {
            background: #fff;
            border-radius: 8rpx;
            overflow: hidden;
            border: 2rpx solid #e5e9ed;
            display: flex;
            flex-direction: column;
            padding-bottom: 16rpx;

            .L {
              width: 40rpx;
              height: 40rpx;
              border-radius: 50%;
              background: #f9fafb;
              position: absolute;
              left: -24rpx;
              top: 68rpx;
              border: 2rpx solid #e5e9ed;
            }

            .R {
              width: 40rpx;
              height: 40rpx;
              border-radius: 50%;
              background: #f9fafb;
              position: absolute;
              float: right;
              right: -24rpx;
              top: 68rpx;
              border: 2rpx solid #e5e9ed;
            }

            .page_item_top {
              height: 86rpx;
              border-bottom: 2rpx dashed #e5e9ed;
              padding: 0 16rpx;
              display: flex;
              align-items: center;
              justify-content: space-between;

              .send_wrap {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 26rpx;
                color: #6A6A6A;
              }

              .sendBack {
                button {
                  font-size: 28rpx;
                  height: 52rpx;
                  line-height: 52rpx;
                  margin: 0;
                  color: rgb(7, 134, 60);
                }
              }

              .page_item_top_L {
                height: 100%;
                float: left;
                display: flex;
                align-items: center;
                line-height: 88rpx;
                font-size: 30rpx;
                font-weight: bold;

                .circleRed{
                  position: relative;
                  margin-right: 8rpx;
                  width: 16rpx;
                  height: 16rpx;
                  border-radius: 50%;
                  background-color: red;
                }

                .L_time {
                  color: #6cc076;
                  font-size: 32rpx;
                }
              }

              .page_item_top_R {
                height: 40rpx;
                float: right;
                line-height: 40rpx;
                font-size: 24rpx;
                padding: 0 8rpx;
                background-color: red;
                color: #fff;
              }
            }

            .page_item_cont {
              padding: 0 32rpx;
              text-align: left;
              position: relative;

              .page_item_conts {
                color: rgb(102, 102, 102);
                font-size: 26rpx;

                .page_item_conts_item {
                  margin-bottom: 16rpx;
                  display: flex;
                  justify-content: space-between;
                  &:first-of-type{
                    margin-top: 16rpx;
                  }
                }

                .p_info {
                  flex: 1;

                  &.red {
                    color: red;
                  }

                }

                .num {
                  float: right;
                }
              }
            }

            .page_item_btns{
              display: flex;
              justify-content: space-between;
              align-items: center;
              .page_item_btn {
                flex: 1;
                height: 72rpx;
                background-image: linear-gradient(to right, #72c172, #3bb197);
                border-radius: 8rpx;
                line-height: 72rpx;
                color: #fff;
                font-size: 36rpx;
                font-weight: 700;
                text-align: center;
                margin-right: 24rpx;
                &:first-of-type{
                  margin-left: 24rpx;
                }
              }
            }
          }

          .L-l {
            width: 2rpx;
            height: 40rpx;
            background: #f9fafb;
            position: absolute;
            left: 20rpx;
            top: 72rpx;
            display: none;
          }

          .R-l {
            width: 2rpx;
            height: 40rpx;
            background: #f9fafb;
            position: absolute;
            right: 20rpx;
            top: 72rpx;
            display: none;
          }
        }
      }
    }
  }
</style>
