<template>
  <view class="patientList">
    <view class="search-box">
      <seiminSearch class="mSearch-input-box" :mode="2" button="inside" placeholder="输入床号或姓名支持拼音检索" @input="debounceInp"
        v-model="keyword"></seiminSearch>
    </view>
    <view class="search-keyword">
      <view class="orderList_listItem" v-for="patient in patientList" :key="patient.id">
        <view class="orderList_listItem_header">
          <view class="orderList_listItem_header_title">
            <block v-if="patient.illnessState">
              <view class="associationType_icon red" v-if="patient.illnessState.value === '2'">危</view>
              <view class="associationType_icon red" v-else-if="patient.illnessState.value === '3'">重</view>
            </block>
            <block v-if="patient.careLevel">
              <view class="associationType_icon red" v-if="patient.careLevel.value === '0'">特</view>
              <view class="associationType_icon red" v-else-if="patient.careLevel.value === '1'">1</view>
              <view class="associationType_icon green" v-else-if="patient.careLevel.value === '2'">2</view>
              <view class="associationType_icon green" v-else-if="patient.careLevel.value === '3'">3</view>
            </block>
            <view class="taskNameAndWorkerName">
              <text class="workerName">{{patient.patientName || '暂无'}}</text>
            </view>
          </view>
          <text class="orderList_listItem_header_more">{{patient.bedNum }}床</text>
        </view>
        <view class="orderList_listItem_item">
          <view class="orderList_listItem_item_content">
            <text class="orderList_listItem_item_name">{{patient.residenceNo || '暂无'}}</text>
            <text class="orderList_listItem_item_time">待检{{patient.watingCount}}</text>
          </view>
          <view class="orderList_listItem_item_btns">
            <button type="primary" class="btn" @click.stop="toDetail(patient.patientCode,patient.patientName)">患者详情</button>
            <button type="primary" class="btn" @click.stop="buildOrder(patient)">一键建单</button>
          </view>
        </view>
      </view>
    </view>
    <seiminFooterNav></seiminFooterNav>
    <seiminModel ref="seiminModel"></seiminModel>
    <seiminPicker ref="sPicker" :title="pickerTitle" titleColor="#808080" titleFontSize="28rpx" confirmColor="#333"
      confirmFontSize="38rpx" confirmFontWeight="500" itemFontSize="32rpx" @onClose="closePicker"
      @onConfirm="confirmPicker" :pickerList="taskTypeList">
    </seiminPicker>
  </view>
</template>

