<template>
    <div class="main-page">
    <div class="main-page-header">
      <p class="title">院内急救信息</p>
      <el-form :inline="true" :model="searchForm" ref="searchForm" size="small" class="InHosFirstAid_form">
        <el-form-item  prop="hospitalCode" label="选择医院">
            <!-- <el-select v-model="searchForm.hospitalCode" placeholder="请选择医院名称" :disabled="roleId==2">
                <el-option  v-for="item in hospitalList"  :key="item.code"  :label="item.Name"  :value="item.code"></el-option>
            </el-select> -->

          <el-select
            v-model="searchForm.hospitalCode"
            placeholder="请选择医院名称"
            style="width: 100%"
            filterable
            :disabled="roleId == 2"
            remote
            :loading="selectLoading"
            :remote-method="remoteMethod"
            :clearable="true"
          >
            <el-option
              v-for="item in hospitalList"
              :label="item.hospitalName"
              :key="item.id"
              :value="item.hospitalCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item  prop="rangeDate"  label="上传时间">
          <el-date-picker type="daterange" start-placeholder="开始日期"   end-placeholder="结束日期"  v-model="searchForm.rangeDate"   prefix-icon="el-icon-date"   format="yyyy-MM-dd"  value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <div class="btns">
          <el-button  type="primary"  size="small"  @click="BTNClickSearch">查询</el-button>
          <el-button  size="small"   @click="resetForm('searchForm')">重置</el-button>
          <el-button v-if="roleId==2"  size="small"   @click="$refs.FileInputEl.click()">导入EXCEL</el-button>
          <el-button v-if="roleId==2"  size="small" @click="downloadFile">模板下载</el-button>
        </div>
      </el-form>
      <div style="display:none;">
        <input type="file"  ref="FileInputEl"  @change="changeSelectFileFn"  accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
      </div>
    </div>
    <div class="main-page-body">
      <div class="mainContent InHosFirstAid">
        <div class="bt tab-btn">
            <el-button :class="{active:activeTab=='1'}"  @click="changeTab(`1`)">胸痛中心</el-button>
            <el-button :class="{active:activeTab=='2'}"  @click="changeTab(`2`)">卒中中心</el-button>
        </div>
        <div class="table-cont">
          <table-mixin :pageSize="pageSize" :pageNum="pageNum"  :total="total"  :pagination="pagination"  :handleSizeChange="handleSizeChange"  :handleCurrentChange="handleCurrentChange">
            <el-table  style="width:100%" :fit="true"  border v-loading="tableData.loading"  :data="tableData.body"  @sort-change="handleSortChange">
              <div  slot="empty"  class="noData"></div>
              <el-table-column  v-for="(item,index) in tableData.head"  :prop="item.key"  :label="item.name"  align="left"  :formatter="item.formatter"  :sortable="item.sortable" :fixed="item.fixed"  :key="item.key+'_'+index"  :min-width="item.width"></el-table-column>
            </el-table>
          </table-mixin>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { tableDataMixin } from '@/common/js/mixin';
