<template>
  <view class="incidentList">
    <view class="head">
      <view class="tab" :class="{active: tab.id === dataInfo.tabActiveId}" v-for="tab in dataInfo.tabs" :key="tab.id" @click="clickTab(tab.id)">
        {{tab.name}}<text v-if="tab.num !== ''">({{tab.num}})</text>
      </view>
      <view class="filter" @click="filterClick">
        <text class="newicon newicon-shaixuan"></text>
      </view>
    </view>
    <view class="body" v-if="dataInfo.list.length">
      <view class="body_item" v-for="data in dataInfo.list" :key="data.id" @click="toDetail(data)">
        <view class="body_item_head" @click.stop="changeCheckbox(data)">
          <view class="patientName">
            <checkbox-group v-if="config.batchPatientBackDept == 1 && data.state.value === '4'">
              <label>
                <checkbox class="checkbox" :checked="data.checked" />
              </label>
            </checkbox-group>
            <text>
              {{ data.patientName }}<text class="sign signRed">{{ data.careLevel ? data.careLevel.name.slice(0, 1) : '' }}<template v-if="data.careLevel && data.illnessState">、</template>{{ data.illnessState ? data.illnessState.name : '' }}</text>
            </text>
          </view>
          <text>{{ data.state ? data.state.name : '' }}</text>
        </view>

        <view class="body_item_content">
          <view class="body_item_content_p">
            <text class="name ellipsis">住院号：{{data.patientCode}}<text v-if="data.bedNum">({{ data.bedNum }})</text></text>
            <text>{{(data.patientDTO && data.patientDTO.gender) ? data.patientDTO.gender.name : ''}}<text v-if="data.age !== undefined" class="ml24">{{data.age}}<text v-if="data.age !== undefined">岁</text></text></text>
          </view>
          <view class="body_item_content_p">
            <text class="name ellipsis">患者科室：{{ data.deptDTO ? data.deptDTO.dept : '' }}</text>
            <text>{{data.tripTypeDTO ? data.tripTypeDTO.inspectMode : ''}}</text>
          </view>
          <view class="body_item_content_p">
            <text class="name ellipsis">签到信息：{{data.signDeptDTO ? data.signDeptDTO.dept : ''}}</text>
            <text>{{data.signTime | formatDate('MM-dd hh:mm')}}</text>
          </view>
        </view>

        <!-- <view class="body_item_foot" v-if="data.state.value === '4'">
          <view class="btns pt0">
            <button @click.stop="tagClick(data)" type="default" class="primaryButton btn">标记回科</button>
          </view>
        </view> -->
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
    <view class="toolbar">
      <button @click="tagClickList()" type="default" class="primaryButton btn" v-if="config.batchPatientBackDept == 1">批量回科</button>
      <view class="toolbar-btn btn" @click="scan()">
        <text class="toolbar-icon newicon newicon-saoma"></text>
        <text class="toolbar-sao">扫一扫</text>
      </view>
    </view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content" @ok="ok" @cancel="cancel" @know="know" :operate="models.operate"></showModel>
    <!-- 搜索 -->
    <patientInspectLogListFilter v-if="dataInfo.isFilter" @cancelEmit="cancelFilter" @confirmEmit="conformFilter" :evt="dataInfo.evtFilter" :tabActiveId="dataInfo.tabActiveId"></patientInspectLogListFilter>
  </view>
</template>

