<template>
  <div class="page_checkAll">
    <div class="cell clearfix">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label>
          <!-- <el-input v-model.trim="listQuery.search" placeholder="姓名/透析号" style="width:150px"></el-input>
          <el-button type="primary" @click="onSearch" icon="el-icon-search">搜索</el-button> -->
           <el-autocomplete
             class="checkSearch"
             popper-class="my-autocomplete"
             v-model.trim="listQuery.search"
             :fetch-suggestions="querySearchAsync"
             :trigger-on-focus="false"
             placeholder="输入病人透析号/姓名"
             @select="handleSelect"
              >
             <i class="el-icon-search el-input__icon" slot="suffix"></i>
               <template slot-scope="{ item }">
                  <div class="name">{{ item.name }}</div>
              </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
      <label class="title">
        <span class="name">日期查询</span> :
      </label>
      <el-date-picker
        v-model="listQuery.start_time"
        prefix-icon="el-icon-date"
        @change="changeTime"
        :editable="false"
        style="width: 196px;"
        type="date"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
      <span class>-</span>
      <el-date-picker
        v-model="listQuery.end_time"
        prefix-icon="el-icon-date"
        @change="changeEndTime"
        :editable="false"
        style="width: 196px;"
        type="date"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </div>
    <el-container>
      <div style="width:150px">
        <div class="tableTitle">患者列表</div>
        <el-table :data="patientsData" border style="width: 100%;" height="500" :row-style="{ color: '#303133' }"
        :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
         highlight-current-row
         @current-change="handleChange">
           <el-table-column prop="dialysis_no" label="透析号" width="80">
            <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="80">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div style="padding-left:10px;flex:1;width:0">
        <div class="tableTitle">统计表</div>
        <el-table :data="tableData" style="width: 100%" border :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
          <el-table-column prop="name" label="姓名" fixed>
            <template slot-scope="scope">{{ scope.row.name}}</template>
         </el-table-column>
         <el-table-column
          :label="modeItem.project_name+'('+modeItem.inspection_frequency+'天)'"
          property="number"
          align="center"
          min-width="110"
          v-for="(modeItem, index) in tableName"
          :key="index"
        >
          <template slot-scope="scope">
             <span v-if="Math.floor(90/modeItem.inspection_frequency) <= scope.row.data[index].Count" style="color:black">{{ scope.row.data[index].Count}}</span>
              <span v-if="Math.floor(90/modeItem.inspection_frequency) > scope.row.data[index].Count" style="color:red">{{ scope.row.data[index].Count}}</span>
          </template>
        </el-table-column>
        </el-table>

        <el-pagination
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40,50]"
          :page-size="10"
          background
          style="margin-top:20px;"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-container>
  </div>
</template>


<script>
  import { PostSearch} from '@/api/patient'
  import {getCurrentOrgPatients,getAllMajorInspection,getPatientList,getPatientDetailCheck,SearchDetailCheck } from "@/api/common/common"
