<template>
  <div class="resident-list">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
      :curmbThird="curmbThird"
      :jumPathThird="jumPathThird">
    </bread-crumb>
    <div class="f-main-content screenSet">
      <div>
        <div class="right-btn-group" v-if="activeName == 'first'">
          <el-button plain size="small" @click="deleteCurrentPatient">删除</el-button>
          <el-button type="primary" size="small" @click="editPatient">编辑</el-button>
        </div>
        <el-tabs v-model="activeName" @tab-click="tabChangeHandler">
          <el-tab-pane label="居民信息" name="first">
            <div class="section">
              <div class="has-header">
                <p>基本信息</p>
                <p class="right-p"><span>添加时间：{{patientInfo.createdTime}}</span><span>最后修改时间：{{ patientInfo.modifiedTime ? patientInfo.modifiedTime : patientInfo.createdTime}}</span></p>
              </div>
              <div class="item">
                <div><p class="title">居民姓名：</p><p class="info">{{(patientInfo.nickname || patientInfo.wechatNickname) | emptyFilter}}</p></div>
                <div><p class="title">身份证：</p><p class="info">{{patientInfo.idNo | emptyFilter}}</p></div>
              </div>
              <div class="item">
                <div><p class="title">出生日期：</p><p class="info">{{birthTimeDisplay | emptyFilter}}{{(patientInfo.age || patientInfo.age == 0) ? `、${patientInfo.age}岁` : ''}}</p></div>
                <div><p class="title">性别：</p><p class="info">{{patientInfo.sex | sexFileter}}</p></div>
              </div>
              <div class="item">
                <div><p class="title">民族：</p><p class="info">{{nationalityDes}}</p></div>
                <div><p class="title">常驻类型：</p><p class="info">{{patientInfo.permanentResidence | permanentFilter}}</p></div>
              </div>
              <div class="item">
                <div><p class="title">健康档案编号：</p><p class="info">{{patientInfo.fileLocator | emptyFilter}}</p></div>
                <div><p class="title">医保号：</p><p class="info">{{patientInfo.socialCard | emptyFilter}}</p></div>
              </div>
              <div class="has-header">数据记录</div>
              <div class="item wrap-p">
                <div><p class="title">诊断：</p><p class="info">{{showDiseaseName | emptyFilter}}</p></div>
                <div><p class="title">分组：</p><p class="info">{{showLabelName | emptyFilter}}</p></div>
              </div>
              <div class="has-header">联系方式</div>
              <div class="item">
                <div><p class="title">手机号：</p><p class="info">{{patientInfo.mobilePhone | emptyFilter}}</p></div>
                <div><p class="title"></p><p class="info"></p></div>
              </div>
              <div class="item">
                <div><p class="title">所在地区：</p><p class="info">{{patientInfo.patientAddress | emptyFilter}}</p></div>
                <div><p class="title">详细地址：</p><p class="info">{{patientInfo.address | emptyFilter}}</p></div>
              </div>
              <div class="item">
                <div><p class="title">工作单位：</p><p class="info">{{patientInfo.workplace | emptyFilter}}</p></div>
                <div>
                  <p class="title">微信：</p>
                  <p class="info" v-if="patientInfo.isWechatBind == '1'">未绑定 <el-button type="text" class="ml10" @click="remindBind"  style="color: #449284;" v-if="patientInfo.isRemind == '1'">提醒绑定</el-button><span class="ml10" v-if="patientInfo.isRemind == '2'">已提醒</span></p>
                  <!--<p class="info" v-else-if="patientInfo.isWechatBind == '2'">已绑定 <span class="ml10">（微信名：{{patientInfo.wechatNickname | emptyFilter}}）</span></p>-->
                  <p class="info" v-else-if="patientInfo.isWechatBind == '2'">{{patientInfo.wechatNickname | emptyFilter}}</p>
                  <p class="info" v-else>-</p>
                </div>
              </div>
              <div class="has-header">其他</div>
              <div class="item">
                <div>
                  <p class="title">备注：</p>
                  <p class="info">
                    <el-input
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 7}"
                      placeholder="请输入内容"
                      v-model="patientInfo.remark"
                      maxlength="200"
                      :show-word-limit="true"
                    >
                    </el-input>
                  </p>
                </div>
                <p class="btn-right"><el-button plain size="small" @click="saveRemark">保存备注</el-button></p>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="健康记录" name="second">
            <div class="health-record-list"
                 v-show="recordList.length"
                 v-infinite-scroll="loadMore"
                 :infinite-scroll-disabled="busy"
                 infinite-scroll-distance="5"
                 infinite-scroll-immediate-check="true">
              <div class="item" v-for="(item, index) in recordList" :key="index">
                <div class="record-date">{{item.finishedTime}}</div>
                <div class="record-content">
                  <div class="record-title">
                    <p>{{item.name}}-第{{item.seqNo}}次随访</p>
                    <span>{{item.fuTypeValue}}</span>
                  </div>
                  <div class="list-visit">
                    <span class="left-label">患教内容：</span>
                    <div class="right-item">{{item.sendContent | emptyFilter}}</div>
                  </div>
                  <div class="list-visit">
                    <span class="left-label">随访量表：</span>
                    <div class="right-item">
                      <p v-for="(item2, index2) in item.scaleSimpleDtos" :key="index2" v-if="item.scaleSimpleDtos.length">{{item2.name}}
                        <span class="check-btn" @click="openScaleDetail(item2.url)">查看量表</span>
                      </p>
                      <p v-if="!item.scaleSimpleDtos.length">暂无量表</p>
                    </div>
                  </div>
                </div>
              </div>
              <p style="text-align: center;padding:10px 0;cursor: pointer" v-if="hasMore">加载中...</p>
              <p style="text-align: center;padding:10px 0;cursor: pointer" v-if="!hasMore">没有更多了</p>
            </div>
            <div class="no-record-content" v-if="!recordList.length">
              <div>
                <img src="../../../assets/image/no-content1.png"/>
                <p>暂无随访记录或您没有权限访问</p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import BreadCrumb from '@/components/breadcrumb'
  import { mapGetters } from 'vuex'
  import { getDiseasesList, getPatientDetail, getRemindPatient, deletePatient, savePatientInfo, getHealthRecordList, getNationsList } from '@/utils/patients/patientsapi'
  export default {
    name: "patientDetail",
    components: {
      BreadCrumb,
    },
    data() {
      return {
        /*面包屑配置*/
        curmbFirst: '居民管理',
        curmbSecond: '我的居民',
        curmbThird: '居民详情',
        jumPathThird: '/patients-manage/mypatients-manage/patients-list',
        activeName: 'first',
        patientId: '',
        doctorId: '',
        patientInfo: {
          isWechatBind: 1,
          remark: '',
        },
        nationalityDes: '',
        showLabelName: '',
        showDiseaseName: '',
        birthTimeDisplay: '',
        recordList: [],
        hasMore: false,
        busy: false,
        pageNo: 1,
        pageSize: 15,
      }
    },
    created() {
      this.patientId = this.$route.query.patientId;
      this.init();
      this.getRecordList();
    },
    mounted() {
    },
    computed: {
      ...mapGetters([
        '_token',
      ])
    },
    methods: {
      init() {
        getPatientDetail(this.patientId).then((data) => {
          if(data.code == '000000') {
            this.patientInfo = data.data;
            if(this.patientInfo){
              this.doctorId = this.patientInfo.doctorId;
              let customLabels = this.patientInfo.customLabels;
              let diseases = this.patientInfo.diseases;
              let groupLabelNames = [];
              let groupDiseaseNames = [];
              //对出生日期的处理
              if(this.patientInfo.birthTime){
                let timeArr = this.patientInfo.birthTime.split('-');
                let mm = parseInt(timeArr[1]) < 10 ? `0${parseInt(timeArr[1])}` : parseInt(timeArr[1]);
                let dd = parseInt(timeArr[2]) < 10 ? `0${parseInt(timeArr[2])}` : parseInt(timeArr[2]);
                this.birthTimeDisplay = `${timeArr[0]}-${mm}-${dd}`;
              }else {
                this.birthTimeDisplay = '';
              }
              // 对分组的处理
              if(customLabels) {
                customLabels.forEach(item => {
                  groupLabelNames.push(item.label)
                });
                this.showLabelName = groupLabelNames.join('；');
              } else {
                this.showLabelName = '';
              }
              // 对诊断疾病的处理
              if(diseases) {
                diseases.forEach(item => {
                  groupDiseaseNames.push(item.diseaseName)
                });
                this.showDiseaseName = groupDiseaseNames.join('；');
              } else {
                this.showDiseaseName = '';
              }
            //  对民族的处理
            if(this.patientInfo.nationality) {
                let nationsList = [];
                getNationsList().then((data) => {
                if(data.code == '000000') {
                  nationsList = data.data;
                  nationsList.forEach(item => {
                    if(String(this.patientInfo.nationality) == item.code ) {
                      this.nationalityDes = item.name;
                    }
                    })
                  }
                })
            }else {
              this.nationalityDes = '-';
            }
            }
          }
        })
      },
      getRecordList() {
        let reqPara = {
          patientId: this.patientId,
          // patientId: '99997701',
          pageNo: this.pageNo,
          pageSize: this.pageSize,
        }
        getHealthRecordList(reqPara).then((data) => {
          if(data.code == '000000'){
            // this.recordList = data.data.healthRecordDtos;
            let healthRecordDtos = data.data.healthRecordDtos;
            let count = data.data.count;
            // if(flag) {
              this.recordList = this.recordList.concat(healthRecordDtos);
              if(count <= this.pageNo * this.pageSize) {
                this.busy = true;
                this.hasMore = false;
              }else {
                this.busy = false;
                this.hasMore = true;
              }
            // }else {
            //   this.recordList = healthRecordDtos;
            //   this.busy = false;
            //   this.hasMore = false;
            // }
          }else {
            this.$message.error(data.message)
          }
        })
      },
      tabChangeHandler(tab) {},
      deleteCurrentPatient() {
        // 把写的提示信息需要换行的地方分成数组 confirmText
        const confirmText = ['您确定要删除此居民吗?',  '删除后，您将无法对该居民发送患教和进行随访，重新添加该居民依旧可查看历史发送记录及随访记录'];
        const newDatas = [];
        const h = this.$createElement;
        for (const i in confirmText) {
          newDatas.push(h('p', null, confirmText[i]))
        }
        this.$confirm('删除居民', {
          title: '删除居民',
          message: h('div', null, newDatas),
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          closeOnPressEscape: false,
          type: 'warning'
        }).then(() => {
          let reqParam = {
            patientIdList: [this.patientId],
            token: this._token,
          };
          deletePatient(reqParam).then(data => {
            if(data.code == '000000') {
              this.$message({
                type: 'success',
                message: `${this.patientInfo.nickname}居民删除成功!`
              });
              setTimeout(()=>{
                this.$router.push({
                  path: '/patients-manage/mypatients-manage/patients-list'
                })
              },2000)
            }else {
              this.$message({
                type: 'error',
                message: data.message
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editPatient() {
        this.$router.push({
          path: '/patients-manage/mypatients-manage/basic-info',
          query: {
            patientId: this.patientId
          }
        })
      },
      //提醒绑定
      remindBind() {
        let remindMobileWechatPara = {
          qrcodeType: 1,
          patientId: this.patientId,
          // deviceInfo: window.getDeviceInfo()
        }
        getRemindPatient({
          ...remindMobileWechatPara
        }).then( data => {
          if(data.code == '000000') {
            this.$message.success(data.data.respMsg);
            this.init();
          }else {
            this.$message.error(data.message);
          }
        })
      },
      //保存备注
      saveRemark() {
        savePatientInfo(this.patientInfo).then(data => {
          if(data.code == '000000'){
            this.$message.success('保存备注成功')
            this.init();
          }else {
            this.$message.error(data.message);
          }
        })
      },
      //查看量表详情
      openScaleDetail(url) {
        window.open(url)
      },
      loadMore() {
        // console.log('触发加载页码',this.pageNo);
        this.busy = true; //把busy置位true，这次请求结束前不再执行
        setTimeout(() => {
          this.pageNo++;
          this.getRecordList()
          //调用获取数据接口，并且传入一个true，让axios方法指导是否需要拼接数组。
        }, 500)
      },

    },
    filters: {
      emptyFilter: function(value) {
        if (!value) {
          return '-';
        } else {
          return value;
        }
      },
      sexFileter: function(value) {
        if (!value && value != 0) {
          return '-';
        } else {
          let hash = {
            1: '男',
            2: '女'
          };
          return hash[value];
        }
      },
      permanentFilter: function (value) {
        if (!value) {
          return '-';
        } else {
          let hash = {
            1: '户籍',
            2: '非户籍'
          };
          return hash[value];
        }
      }
    },
  }
</script>
<style lang="scss" scoped>
  @import '../../../style/patients-style/element-reset.css';

  .f-main-content{
    background: #ffffff;
    padding: 30px;
    .right-btn-group{
      position: absolute;
      right: 60px;
      z-index: 1800;
    }
    .section{
      .item{
        display: flex;
        font-size: 14px;
        div{
          display: flex;
          flex: 1;
          line-height: 36px;
          .title{
            width: 150px;
            text-align: right;
          }
          .info{
            color: #999;
            padding-left: 15px;
            width: 100%;
          }
        }
        &.wrap-p{
          div{
            line-height: 28px;
          }
        }
        .btn-right{
          width: 35%;
          padding-left:10px;
        }
      }
      .has-header{
        display: flex;
        justify-content: space-between;
        padding: 15px 0;
        margin-bottom: 15px;
        border-bottom: 1px dashed #888;
        .right-p{
          display: inline-block;
          text-align: right;
          color: #999;
          font-size: 14px;
          span:last-child{
            margin-left: 15px;
          }
        }
      }
    }
    .health-record-list{
      /*height: 300px;*/
      overflow-y: auto;
      @media screen and (min-width:1240px) and (max-width:1545px){
        height: 300px;
      }
      @media screen and (min-width:1545px) and (max-width:1600px){
        height: 500px;
      }
      @media screen and (min-width:1600px){
        height: 650px;
      }
      &::-webkit-scrollbar{
        width:5px;
      }
      &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgba(0,0,0,0.1);
      }
      .item{
        width: 100%;
        margin-bottom: 15px;
        .record-date{
          color: #999;
          padding-bottom: 10px;
        }
        .record-content{
          width: 100%;
          border: 1px solid #E4E7ED;
          border-radius: 5px;
          padding: 10px 15px 13px;
          .record-title{
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            span{
              color: #999;
              font-size: 14px;
            }
          }
          .list-visit{
            line-height: 28px;
            padding: 6px 0 2px;
            display: flex;
            display: -webkit-flex;
            align-items: flex-start;
            font-size: 14px;
            color: #999;
            .left-label{
              line-height: 28px;
            }
            .right-item{
              flex: 1;
              line-height: 28px;
              p{
                line-height: 28px;
                .check-btn{
                  color: #449284;
                  cursor: pointer;
                  margin-left: 15px;
                }
              }
            }
          }
        }
      }
    }
    .no-record-content{
      @media screen and (min-width:1240px) and (max-width:1545px){
        height: 300px;
      }
      @media screen and (min-width:1545px) and (max-width:1600px){
        height: 500px;
      }
      @media screen and (min-width:1600px){
        height: 600px;
      }
      text-align: center;
      padding: 50px 0 60px;
      img{
        width: 120px;
      }
      p{
        color: #B9B9C6;
        font-size: 20px;
      }
    }
    .ml10{
      margin-left: 10px;
    }
  }
</style>
