<template>
  <div class="flex flex-1 flex-col patient-list">
    <div class="title flex justify-between items-center">
      <u-search
        style="width: 500rpx"
        v-model="name"
        shape="round"
        action-text=" "
        placeholder="请输入患者"
        @search="getData(true)"
        @blur="searchBlur"
      ></u-search>
      <select-lay
        :zindex="99"
        :showplaceholder="false"
        :value="tval"
        name="name"
        placeholder="请选择类型"
        :options="provinces"
        @selectitem="changeSelect"
      >
      </select-lay>
    </div>
    <u-modal
      v-model="show"
      :closeOnClickOverlay="true"
      title="提示"
      content="是否确定删除当前患者信息？"
      show-cancel-button
      confirm-text="删除"
      @confirm="confirmDel"
    ></u-modal>
    <u-modal
      v-model="show1"
      :closeOnClickOverlay="true"
      title="提示"
      content="退出当前病例后，其他医生可接诊。确定要退出吗？"
      show-cancel-button
      confirm-text="退出"
      @confirm="confirmBack"
    ></u-modal>
    <u-toast ref="uToast" />
    <scroll-view scroll-y="true" :style="{ height: height }" :lower-threshold="50" scroll-with-animation @scrolltolower="scrolltolower">
      <div v-if="patientList.length" class="white list-box w-full flex-1 flex-col">
        <div class="patients flex flex-row">
          <div>{{ tval === 0 ? '急救患者' : '出院患者' }}</div>
          <div class="ml-2 card-total flex items-center justify-center">{{ total }}</div>
        </div>
        <div
          v-for="(card, cardIndex) in patientList"
          :key="cardIndex"
          class="mb-4 w-full card-box flex flex-row flex-nowrap"
          style="position: relative"
          @mousedown="start"
          @touchstart="start"
          @mousemove="move($event, cardIndex)"
          @touchmove="move($event, cardIndex)"
          @mouseup="end"
          @touchend="end"
        >
          <div
            @longpress="longpress(card.firstAidId)"
            @click="changeTimeLine(card.recordUserId, card.firstAidId, globalData.createAuth - 0 === 0 ? 1 : 0, card.demonstrate)"
            style="height: 100%; width: 100%; position: absolute; top: 0; left: 0; z-index: 10"
          ></div>
          <div :style="{ 'margin-left': outIndex === cardIndex && card.recordUserId - 0 ? '-68px' : '' }" class="w-full anima">
            <div class="crad-content">
              <div class="status-wait" v-if="!(card.recordUserId - 0)"></div>
              <div class="flex mb-2">
                <div class="pr-2 fw-bold">
                  <span v-if="card.name">
                    {{ card.name }}
                  </span>
                  <span v-else> 无名氏 </span>
                </div>
                <div class="pr-2 fw-bold">
                  <span v-if="card.gender === 0">女</span>
                  <span v-else-if="card.gender === 1">男</span>
                  <span v-else>-</span>
                </div>
                <div class="pr-2 fw-bold">
                  <span v-if="card.age || card.age === 0">{{ card.age }}</span>
                  <span v-else>-</span>
                </div>
                <u-tag style="z-index: 99; margin-right: 0" plain shape="circle" v-if="card.isJmrs - 0 === 1" text="静脉溶栓"> </u-tag>
                <u-tag
                  class="ml-2 flex items-center justify-center"
                  type="success"
                  plain
                  shape="circle"
                  v-if="card.isXgzl - 0 === 1"
                  text="血管内治疗"
                >
                </u-tag>
              </div>
              <div class="flex">
                <div>{{ tval === 0 ? '到院时间：' : '出院时间：' }}</div>
                <div v-if="card.record2" style="color: rgba(0, 0, 0, 0.85)">
                  {{ $moment(+card.record2).format('YYYY-MM-DD HH:mm') }}
                </div>
              </div>
            </div>
            <img src="./icon/yanshi.png" class="img-box" v-if="card.demonstrate === 1" />
          </div>
          <div
            :style="{
              width: outIndex === cardIndex && card.recordUserId - 0 ? '68px' : 0,
              color: outIndex === cardIndex && card.recordUserId - 0 ? 'rgba(255,255,255,1)' : 'rgba(255,0,0,0)',
            }"
            class="sign-out flex items-center justify-center anima"
            @click="quitTips(card.firstAidId)"
          >
            退出
          </div>
        </div>
      </div>
    </scroll-view>
    <div class="add-patient" @click="jump">
      <u-icon color="#fff" size="40" name="plus"></u-icon>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex';