<script>
  import {
    debounce
  } from 'lodash/function';
  import {
    reqFetchDataList,
    reqDeptTSPTaskType,
    reqBuildTrip,
  } from "../../request/api.js";
  import {
    mapState,
    mapMutations,
  } from "vuex";
  import {
    ASSOCIATION_TYPES
  } from '../../utils/enum.association_types.js';
  export default {
    data() {
      return {
        ASSOCIATION_TYPES,
        checkedShowMsg: {}, //当前选中的任务类型的buildtrip信息
        selectedPatient: {}, //当前选中的患者
        taskTypeListResource: [], //任务类型列表(请求的原始数据)
        taskTypeList: [], //任务类型列表
        pickerTitle: "", //一键建单picker的title
        debounceInp: null,
        keyword: "",
        patientList: [],
        totalNum: 0, //工单总数量
        idx: 0, //页码
      };
    },
    computed: {
      ...mapState("login", ["loginInfo"]),
      ...mapState('other', ["deptDisplay"]),
    },
    methods: {
      ...mapMutations('other', ['changeQucikCreateOrderType', 'clearPatientBuildData', 'changePatientBuildData']),
      //关闭
      closePicker() {
        this.$refs.sPicker._close();
      },
      //打开
      openPicker() {
        this.$refs.sPicker._open();
      },
      //确定:接收子组件传来的参数
      confirmPicker(checkedObj) {
        console.log(checkedObj);
        // 补充:清除建单数据
        this.clearPatientBuildData();
        // 2,获取buildTrip信息
        let postData = {
          "taskTypeId": checkedObj.value,
          "patientCode": this.selectedPatient.patientCode
        };
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        reqBuildTrip(postData).then(res => {
          uni.hideLoading();
          let taskType = this.taskTypeListResource.find(v => v.id == checkedObj.value);
          let patientTaskType = taskType || {};
          if (patientTaskType.associationType.value == this.ASSOCIATION_TYPES['患者其他服务业务']) {
            // 患者其他服务业务--无法用status判断,运输过程“默认患者所在科室”没有返回status==200,估计是后端漏掉了这种情况,如果后期后端可以返回status,则可以根据status判断。
            if (res.start && res.end) {
              if (res.status == 100013 || res.status == 100014 || res.status == 100015) {
                this.checkedShowMsg = res.data;
                //需要选择起点科室和目标科室
                this.changeQucikCreateOrderType({
                  type: "patient",
                  taskTypeId: checkedObj.value,
                  patientTaskType,
                  selectedPatient: this.selectedPatient,
                  patientBuildTrip: res,
                });
                uni.navigateTo({
                  url: "/pages/quickCreateOrder/quickCreateOrder",
                });
              } else {
                //无需选择科室
                this.checkedShowMsg = res.data;
                this.changePatientBuildData({
                  key: 'dept',
                  value: {
                    startDept: res.start.start.list[0],
                    endDept: res.end.end.list[0],
                  }
                });
                this.changeQucikCreateOrderType({
                  type: "patient",
                  taskTypeId: checkedObj.value,
                  patientTaskType,
                  selectedPatient: this.selectedPatient,
                  patientBuildTrip: res,
                });
                uni.navigateTo({
                  url: "/pages/patientBuild/patientBuild",
                });
              }
            } else {
              this.$refs.seiminModel.show({
                skin: "toast",
                icon: "error",
                content: res.msg || "获取数据失败",
              });
              throw new Error(res.msg || '获取数据失败');
            }
          } else if (patientTaskType.associationType.value == this.ASSOCIATION_TYPES['患者陪检业务']) {
            // 患者陪检业务
            if (res.status == 200) {
              this.checkedShowMsg = res.data;
              this.changePatientBuildData({
                key: 'dept',
                value: {
                  startDept: {
                    id: res.startDept,
                    dept: res.startDeptName,
                    deptalias: res.startDeptAlias
                  }, //待改
                  endDept: {
                    id: res.startDept,
                    dept: res.startDeptName,
                    deptalias: res.startDeptAlias
                  }, //待改
                }
              });
              this.changeQucikCreateOrderType({
                type: "patient",
                taskTypeId: checkedObj.value,
                patientTaskType,
                selectedPatient: this.selectedPatient,
                patientBuildTrip: res,
              });
              uni.navigateTo({
                url: "/pages/appointmentInspect/appointmentInspect",
              });
            } else {
              this.$refs.seiminModel.show({
                skin: "toast",
                icon: "error",
                content: res.msg || "获取数据失败",
              });
              throw new Error(res.msg || '获取数据失败');
            }
          }
        })
      },
      // 一键建单
      buildOrder(patient) {
        this.selectedPatient = patient;
        // 1,请求任务类型列表
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        reqDeptTSPTaskType().then(res => {
          uni.hideLoading();
          if (res.status == 200) {
            res.data = res.data || [];
            this.taskTypeListResource = res.data;
            this.taskTypeList = res.data.map((v) => ({
              value: v.id,
              label: v.taskName,
            }));
            this.pickerTitle = `您选择了<b class="green">${patient.patientName}</b>患者,请选择下方具体服务项`;
            this.openPicker();
          } else {
            this.$refs.seiminModel.show({
              skin: "toast",
              icon: "error",
              content: res.msg || "获取数据失败",
            });
            throw new Error(res.msg || "获取数据失败");
          }
        })
      },
      // 跳转患者详情
      toDetail(patientCode,patientName) {
        uni.navigateTo({
          url: `/pages/patientDetail/patientDetail?patientCode=${patientCode}&patientName=${patientName}`
        })
      },
      //监听输入
      inputChange(event = '', idxPlus = false) {
        let keyWord = event.detail ? event.detail.value : event;
        if (idxPlus) {
          //累加
          ++this.idx;
        } else {
          this.idx = 0;
        }
        let postData = {
          "idx": this.idx,
          "sum": 9999,
          "patient": {
            keyWord,
            "department": {
              "id": this.loginInfo.user.dept.id
            }
          }
        };
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        reqFetchDataList("nurse", "patient", postData).then((res) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          if (res.status == 200) {
            res.list = res.list || [];
            if (idxPlus) {
              //累加
              this.patientList = this.patientList.concat(res.list);
            } else {
              this.patientList = res.list;
            }
            this.totalNum = res.totalNum || 0;
          } else {
            this.$refs.seiminModel.show({
              skin: "toast",
              icon: "error",
              content: res.msg || "获取数据失败",
            });
            throw new Error(res.msg || "获取数据失败");
          }
        });
      },
      // 查询最新列表(上拉)
      reachBottom() {
        //没有更多
        if (this.patientList.length == this.totalNum) {
          uni.showToast({
            icon: 'none',
            title: '没有更多数据了'
          })
          return;
        }
        this.inputChange(this.keyword, true);
      },
    },
    onReachBottom() {
      this.reachBottom();
    },
    onPullDownRefresh() {
      this.inputChange(this.keyword)
    },
    created() {
      this.debounceInp = debounce(this.inputChange, 500);
    },
    beforeDestroy() {
      this.debounceInp.cancel()
    },
    onLoad() {
      this.inputChange();
    },
  };