export default {
  data() {
    return {
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 10
      },
      value: "请选项",
      tableData: [],
      patientsData:[],
      total:0,
      tableName:[],
      ObjectData:{},
      patient_id:0,
      patient_name:"",
    };
  },
  methods: {
    handleDelete(index, row) {
        console.log(index, row);
      },
    changeTime(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.listQuery.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.start_time = "";
      } else {
        this.getPatientList()
      }
    },
    onSearch(){
     getPatientDetailCheck(this.patient_id,this.listQuery.start_time,this.listQuery.end_time).then(response=>{
          if(response.data.state === 1){
            var checkDetail =  response.data.data.checkDetail
        
            var arr = []
            for(let i=0;i<checkDetail.length;i++){
              for(let j=0;j<this.tableName.length;j++){
                 if(checkDetail[i].ProjectId == this.tableName[j].inspection_major){
                   arr.push(checkDetail[i])
                 }
              }
            }

            let projectArr = []
            this.newArr.map(item => {
              projectArr.push(item.project_name)
            })
            projectArr.forEach((item,index) => {
              if(!(arr[index] && item == arr[index].ProjectName)){
                arr.splice(index,0,{Count:0, ProjectName: item,name: this.listQuery.search})
              }
            })
            this.tableData = []
            let obj = {}
            obj.name = this.listQuery.search
            obj.data = arr
            this.tableData.push(obj)
            this.total = 1
           
          }
      })
    },
     handleSizeChange(limit) {
      this.listQuery.limit = limit;
       this.getPatientList()
    },
    handleCurrentChange(page) {
      this.listQuery.page = page;
       this.getPatientList()
    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.end_time = "";
      } else {
        this.getPatientList()
      }
    },
    //获取病人列表
    getCurrentOrgPatients(){
      getCurrentOrgPatients().then(response=>{
         if(response.data.state === 1){
            var patients = response.data.data.patients
            this.patientsData = patients
         }
      })
    },
    //获取检验检查项目
    getAllMajorInspection(){
      getAllMajorInspection().then(response=>{
        if(response.data.state === 1){
           var inspection = response.data.data.inspection
           console.log("inspection",inspection)
           var a=[];
           for(let i=0;i<inspection.length;i++){
             a.push(inspection[i])
           }

           this.newArr = a
           var arr = this.arrayToObj(a)
           
      
           this.ObjectData = arr
           this.tableName = inspection
        }
      })
    },
    getPatientList(){
        this.tableData = []
      getPatientList(this.listQuery.start_time,this.listQuery.end_time,this.listQuery.limit,this.listQuery.page).then(response=>{
         if(response.data.state === 1){
           var patientInfo = response.data.data.patientInfo
           console.log("patientInfo",patientInfo)

           var total = response.data.data.total
        
           this.total = total
          var list = response.data.data.list
          console.log("counts",list)
          var dtd = []
          for(let i=0;i<list.length;i++){
              for(let j=0;j<this.tableName.length;j++){
                  if(list[i].ProjectId == this.tableName[j].inspection_major){
                    dtd.push(list[i])
                  }
              }
          }
   
          var dd = {};
           for (const index in dtd) {
            if (!(dtd[index].name in dd)) {
               dd[dtd[index].name] = {};
            }
            if (!(dtd[index].ProjectId in dd[dtd[index].name]) && dtd[index].ProjectId != 0) {
              dd[dtd[index].name][dtd[index].ProjectName] = dtd[index];
            }
          }
       
           
            for(const key in dd){
              for(const mkey in this.ObjectData){
                if (!(this.ObjectData[mkey].project_name in dd[key])) {
                  dd[key][this.ObjectData[mkey].project_name] = {
                    ProjectName: this.ObjectData[mkey].project_name,
                    name: mkey,
                    Count: 0
                  };
                }
              }
              this.tableData.push({ name: key, data: dd[key]});
            }
            console.log("表哥",this.tableData)
            let projectArr = []
          
            this.newArr.map(item => {
              projectArr.push(item.project_name)
            })
      
            this.tableData.map(item => {
              let arr = Object.values(item.data);
       
              arr.sort((a,b)=>{
                return projectArr.indexOf(a.ProjectName)-projectArr.indexOf(b.ProjectName);
              });
              item.data = arr
            })
         }
      })
    },
    handleChange(val){
      getPatientDetailCheck(val.id,this.listQuery.start_time,this.listQuery.end_time).then(response=>{
          if(response.data.state === 1){
            var checkDetail =  response.data.data.checkDetail
        
            var arr = []
            for(let i=0;i<checkDetail.length;i++){
              for(let j=0;j<this.tableName.length;j++){
                 if(checkDetail[i].ProjectId == this.tableName[j].inspection_major){
                   arr.push(checkDetail[i])
                 }
              }
            }

            let projectArr = []
            this.newArr.map(item => {
              projectArr.push(item.project_name)
            })
            projectArr.forEach((item,index) => {
              if(!(arr[index] && item == arr[index].ProjectName)){
                arr.splice(index,0,{Count:0, ProjectName: item,name: val.name})
              }
            })
            this.tableData = []
            let obj = {}
            obj.name = val.name
            obj.data = arr
            this.tableData.push(obj)
            this.total = 1
           
          }
      })
    },
   arrayToObj(arr){
      return Object.assign({},arr);
    },
  querySearchAsync(keyword, cb) {
        let key = ''
        if (keyword != undefined) {
          key = keyword
        }
        let searchArray = []
        PostSearch(key).then(response => {
          if (response.data.state == 1) {
             searchArray = response.data.data.patient
             console.log("searchArray",searchArray)
            cb(searchArray)
          } else {
            cb([])
          }
        })
      },
   handleSelect(val) {
        this.listQuery.search = val.name
        this.patient_id = val.id
        this.onSearch()
      },
  },
  created(){
     var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.listQuery.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 3);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();
    this.listQuery.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
       //获取该机构下的所有患者
     this.getCurrentOrgPatients()
     //获取检验检查项目
     this.getAllMajorInspection()
     //获取列表数据
     this.getPatientList()
  }
};
</script>

<style lang="scss" scoped>
.tableTitle {
  font-size: 16px;
  color: #000;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
<style lang="scss">
.page_checkAll {
  .cell {
    text-align: center;
  }
  ::-webkit-scrollbar{
    height: 15px !important;
  }
}
</style>