<script>
  import patientInspectLogListFilter from './components/patientInspectLogListFilter.vue';
  import { get, post, SM, deleteIt, webHandle } from "../../http/http.js";
  import uniq from 'lodash-es/uniq'
  export default {
    components:{
      patientInspectLogListFilter,
    },
    onShow() {
      this.SMFlag = true;
    },
    data(){
      return {
        config: {},
        selectData: {},
        SMFlag: true,
        loginUser: uni.getStorageSync('userData').user,
        hosId: uni.getStorageSync('userData').user.currentHospital.id,
        // 弹窗model
        models: {
          disjunctor: false,
        },
        dataInfo: {
          tabs: [
            {id: 1, name: '全部', value: '1', num: ''},
            {id: 2, name: '我带出的', value: '2', num: ''},
            {id: 3, name: '我接收的', value: '3', num: ''},
          ],
          tabActiveId: 1,//当前选择的tab
          list: [],//工单列表
          idx: 0,//页码
          hasMore: true,//是否有更多数据
          isFilter: false,//筛选框开关
          evtFilter: {
            signUser: {id: 0, name: '全部'},
            inspectUser: {id: 0, name: '全部'},
            department: {id: 0, dept: '全部'},
            stateList: [],
          },//筛选框数据
        }
      }
    },
    methods: {
      // 多选框
      changeCheckbox(data){
        if(this.config.batchPatientBackDept == 1 && data.state.value === '4'){
          this.$set(data, 'checked', !data.checked);
        }
      },
      // 获取状态列表
      getStateList(isStorage = false){
        let postData = {
          "type": "list",
          "key": "patient_inspect_state",
        };
        post("/common/common/getDictionary", postData).then(res => {
          let stateList = res || [];

          if(isStorage){
            this.dataInfo.evtFilter = uni.getStorageSync('patientInspectLogEvtFilter');
            this.dataInfo.tabActiveId = +uni.getStorageSync('patientInspectLogTabActiveId');
          }else{
            // 默认出科陪检中
            this.dataInfo.evtFilter.stateList = stateList.map(v => ({...v, checked: v.value == 4}));
          }

          this.getList(0);
        })
      },
      // 扫一扫
      scan(isFlag = false) {
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((ress1) => {
          this.scan_common(ress1, isFlag);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
      // 扫一扫方法
      scan_common(ress1, isFlag = false){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          idx: 0,
          sum: 1,
          patientInspectLog: {
            hosId: this.hosId,
            scanCode: ress1,
            simpleQuery: 1,
          }
        }
        post("/simple/data/fetchDataList/patientInspectLog", postData).then((ress) => {
          this.SMFlag = true;
          uni.hideLoading();
          if (ress.status == 200) {
            let list = ress.list || [];
            if(list.length){
              let patientInspectLog = undefined;
              patientInspectLog = list[0];
              uni.navigateTo({
                url: `/pages/patientInspectLog/patientInspectLogDetail?patientInspectLogId=${patientInspectLog.id}&from=patientInpectLogList`
              })
            }else{
              uni.showToast({
                icon: "none",
                title: "未查询到患者闭环信息！",
              });
            }
          } else {
            uni.showToast({
              icon: "none",
              title: ress.msg || "接口获取数据失败！",
            });
          }
        });
      },
      // 初始化
      onLoadFn(isStorage = false){
        this.getTabs(isStorage);
      },
      // 获取tab选项
      getTabs(isStorage = false){
        this.getStateList(isStorage);
      },
      // 获取列表信息
      getList(idx){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        this.dataInfo.idx = idx === undefined ? this.dataInfo.idx : idx;
        if(this.dataInfo.idx === 0){
          this.dataInfo.list = [];
        }

        let postData = {
            "idx": this.dataInfo.idx,
            "sum": 20,
            "patientInspectLog": {
              "hosId": this.hosId,
              simpleQuery: 1,
            }
        }

        let tabActiveObj = this.dataInfo.tabs.find(v => v.id == this.dataInfo.tabActiveId);
        console.log(tabActiveObj)

        if(tabActiveObj && tabActiveObj.id){
          if(tabActiveObj.id === 1){
            if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.signUser && this.dataInfo.evtFilter.signUser.id){
              postData.patientInspectLog.signUser = this.dataInfo.evtFilter.signUser.id;
            }
            if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.inspectUser && this.dataInfo.evtFilter.inspectUser.id){
              postData.patientInspectLog.outDeptUser = this.dataInfo.evtFilter.inspectUser.id;
            }
          }else if(tabActiveObj.id === 2){
            postData.patientInspectLog.outDeptUser = this.loginUser.id;
            if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.signUser && this.dataInfo.evtFilter.signUser.id){
              postData.patientInspectLog.signUser = this.dataInfo.evtFilter.signUser.id;
            }
          }else if(tabActiveObj.id === 3){
            postData.patientInspectLog.signUser = this.loginUser.id;
            if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.inspectUser && this.dataInfo.evtFilter.inspectUser.id){
              postData.patientInspectLog.outDeptUser = this.dataInfo.evtFilter.inspectUser.id;
            }
          }
        }

        if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.department && this.dataInfo.evtFilter.department.id){
          postData.patientInspectLog.deptId = this.dataInfo.evtFilter.department.id;
        }

        if(this.dataInfo.evtFilter && this.dataInfo.evtFilter.stateList && this.dataInfo.evtFilter.stateList.length){
          let values = this.dataInfo.evtFilter.stateList.filter(v => v.checked).map(v => v.value).toString();
          postData.patientInspectLog.state = values ? {
            value: values
          } : undefined;
        }

        post("/simple/data/fetchDataList/patientInspectLog", postData).then(res => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          if(res.status == 200){
            let list = res.list || [];
            if(list.length){
              this.dataInfo.hasMore = true;
              this.dataInfo.list = this.dataInfo.idx === 0 ? list : this.dataInfo.list.concat(list);
            }else{
              this.dataInfo.hasMore = false;
            }
          }else{
            uni.showToast({
              icon: 'none',
              title: res.msg || '请求数据失败！'
            });
          }
        })
      },
      // 详情
      toDetail(data){
        uni.navigateTo({
          url: `/pages/patientInspectLog/patientInspectLogDetail?patientInspectLogId=${data.id}&from=patientInpectLogList`
        })
      },
      // 批量回科
      tagClickList(){
        let list = this.dataInfo.list.filter(v => v.checked);
        if(list.length){
          let arr = list.filter(v => v.deptDTO).map(v => v.deptDTO.id);
          arr = uniq(arr);
          if(arr.length > 1){
            uni.showToast({
              icon: "none",
              title: "您选择的患者中含多个科室，请调整好再试！",
            });
          }else if(arr.length === 1){
            uni.navigateTo({
              url: `/pages/patientInspectLog/patientInspectLogSendBack?deptId=${arr[0]}&patientList=${encodeURIComponent(JSON.stringify(list))}`,
            })
          }else{
            uni.showToast({
              icon: "none",
              title: "您选择的患者中没有科室，请调整好再试！",
            });
          }
        }else{
          uni.showToast({
            icon: "none",
            title: "请选择患者！",
          });
        }
      },
      getConfig1(){
        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) => {
          if (res.status == 200) {
            let list = res.list || [];
            if(list.length){
              this.config = res.list[0];
            }else{
              this.config = {};
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        })
      },
      // 标记回科
      tagClick(data){
        this.selectData = data;
        this.models = {
          disjunctor: true,
          title: "提示",
          content: `将${data.patientName}患者标记为已回科，是否确认？`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      //确定
      ok() {
        this.models.disjunctor = false;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/nurse/patientInspect/setPatientInspectBackDept", {
          pilIds: this.selectData.id.toString(),
        }).then((res) => {
          uni.hideLoading();
          let _this = this;
          if (res.state == 200) {
            uni.showToast({
              icon: "none",
              mask: true,
              title: "操作成功！",
            });
            setTimeout(() => {
              _this.getList(0);
            },300)
          } else {
            uni.showToast({
              icon: 'none',
              title: res.msg || '请求数据失败！'
            });
          }
        })
      },
      //取消
      cancel() {
        this.models.disjunctor = false;
      },
      // 点击tab
      clickTab(tabId){
        this.dataInfo.tabActiveId = tabId;
        if(tabId === 1){
          this.dataInfo.evtFilter.signUser = {id: 0, name: '全部'};
          this.dataInfo.evtFilter.inspectUser = {id: 0, name: '全部'};
        }else if(tabId === 2){
          this.dataInfo.evtFilter.signUser = {id: 0, name: '全部'};
          this.dataInfo.evtFilter.inspectUser = this.loginUser;
        }else if(tabId === 3){
          this.dataInfo.evtFilter.signUser = this.loginUser;
          this.dataInfo.evtFilter.inspectUser = {id: 0, name: '全部'};
        }
        this.getList(0);
      },
      // 点击筛选
      filterClick(){
        this.dataInfo.isFilter = true;
      },
      // 确认筛选
      conformFilter(evtFilter){
        uni.setStorageSync('patientInspectLogEvtFilter', evtFilter);//缓存
        uni.setStorageSync('patientInspectLogTabActiveId', this.dataInfo.tabActiveId);//缓存
        this.dataInfo.evtFilter = evtFilter;
        this.dataInfo.isFilter = false;
        this.getList(0);
      },
      // 关闭筛选
      cancelFilter(){
        this.dataInfo.isFilter = false;
      },
    },
    onLoad(options){
      this.getConfig1();
      this.onLoadFn(uni.getStorageSync('patientInspectLogEvtFilter') && uni.getStorageSync('patientInspectLogTabActiveId'));
    },
    onTabItemTap(){
      this.onLoadFn();
    },
    onPullDownRefresh(){
      this.getList(0);
    },
    onReachBottom(){
      this.dataInfo.idx += 1;
      if (this.dataInfo.hasMore) {
        this.getList(); // 当触底时加载更多数据
      }
    },
  };