</script>
<style lang="scss" scoped>
  .patientList {
    padding-bottom: 108rpx;

    .search-box {
      background-color: rgb(242, 242, 242);
      padding: 15rpx 2.5%;
      position: fixed;
      z-index: 99;
      width: 100%;
      @include flex(space-between);

      .mSearch-input-box {
        width: 100%;
      }

      .input-box {
        width: 85%;
        flex-shrink: 1;
        @include flex(center, center);

        &>input {
          width: 100%;
          height: 60rpx;
          font-size: 32rpx;
          border: 0;
          border-radius: 60rpx;
          appearance: none;
          padding: 0 3%;
          margin: 0;
          background-color: #ffffff;
        }
      }

      .search-btn {
        width: 15%;
        margin: 0 0 0 2%;
        flex-shrink: 0;
        font-size: 28rpx;
        color: #fff;
        background: linear-gradient(to right, #ff9801, #ff570a);
        border-radius: 60rpx;
        @include flex(center, center);
      }
    }

    .search-keyword {
      padding: 88rpx 24rpx 0;

      // 列表项
      .orderList_listItem {
        width: 702rpx;
        min-height: 320rpx;
        background-color: #fff;
        position: relative;
        margin-top: 8rpx;
        border-radius: 8rpx;
        padding: 0 24rpx;
        font-size: 32rpx;
        @include border;
        @include semicircle(#F9FAFB, 82rpx);
        @include flex(flex-start, stretch, column);

        .orderList_listItem_header {
          height: 86rpx;
          @include border($directive:bottom, $style:dashed);
          @include flex(space-between, center);

          .orderList_listItem_header_title {
            color: #333;
            flex: 1;
            @include flex(flex-start, center);

            .associationType_icon {
              width: 48rpx;
              height: 48rpx;
              border-radius: 50%;
              font-size: 24rpx;
              margin-right: 8rpx;
              @include border($color:#39b199);
              @include flex(center, center);

              &.green {
                color: $defaultColor;
                border: 1px solid $defaultColor;
                background-color: rgba(73, 184, 86, 0.1);
              }

              &.red {
                color: #FF3B53;
                border: 1px solid #FF3B53;
                background-color: #FFE8EB;
              }
            }

            .taskNameAndWorkerName {
              flex: 1;
              @include flex;

              .taskName {
                max-width: 10em;
                @include clamp;
              }

              .workerName {
                flex: 1;
                @include clamp;
              }
            }
          }

          .orderList_listItem_header_more {
            color: #333;
            font-weight: bold;
            @include clamp;
          }
        }

        .orderList_listItem_item {
          height: 88rpx;
          color: #333;
          font-size: 30rpx;
          flex: 1;
          @include border(bottom);
          @include flex(flex-start, stretch, column);

          &:last-of-type {
            border-bottom: none;
          }

          .orderList_listItem_item_content {
            min-height: 143rpx;
            flex: 1;
            @include flex(space-between, center);

            .orderList_listItem_item_name {
              font-size: 34rpx;
            }

            .orderList_listItem_item_time {
              color: #333;
              font-size: 34rpx;
              font-weight: bold;
            }
          }

          .orderList_listItem_item_btns {
            position: relative;
            left: -24rpx;
            width: 698rpx;
            height: 88rpx;
            @include btn_background;
            @include flex;

            .btn {
              flex: 1;
              background-color: transparent;
              position: relative;
              @include flex(center, center);

              &::before {
                content: '';
                position: absolute;
                right: 0;
                top: 0;
                width: 1px;
                height: 100%;
                @include border(right, #fff);
              }

              &:last-of-type::before {
                border-right: none;
              }

              &::after {
                border: none;
              }
            }
          }
        }
      }
    }
  }
</style>