<template>
  <div class="page_timePersonal">
    <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"
        :picker-options="pickerOptions"
      ></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"
        :picker-options="pickerOptions"
      ></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">
        <div class="tableTitle">统计表</div>
        <el-table :data="DialysisData" style="width: 100%" border :row-style="{ color: '#303133' }" 
        :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
        >
          <el-table-column prop="name" label="姓名" width="140">
            <!-- <template slot-scope="scope">{{ scope.row.name }}</template> -->
          </el-table-column>
          <el-table-column  label="年龄" width="140">
             <template slot-scope="scope">{{ getAge(scope.row.id_card_no) }}</template>
          </el-table-column>
          <el-table-column prop="dialysis_no" label="透析号" width="140">
              <!-- <template slot-scope="scope">{{ scope.row.dialysis_no }}</template> -->
          </el-table-column>
          <el-table-column prop="mode_id" label="透析模式">
              <template slot-scope="scope">
                <span>{{ scope.row.mode_id.join("、") }}</span>
              </template>
           </el-table-column>
          <el-table-column prop="address" label="透析总次数" width="140">
            <template slot-scope="scope">
                <span>{{ getDialysisCount(scope.row.patient_id)}}</span>
              </template>
          </el-table-column>
        </el-table>

        <el-pagination
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[20, 40, 60, 80, 100]"
          :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,getDialysisList,getDialysisDetailById,getPrescriptionByName } from "@/api/common/common";
 import { uParseTime } from "@/utils/tools";