export default {
  props: {},
  data: () => ({
    height: '',
    name: '', // 搜索框患者名称
    provinces: [
      {
        label: '急救患者',
        value: 0,
      },
      {
        label: '出院患者',
        value: 1,
      },
    ],
    tval: 0, // 默认选择的患者类型: 急救患者
    pageNum: 1, // 默认查询第一页的数据
    patientList: [], // 患者列表
    total: '', // 列表共有多少条数据
    role: '',
    show: false, // 是否显示删除modal框
    show1: false, // 是否显示退出急救的modal框
    delFirstAidId: '', // 即将要删除的患者的急救id
    firstAidId: '',
    quitId: '', // 将要退出急救的患者的急救id
    startX: 0, // 当前滑动的距离
    outIndex: -1, // 当前哪个card处于左滑选择可以单击退出的位置
    isMove: false, // 当前是否处于滑动状态
  }),
  computed: {
    ...mapState('carbasics', ['globalData', 'refreshList']),
    ...mapGetters('project', ['projectId']),
  },
  mounted() {
    const system = uni.getSystemInfoSync();
    this.height = system.windowHeight - 33 - 38 - 52 + 'px';
    console.log('this.height: ', this.height);
  },

  created() {
    this.getData(true);
  },
  methods: {
    ...mapMutations('carbasics', ['setFirstAidId', 'setDetailValueType']),
    jump() {
      uni.navigateTo({ url: `/pages/establish/establish?role=${this.role}` });
    },
    // 鼠标按下事件
    start(event) {
      if (event.touches) {
        this.startX = event.touches[0].clientX;
        // console.log(event.touches[0].clientX);
      }
      this.isMove = true;
    },
    // 鼠标松开事件
    end() {
      this.isMove = false;
    },
    // 拖动box事件
    move(event, index) {
      if (this.isMove) {
        if (this.outIndex === index) {
          this.outIndex = -1;
        } else {
          if (event.touches && (event.touches[0].clientX - this.startX > 10 || event.touches[0].clientX - this.startX < -10)) {
            this.outIndex = index;
          }
        }
      }
      this.isMove = false;
    },
    // 退出急救
    quitTips(id) {
      this.quitId = id;
      this.show1 = true;
    },
    // 退出急救二次确认
    async confirmBack() {
      try {
        const param = { firstAidId: this.quitId, projectId: this.projectId };
        const res = await uni.$u.api.quitAid(param);
        this.getData(true);
        this.visible1 = false;
      } catch (error) {
        this.$refs.uToast.show({
          title: '退出失败',
          type: 'error',
        });
      }
      this.outIndex = -1;
    },
    // 用户点击患者card时,判断是否已经被接诊
    // 如果没有被接诊,这自动选择接诊该患者
    // 如果已经接诊,则直接跳转到患者的信息录入目录中
    changeTimeLine(recordUserId, firstAidId, caseType, demonstrate) {
      try {
        if (!(recordUserId - 0)) {
          this.changeShow(firstAidId, caseType, demonstrate);
        } else {
          this.setFirstAidId(firstAidId);
          this.setDetailValueType(demonstrate);
          // this.$router.push(`/patient-line`);
          uni.navigateTo({ url: `/pages/patientLine/patientLine?caseType=${caseType}` });
        }
      } catch (error) {
        this.$refs.uToast.show({
          title: '切换失败',
          type: 'error',
        });
        0;
      }
    },
    // 判断当前用户是否为医生,如果是医生,则将该患者加入急救
    changeShow(id, caseType, demonstrate) {
      if (this.role === 'YiSheng') {
        // 只有加入急救的时候用到了这个急救id,但还是存了起来
        // 这里存起来的原因,是因为目前只有神内路线,当神外路线打开后,需要选择神内/神外才能加入,所以需要存储
        this.firstAidId = id;
        this.handleOk(this.globalData.createAuth - 0 === 0 ? 1 : 0, caseType, demonstrate);
        // this.visible = true; // 神内/神外选择加入
      }
    },
    // 将患者加入急救
    async handleOk(type, caseType, demonstrate) {
      try {
        const { projectId, firstAidId } = this;
        const param = {
          projectId,
          firstAidId,
          type,
        };
        const res = await uni.$u.api.joinAid(param);
        if (res) {
          this.$refs.uToast.show({
            title: '加入成功',
            type: 'success',
          });
          const codeAndAnswerList = [
            {
              questionCode: 'JKJY-SFXJ',
              answer: ['是'],
            },
            {
              questionCode: 'JKJY-XJFS',
              answer: ['集体病区教育'],
            },
            {
              questionCode: 'YJJL-CTendTime-outSide',
              answer: ['否'],
            },
          ];
          const setParam = {
            codeAndAnswerList,
            firstAidId,
          };
          uni.$u.api.setRecord(setParam);
          this.getData(true);
          this.setFirstAidId(firstAidId);
          this.setDetailValueType(demonstrate);
          // this.$router.push(`/patient-line`);
          uni.navigateTo({ url: `/pages/patientLine/patientLine?caseType=${caseType}` });
        } else {
          this.$refs.uToast.show({
            title: '加入失败',
            type: 'error',
          });
        }
      } catch (error) {
        this.$refs.uToast.show({
          title: error,
          type: 'error',
        });
      }
    },
    // 长按事件
    longpress(delFirstAidId) {
      this.delFirstAidId = delFirstAidId;
      this.show = true;
    },
    async confirmDel() {
      try {
        const param = { firstAidId: this.delFirstAidId };
        const res = await this.$u.api.delDemo(param);
        this.getData(true);
      } catch (error) {
        console.log('error: ', error);
      }
    },
    // 获取列表数据
    async getData(status) {
      try {
        // status 是否是重新请求数据,如果是重新请求数据,则清空页码和已查询的数据
        if (status) {
          this.pageNum = 1;
          this.patientList = [];
        }
        const params = {
          param: {
            firstAidType: this.tval,
            name: this.name,
            type: this.globalData.powerType,
            projectId: this.projectId,
            caseType: this.globalData.createAuth - 0 === 0 ? 1 : 0,
            pageNum: this.pageNum,
            pageSize: 10,
          },
        };
        const data = await this.$u.api.querySelf(params);
        if (data.page.list.length) {
          if (status) {
            this.patientList = data.page.list;
          } else {
            this.patientList = this.patientList.concat(data.page.list);
          }
          this.total = data.page.total;
          this.role = data.role;
        } else {
          this.$t.ui.showToast('没有更多数据');
        }
      } catch (error) {
        console.log('error: ', error);
      }
    },
    // 改变急救类型时,重新查询数据
    changeSelect(e) {
      this.tval = this.provinces[e].value;
      this.getData(true);
    },
    searchBlur() {
      setTimeout(() => this.getData(true), 10);
    },
    // scroll-view滚动到底部时,触发查询下一页数据
    scrolltolower() {
      this.pageNum++;
      this.getData(false);
    },
  },
  watch: {
    refreshList() {
      setTimeout(() => {
        this.getData(true);
      }, 300);
    },
  },
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.add-patient {
  z-index: 10;
  border-radius: 50%;
  height: 40px;
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #0284c7;
  position: fixed;
  bottom: 100px;
  right: 16px;
}
.patient-list {
  background-color: #fff;
}
.title {
  height: 52px;
  width: 750rpx;
  padding: 8px 16px;
  // position: fixed;
  // top: 32px;
  background: #fff;
  box-shadow: 0 0 4px 4px #ccc;
}
.card-box {
  /* box-shadow: 0 0 5px #ccc; */
  border: 2px solid #ccc;
  margin: 16px 0;
  border-radius: 8px;
  overflow: hidden;
}
.anima {
  transition: all 0.5s;
  position: relative;
}
.crad-content {
  font-size: 14px;
  color: #414141;
  padding: 12px;
}
.status-wait {
  position: absolute;
  right: 6px;
  top: 6px;
  height: 14px;
  width: 14px;
  border-radius: 50%;
  background: #ff8f00;
  box-shadow: 0 0 5px #ff8f00;
}
.fw-bold {
  font-size: 16px;
  font-weight: bold;
}
.sign-out {
  background-color: red;
  font-size: 14px;
  color: #fff;
  z-index: 10;
}
.list-box {
  padding: 16px;
}
.patients {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 0;
}
.card-total {
  padding: 0 8px;
  border-radius: 10px;
  background-color: #009dff;
  color: white;
}
.img-box {
  position: absolute;
  top: 14px;
  width: 44px;
  height: 44px;
  right: 16px;
}
</style>