import { getList, queryHospitalList ,uploadExcel} from '@/api/hospital';
import { mapGetters } from 'vuex';
export default {
  mixins: [tableDataMixin],
  data() {
    var d=new Date();var yar=d.getFullYear(),month=d.getMonth()+1,day=d.getDate();month=(month<10)?('0'+month):(month);day=(day<10)?('0'+day):(day);
    let oDate=[`${yar}-01-01`,`${yar}-${month}-${day}`];
    return {
      roleId:null,
      activeTab:'1',
      hospitalList:[],
      searchForm: {
        hospitalCode:'',
        rangeDate:oDate
      },
      patientTypeList: [],
      selectLoading: false,
      queryParams: {

      },
      tableData: {
        loading: false,
        head:[],
        body: [],
        option: [],
        condition: []
      }
    }
  },
  computed:{
     ...mapGetters(['userInfo']),
     TableField:function(){ return((this.activeTab==1)?([{name:"门诊ID",key:"certificateNo"},{name:"姓名",key:"name"},{name:"性别",key:"gender"},{name:"年龄",key:"age"},{name:"电话",key:"phoneNo"},{name:"住院ID",key:"inPatientId"},{name:"发病时间",key:"attackTime"},{name:"初步诊断",key:"firstDiagnosis"},{name:"诊断时间",key:"diagnosisTime"},{name:"来院方式",key:"toHospitalWay"},{name:"到达医院大门时间",key:"toHospitalTime"},{name:"首次医疗接触时间",key:"firstContactTime"},{name:"首诊医师接诊时间",key:"firstDoctorContactTime"},{name:"转出医院名称",key:"transferOutHospitalName"},{name:"转出医院入门时间",key:"transOutIntoTime"},{name:"转出医院出门时间",key:"transOutLeaveTime"},{name:"心电图采集时间",key:"ecgCollectTime"},{name:"心电图诊断时间",key:"ecgDiagTime"},{name:"肌钙蛋白抽血时间",key:"bloodDrawingTime"},{name:"肌钙蛋白报告时间",key:"bloodReportTime"},{name:"肌钙蛋白检测值",key:"checkValue"},{name:"请会诊时间",key:"consulationTime"},{name:"会诊到达时间",key:"consulationArriveTime"},{name:"抗血小板治疗药物",key:"antiplateMedical"},{name:"抗血小板给药时间",key:"antiplateTime"},{name:"抗凝给药时间",key:"anticoaTime"},{name:"再灌注措施",key:"refersionMessure"},{name:"开始知情同意",key:"startInformedConsent"},{name:"签署知情同意",key:"signInformedConsent"},{name:"启动导管室时间",key:"startCatherRoomTime"},{name:"激活导管室时间",key:"activeCatherRoomTime"},{name:"导丝通过时间",key:"guideWirePassTime"},{name:"溶栓开始时间",key:"startThrombolysisTime"},{name:"溶栓结束时间",key:"endThrombolysisTime"},{name:"出院诊断",key:"dischargeDiagnosis"}]):([{name:"序号",key:"idx"},{name:"住院号",key:"hospitalId"},{name:"病患姓名",key:"name"},{name:"性别",key:"gender"},{name:"年龄",key:"age"},{name:"初步诊断",key:"firstDiagnosis"},{name:"诊断时间",key:"diagnosisTime"},{name:"治疗类型",key:"treatmentType"},{name:"住院时间",key:"inHospitalTime"},{name:"入院途径",key:"admissionRoute"},{name:"是否在院卒中",key:"isInHospitalStroke"},{name:"来院方式",key:"toHospitalWay"},{name:"发病时间",key:"attackTime"},{name:"患者到院时间",key:"toHospitalTime"},{name:"患者到达急诊科时间",key:"arrivedEmergencyTime"},{name:"申请会诊时间",key:"consulationTime"},{name:"卒中团队到达急诊科时间",key:"stokeArrivedEmergencyTime"},{name:"患者离开急诊科时间",key:"leaveEmergencyTime"},{name:"患者到达CT时间",key:"arriveCtTime"},{name:"患者到达MRI时间",key:"arriveMrTime"},{name:"获得CT结果时间",key:"getCtTime"},{name:"获得MRI结果时间",key:"getMriTime"},{name:"抽血开始时间(院内首次)",key:"firstBloodTime"},{name:"血液样本送达检验科时间",key:"sampleDeliverLabTime"},{name:"获得血常规时间",key:"bloodRoutineTime"},{name:"获取凝血常规时间",key:"coagulationRoutineTime"},{name:"获取肾功能结果时间",key:"renalFunctionTime"},{name:"获取电解质结果时间",key:"electrolyteTime"},{name:"开始溶栓知情同意",key:"startInformedConsent"},{name:"签署知情同意时间",key:"signInformedConsent"},{name:"首剂给药时间",key:"firstMedicalTime"},{name:"开始穿刺时间",key:"startPunctureTime"},{name:"穿刺成功时间",key:"successPunctureTime"},{name:"血管再通时间",key:"recanalizationTime"},{name:"出院时间",key:"dischargeTime"},{name:"急诊科耗时",key:"emergencyCostTime"},{name:"发病时长",key:"durationOfOnset"},{name:"患者入院-抽血开始时间耗时",key:"admissionDrawingTime"},{name:"抽血开始时间-血液送达检验科耗时",key:"drawingLabTime"},{name:"血液样本送达检验科-血常规结果时间（≤10分钟）",key:"labGetRoutineTime"},{name:"DNT时长",key:"dntOfTime"},{name:"DIT时长",key:"ditOfTime"},{name:"DTP时长",key:"dtpOfTime"},{name:"DRT时长",key:"drtOfTime"},{name:"急诊接诊医生",key:"emergencyDoctor"},{name:"急诊接诊护士",key:"emergencyNurse"},{name:"溶栓医生",key:"thrombolysisDoctor"},{name:"介入医生",key:"interventionalDoctor"}])) },
  },
  created(){
    this.roleId = this.userInfo.roleId
    this.ChangeSetTableHead()
    if (this.roleId == 2) {
      console.log(this.userInfo)
      this.hospitalList = [{
        hospitalCode: this.userInfo.hospitalCode,
        hospitalName: this.userInfo.hospitalName,
      }];
      this.searchForm.hospitalCode = this.userInfo.hospitalCode
    } else if (this.roleId == 1) {
      //获取可选择的医院
      queryHospitalList().then(res => {
        this.hospitalList = res.respData
      })
    } else if (this.roleId == 3) {
      //获取可选择的医院
      queryHospitalList({}, '', this.userInfo.area).then(res => {
        this.hospitalList = res.respData
      })
    }
  },
  mounted() {
      this.search()
  },
  methods: {
    BTNClickSearch(){
        this.pageNum=1;
        this.search();
    },
    changeSelectFileFn(e){
        var that=this;
        var File=e.target.files[0]
        var formData=new FormData();
        formData.append('file',File);
        formData.append('productType',that.activeTab);
        uploadExcel(formData).then(res=>{
            that.$refs.FileInputEl.value="";
            if (res.msg == 201) {
              that.$message.success(res.content||'上传成功');
              that.search();
            } else {
              that.$message.error(res.content||"上传失败");
            }
        })
    },
    ChangeSetTableHead(){
        var that=this;
        var tableHead=that.TableField;
        var head=tableHead.map(function(item,index){
            var oc={name:item.name,key:item.key}
            oc.fixed=!!(index<2);
            oc.sortable=false;
            oc.width=null;
            if(oc.name.indexOf('姓名')!=-1){
               oc.width='150';
            };            
            if((oc.name.indexOf('时间')!=-1)&&(oc.name.indexOf('-')!=-1)){
                oc.width='100';
            }else if(oc.name.indexOf('时间')!=-1){
                oc.width='165';
            };
            if(oc.name=='门诊ID'){
              oc.width='100';
            }else if(oc.name=='电话'){
              oc.width='120';
            }else if(oc.name=='年龄'){
              oc.width='80';
            }else if(oc.name=="性别"){
              oc.width='80';
              oc.formatter=(function(row, column, cellValue, index){
                  if(cellValue =='1'){  return `男`  }else if(cellValue =='2'){   return `女`  }else{  return `未知` };
              });
            }else if(oc.name=='出院诊断'){
                oc.width='850';
            }
            return Object.freeze(oc);
        });
        that.tableData.head=Object.freeze(head);
    },
    changeTab(num){
      this.activeTab=num;
      this.search();
    },
    getTableData() {
      var that=this;
      that.tableData.loading = true;
      that.ChangeSetTableHead();
      var Code=that.searchForm.hospitalCode;
      var startDate="",endDate="";
      if(that.searchForm.rangeDate&&Array.isArray(that.searchForm.rangeDate)){
          startDate=(that.searchForm.rangeDate)[0];
          endDate=(that.searchForm.rangeDate)[1];
      }
      var result=that.hospitalList.find(function(co){ return co.code==Code;});
      var hName="";
      if(result){  hName=result.Name; }
      const params = {
        productType:that.activeTab,
        startDate:startDate,
        endDate:endDate,
        hospitalCode:Code,
        hospitalName:hName,
        pageNo: that.pageNum,
        pageSize: that.pageSize
      };
      if(that.roleId==3){
          params.area=that.userInfo.area;
      }
      getList(params).then((res)=>{
        if(res.msg==201){
          var tableField=that.TableField;
          res.respData.list=(Array.isArray(res.respData.list)?(res.respData.list):[]).map(function(row){
              var rowobj={};
              tableField.forEach(function({key}){ rowobj[key]=(row[key])?(row[key]):``;(row[key]===undefined)?(console.log("列表数据缺少字段："+key )):null })
              return rowobj;
          });
          that.dealTableResponse(res)
        }else{
          that.$message.error(res.content)
        }
      })
    },
    logTypeFormatter(row, column, cellValue, index) {
      const logType = this.logTypeList.find(i => i.val === cellValue)
      return logType ? logType.name : ''
    },
    goDetail(type, row) {
      const query = {
        type: type
      }
      if (type === 'update' || type === 'detail') {
        query.patientType = row.patientType
        query.associationId = row.associationId
      }
      const routerData = this.$router.resolve({
        path: '/business/hospital/detail',
        query: query
      })

      window.open(routerData.href, '_blank')
    },
    downloadFile() {
      var a = document.createElement('a')
      let href = "", fileName = ''
      if (this.activeTab == '1') {
        href = "/mdxtpt/static/xls/chest.xls"
        fileName = "胸痛上报模板.xls"
      } else if (this.activeTab == '2') {
        href = "/mdxtpt/static/xls/stroke.xls"
        fileName = "卒中上报模板.xls"
      }
      console.log(href)
      a.href = href
      a.download = fileName
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    remoteMethod(query) {
      this.selectLoading = true;
      let area = ''
      if (this.roleId == 3) {
        area = this.userInfo.area
      }
      queryHospitalList({}, query, area).then(res => {
        this.hospitalList = res.respData
        this.selectLoading = false;
      })
    },
  }
};
</script>

<style lang="scss"   >
.InHosFirstAid{
    .el-input.is-disabled .el-input__inner{
        color:#606266;
    }
    .tab-btn{
       font-size:0; 
       button.el-button{
           position: relative;
           font-size:14px;
           border-radius:0;
           margin-left:0;
           margin-right:0;
           &.active{
               border-color:#FFF;
               color:#3B88D9;
               &:before{
                    content: "";
                    display: inline-block;
                    width: 10px;
                    height: 10px;
                    background-color:#3B88D9;
                    margin-right: 8px;
                    border-radius:50%;
               }
           }
       } 
    }
    .table-cont{
      padding:20px;
    }
} 
</style>
<style lang="scss">
.InHosFirstAid_form .el-input.is-disabled .el-input__inner{
    color:#606266;
}
</style>