export default {
  data() {
    return {
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 20
      },
      DialysisCount:[],
      total:0,
      options: [],
      value: "请选项",
      tableData: [],
      DialysisData: [],
      patientsData:[],
      prescriptionList:[],
      limit:1000,
      page:1,
      pickerOptions: {
        disabledDate(time) {
          let threeMonths = new Date(new Date().setFullYear(new Date().getFullYear()-1)).getTime() - 24 * 3600 * 1000;
          return time.getTime() > Date.now() || time.getTime() < threeMonths;;
        }
      }, 
      patient_id:0,
    };
  },
  methods: {
    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.getDialysisList()
      }
      
    },
    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.getDialysisList()
      }
    },
   getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    getCurrentOrgPatients(){
      getCurrentOrgPatients().then(response=>{
         if(response.data.state == 1){
           var patients = response.data.data.patients
           this.patientsData = patients
         }
      })
    },
    getTime(time) {
      return uParseTime(time, "{y}-{m}-{d}");
    },
    handleSizeChange(limit) {
      this.listQuery.limit = limit;
      this.getDialysisList();
    },
    handleCurrentChange(page) {
      this.listQuery.page = page;
      this.getDialysisList();
    },
    getDialysisList(){
      getDialysisList(this.listQuery.start_time,this.listQuery.end_time,this.listQuery.page,this.listQuery.limit).then(response=>{
         if(response.data.state === 1){
          var list = response.data.data.list
          console.log("list",list)
          var totallist  =  response.data.data.totallist
           console.log("totallist",totallist)
          this.total = totallist  
          var prescriptionList = response.data.data.prescriptionList
          console.log("prescriptionList",prescriptionList)
          this.getModeId(prescriptionList)
          var count = response.data.data.count
          console.log("count",count)
          this.DialysisCount = count
          // for(let i=0;i<count.length;i++){
          //  for(let j=0;j<prescriptionList.length;j++){
          //    if(count[i].patient_id == prescriptionList[j].patient_id){
          //         prescriptionList[j].count = count[i].Count
          //    }
          //  }
          // }
          // console.log("prescriptionList",prescriptionList)
          let dataInfo = {}
          list.forEach((item, index) => {
            let { patient_id } = item
            if (!dataInfo[patient_id]) {
              dataInfo[patient_id] = {
                patient_id,
                name:item.name,
                id_card_no:item.id_card_no,
                dialysis_no:item.dialysis_no,
                total_dialysis:item.total_dialysis,
                user_sys_before_count:item.user_sys_before_count,
                mode_id: []
              }
            }
          })
          let list = Object.values(dataInfo)
          console.log("arr",list)    
          list.map(item => {
            for (let i = 0; i < prescriptionList.length; i++) {
              if (item.patient_id === prescriptionList[i].patient_id) {
                item.mode_id.push(prescriptionList[i].mode_id)
              }
            }
          })
        //  console.log("list---",list)
          this.DialysisData = list
         }
      })
    },
    getAge(UUserCard) {
			if (UUserCard != null && UUserCard != '') {
				//获取年龄
				var myDate = new Date();
				var month = myDate.getMonth() + 1;
				var day = myDate.getDate();
				var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
				if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
					age++;
				}
				return age;
			}
    },
    getDialysisCount(id){
       var count = 0
       for(let i=0;i<this.DialysisCount.length;i++){
           if(id == this.DialysisCount[i].patient_id){
              count = this.DialysisCount[i].Count
           }
       }
       return count
    },
    onSearch(){
      if(this.listQuery.search == "" || this.listQuery.search == null){
         this.getDialysisList()
         return false
      }else{
       getPrescriptionByName(this.patient_id,this.listQuery.start_time,this.listQuery.end_time,this.limit,this.page).then(response=>{
         if(response.data.state === 1){
           var patients =  response.data.data.patient
           this.getModeId(patients)
           //console.log("patient",patients)
           var hash = {};
           var i = 0;
           var res = [];
           patients.forEach(function(item) {
            var patient_id = item.patient_id;
            hash[patient_id] ? res[hash[patient_id] - 1].mode_id.push(item.mode_id) : hash[patient_id] = ++i && res.push({
                mode_id: [item.mode_id],
                patient_id: patient_id,
                dialysis_no: item.dialysis_no,
                name:item.name,
                id_card_no:item.id_card_no,
                total_dialysis:item.total_dialysis,
                user_sys_before_count:item.user_sys_before_count,
            })
           });
           this.DialysisData = res
           var total =  response.data.data.total
           this.total = res.length
          // console.log("total",total)
         }
       })
      }
    
    },
    unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.mode_id) && res.set(arr.mode_id, 1));
      },
    handleChange(val){
       getDialysisDetailById(val.id,this.listQuery.start_time,this.listQuery.end_time,this.limit,this.page).then(response=>{
          if(response.data.state === 1){
            var patients =  response.data.data.patients
            this.getModeId(patients)
            // console.log("patients",patients)
            var hash = {};
            var i = 0;
            var res = [];
            patients.forEach(function(item) {
              var patient_id = item.patient_id;
              hash[patient_id] ? res[hash[patient_id] - 1].mode_id.push(item.mode_id) : hash[patient_id] = ++i && res.push({
                  mode_id: [item.mode_id],
                  patient_id: patient_id,
                  dialysis_no: item.dialysis_no,
                  name:item.name,
                  id_card_no:item.id_card_no,
                  total_dialysis:item.total_dialysis,
                  user_sys_before_count:item.user_sys_before_count,
              })
            });
            this.DialysisData = res
           // console.log(res)
            var total =  response.data.data.total
            this.total = res.length
            // console.log("total",total)
          }
       })
     
    },
    getModeId(patients){
      for(let i=0;i<patients.length;i++){
        if(patients[i].mode_id == 1){
          patients[i].mode_id = "HD"
        }else if(patients[i].mode_id == 2){
          patients[i].mode_id = "HDF"
        }else if(patients[i].mode_id == 3){
          patients[i].mode_id = "HD+HP"
        }else if(patients[i].mode_id == 4){
          patients[i].mode_id = "HP"
        }else if(patients[i].mode_id == 5){
          patients[i].mode_id = "HF"
        }else if(patients[i].mode_id == 6){
          patients[i].mode_id = "SCUF"
        }else if(patients[i].mode_id == 7){
          patients[i].mode_id = "IUF"
        }else if(patients[i].mode_id == 8){
          patients[i].mode_id = "HFHD"
        }else if(patients[i].mode_id == 9){
          patients[i].mode_id = "HFHD+HP"
        }else if(patients[i].mode_id == 10){
          patients[i].mode_id = "PHF"
        }else if(patients[i].mode_id == 11){
          patients[i].mode_id = "HFR"
        }else if(patients[i].mode_id == 12){
          patients[i].mode_id = "HDF+HP"
        }else if(patients[i].mode_id == 13){
          patients[i].mode_id = "CRRT"
        }else if(patients[i].mode_id == 14){
          patients[i].mode_id = "腹水回输"
        }else if(patients[i].mode_id == 15){
            patients[i].mode_id = "HD前置换"
        }else if(patients[i].mode_id == 16){
            patients[i].mode_id = "HD后置换"
        }else if(patients[i].mode_id == 17){
            patients[i].mode_id = "HDF前置换"
        }else if(patients[i].mode_id == 18){
            patients[i].mode_id = "HDF后置换"
        }else if(patients[i].mode_id == 19){
          patients[i].mode_id = "IUF+HD"
        }
      }
    },
     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) {
        console.log("val",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.getDialysisList()
  }
};
</script>

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