</script>

<style lang="scss" scoped>
.checkbox{
  /deep/ .uni-checkbox-input.uni-checkbox-input-checked{
    color: #42b983!important;
  }
}

/deep/ .checkbox:not([disabled]) .uni-checkbox-input:hover {
  border-color: #42b983 !important;
  color: #42b983 !important;
}
.toolbar {
  position: fixed;
  left: 0;
  bottom: var(--window-bottom);
  z-index: 99;
  width: 100%;
  display: flex;
  padding: 24rpx;
  gap: 24rpx;
  box-sizing: border-box;
  background-color: #f9f9fb;
  
  .primaryButton{
    padding: 0;
  }
  
  .btn{
    flex: 1;
  }
  
  .toolbar-btn{
    height: 88rpx;
    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;
  }
}
page{
  height: calc(100vh - var(--window-bottom));
}
.incidentList{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .head{
    height: 88rpx;
    display: flex;
    position: fixed;
    z-index: 99;
    width: 100%;
    background-color: #fff;
    font-size: 30rpx;
    .tab{
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 4rpx solid transparent;
      &.active{
        color: #49b856;
        border-color: #49b856;
      }
    }
    .filter{
      width: 84rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      .newicon-shaixuan{
        font-size: 36rpx;
        color: #2C2C2C;
      }
    }
  }
  .body{
    margin-bottom: calc(var(--window-bottom) + 88rpx + 48rpx);
    margin-top: 88rpx;
    border-top: 6rpx solid #EBEBEB;
    .body_item{
      border-bottom: 8rpx solid #EBEBEB;
      &:last-of-type{
        border-bottom: none;
      }
      .body_item_head{
        word-break: break-all;
        text-align: justify;
        text-align: left;
        margin: 24rpx;
        font-size: 30rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .patientName{
          display: flex;
          align-items: center;
        }
        .sign{
          margin-left: 16rpx;
          color: #49B856;
          &.signRed{
            color: #FF0000;
          }
        }
      }
      .body_item_content{
        border-top: 1rpx solid #D8D8D8;
        padding: 24rpx;
        .body_item_content_p{
          color: #6A6A6A;
          font-size: 26rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24rpx;
          &:last-of-type{
            margin-bottom: 0;
          }
          .name{
            flex: 1;
          }
          .status{
            padding: 4rpx 10rpx;
            border-radius: 20rpx;
            background-color: #DBE8FE;
            font-size: 22rpx;
            color: #006CF9;
          }
          .icon_all{
            .mic-filled,
            .image-filled
            {
              margin-left: 16rpx;
            }
          }
        }
      }
      .body_item_foot{
        border-top: 1rpx solid #D8D8D8;
        font-size: 26rpx;
        padding: 24rpx;
        .foot_info{
          display: flex;
          justify-content: space-between;
          align-items: center;
          .phone-filled{
            margin-left: 5rpx;
          }
        }
      }
    }
  }
  .zanwu{
    box-sizing: border-box;
    margin-bottom: calc(var(--window-bottom) + 88rpx);
    margin-top: 88rpx;
    border-top: 6rpx solid #EBEBEB;
    height: calc(100vh - var(--window-bottom) - 176rpx);
    display: flex;
    justify-content: center;
    background-color: #F7F7F7;
    .newicon-zanwu{
      font-size: 256rpx;
      color: #D6D6D6;
      margin-top: 140rpx;
    }
  }
}
</style>
