<template>
  <div class="page_checkPersonal">
    <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"
              style="width:160px"
              >
             <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" style="text-align:left;">
        <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:160px">
        <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
           ref="singleTable"
          @current-change="handleChange"
          >
           <el-table-column prop="dialysis_no" label="透析号" width="70">
            <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="90">
            <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>
        <div>
          <line-chart :options="chart"></line-chart>
        </div>
      </div>
    </el-container>
  </div>
</template>


<script>
import { PostSearch} from '@/api/patient'
import echarts from "echarts";
import LineChart from "../../components/LineChart";
import { getCurrentOrgPatients,getInspectionTotalCount,getInspectionDetailById,getSearchPatientInfo } from "@/api/common/common";
export default {
  components: {
    LineChart
  },
  data() {
    return {
      patient_id:0,
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 10
      },
      value: "请选项",
      patientsData:[],
      tableData:[],
      chart: {
        tooltip: {},
        // legend: {
        //   data: ["次数"],
        //   left: 0
        // },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} %"
          },
          show: false
        },
        series: [
          {
            name: "次数",
            type: "bar",
            data: [],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: (params) => {
                  if(this.obj.length > 0){
                      let str = ''
                      str = params.data +'次' + '\n(参考值'+ this.obj[params.dataIndex] +'次)'
                    return str
                  }else{
                    let str = ''
                    str = params.data+'次'
                    return str
                  }
                }
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

              //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
              normal: {
                color: function(params) {
                  //我这边就两个柱子，大体就两个柱子颜色渐变，所以数组只有两个值，多个颜色就多个值
                  var colorList = [
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],

                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"]
                  ];

                  var index = params.dataIndex;
                  if (params.dataIndex >= colorList.length) {
                    index = params.dataIndex % colorList.length;
                  }

                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorList[index][0] },
                    // { offset: 0.5, color: colorList[index][1] },
                    { offset: 1, color: colorList[index][1] }
                  ]);
                },
                barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
              },

              //鼠标悬停时：
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ],
        dataZoom: [
          {
            // Y轴固定,让内容滚动
            type: 'slider',
            show: false,
            xAxisIndex: [0],
            start: 1,
            end: 20, // 设置X轴刻度之间的间隔(根据数据量来调整)
            zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 1,
            end: 20,
            zoomLock: true // 锁定区域禁止缩放
          }
        ]
      },
      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;;
        }
      }, 
      modesData: {
        xAxis: [],
        series: []
      },
      obj:[],
      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.getInspectionTotalCount()
      }
    },
    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.getInspectionTotalCount()
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    getCurrentOrgPatients(){
      getCurrentOrgPatients().then(response=>{
         var patients = response.data.data.patients
         for(let i=0;i<patients.length;i++){
            this.$refs.singleTable.setCurrentRow(patients[0])
            this.patient_id = patients[0].id
         }
         this.patientsData = patients
          //获取检验检查项目
         this.getInspectionTotalCount()
      })
    },
    getInspectionTotalCount(){
      this.modesData.series = []
      this.modesData.xAxis = []
      getInspectionTotalCount(this.listQuery.start_time,this.listQuery.end_time,this.patient_id).then(response=>{
        if(response.data.state === 1){
          var Inspection = response.data.data.Inspection
    
          this.tableData = Inspection
        
          var counts = response.data.data.counts
        
          var arr = []
          for(let i=0;i<Inspection.length;i++){
            for(let j=0;j<counts.length;j++){
              if(Inspection[i].inspection_major == counts[j].ProjectId){
                arr.push(counts[j])
              }
            }
          }
        
          // var arrtwo =  this.arrayDate(counts,this.normData)
          
          var hash = {};
          var i = 0;
          var res = [];
          arr.forEach(function(item) {
            var ProjectName = item.ProjectName;
            hash[ProjectName] ? res[hash[ProjectName] - 1].Count.push(item.Count) : hash[ProjectName] = ++i && res.push({
                Count: [item.Count],
                ProjectName: ProjectName,
                ProjectId: item.ProjectId,
                Sort:item.Sort,
            })
          });
          
          res.map(item => {
            item.Count = eval(item.Count.join('+'))
          })
          
          let arr1 = []
          this.tableData.map(it => {
            arr1.push(it.project_name)
          })

          arr1.forEach((item,index)=>{
            if(!(res[index] && item ==res[index].ProjectName)){
              res.splice(index,0,{Count:0, ProjectName: item, Sort: index+1})
            }
          })
          res.map(item => {
            this.modesData.series.push(parseInt(item.Count));
          })
          // console.log("this=====",this.tableData)
          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name);
            let time = new Date(this.listQuery.end_time) - new Date(this.listQuery.start_time)
            let day = parseInt(time / (1000 * 60 * 60 * 24))
            this.obj.push(Math.round(day / this.tableData[key].inspection_frequency))
          }
          
          this.chart.series[0].data = this.modesData.series
          this.chart.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.chart.xAxis.data)
        }
      })
    },

    //获取单个病人数据
    handleChange(val){
      this.modesData.series = []
      this.modesData.xAxis = []
       getInspectionDetailById(val.id,this.listQuery.start_time,this.listQuery.end_time).then(response=>{
          if(response.data.state === 1){
            var patientdetail = response.data.data.patientdetail
            // console.log("patientdetail",patientdetail)
            var arr=[]

          for(let i=0;i<this.tableData.length;i++){
            for(let j=0;j<patientdetail.length;j++){
              if(this.tableData[i].inspection_major == patientdetail[j].ProjectId){
                arr.push(patientdetail[j])
              }
            }
          }
          // console.log('arr',arr)
         
          
          var hash = {};
          var i = 0;
          var res = [];
          arr.forEach(function(item) {
            var ProjectName = item.ProjectName;
            hash[ProjectName] ? res[hash[ProjectName] - 1].Count.push(item.Count) : hash[ProjectName] = ++i && res.push({
                Count: [item.Count],
                ProjectName: ProjectName,
                ProjectId: item.ProjectId,
                Sort:item.Sort,
            })
          });
          
          res.map(item => {
            item.Count = eval(item.Count.join('+'))
          })
          
          let arr1 = []
          this.tableData.map(it => {
            arr1.push(it.project_name)
          })

          arr1.forEach((item,index)=>{
            if(!(res[index] && item ==res[index].ProjectName)){
              res.splice(index,0,{Count:0, ProjectName: item, Sort: index+1})
            }
          })
          res.map(item => {
            this.modesData.series.push(parseInt(item.Count));
          })
          // console.log("this=====",this.tableData)
          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name);
            let time = new Date(this.listQuery.end_time) - new Date(this.listQuery.start_time)
            let day = parseInt(time / (1000 * 60 * 60 * 24))
            this.obj.push(Math.round(day / this.tableData[key].inspection_frequency))
          }
          
          this.chart.series[0].data = this.modesData.series
          this.chart.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.chart.xAxis.data)
          //   for(let i=0;i<this.tableData.length;i++){
          //     for(let j=0;j<patientdetail.length;j++){
          //        if(this.tableData[i].inspection_major == patientdetail[j].ProjectId){
          //           arr.push(patientdetail[j])
          //        }
          //     }
          //   }
            
          //  let time = new Date(this.listQuery.end_time) - new Date(this.listQuery.start_time)
          //  let day = parseInt(time / (1000 * 60 * 60 * 24))
          //  console.log("tabledata",this.tableData)
          //   for (const key in this.tableData) {
          //     this.modesData.xAxis.push(this.tableData[key].project_name);
          //     if (key in arr) {
          //       this.modesData.series.push(parseInt(arr[key].Count));
          //       this.obj.push(Math.round(day / arr[key].InspectionFrequency))
          //     } else {
          //       this.modesData.series.push(0);
          //       this.obj.push(0)
          //     }
          //   }
          //   this.chart.series[0].data = this.modesData.series
          //   this.chart.xAxis.data = this.modesData.xAxis
          //   this.getArrLength(this.chart.xAxis.data)
          }
       })
    },

    //搜索功能
    onSearch(){
       this.modesData.series = []
       this.modesData.xAxis = []
      getSearchPatientInfo(this.patient_id,this.listQuery.start_time,this.listQuery.end_time).then(response=>{
         if(response.data.state  === 1){
           var PatientsInfo = response.data.data.PatientsInfo
          //  console.log("patientsInfo",PatientsInfo)
           var arr = []
        
          for(let i=0;i<this.tableData.length;i++){
            for(let j=0;j<PatientsInfo.length;j++){
              if(this.tableData[i].inspection_major == PatientsInfo[j].ProjectId){
                arr.push(PatientsInfo[j])
              }
            }
          }
          // console.log('arr',arr)
         
          
          var hash = {};
          var i = 0;
          var res = [];
          arr.forEach(function(item) {
            var ProjectName = item.ProjectName;
            hash[ProjectName] ? res[hash[ProjectName] - 1].Count.push(item.Count) : hash[ProjectName] = ++i && res.push({
                Count: [item.Count],
                ProjectName: ProjectName,
                ProjectId: item.ProjectId,
                Sort:item.Sort,
            })
          });
          
          res.map(item => {
            item.Count = eval(item.Count.join('+'))
          })
          
          let arr1 = []
          this.tableData.map(it => {
            arr1.push(it.project_name)
          })

          arr1.forEach((item,index)=>{
            if(!(res[index] && item ==res[index].ProjectName)){
              res.splice(index,0,{Count:0, ProjectName: item, Sort: index+1})
            }
          })
          res.map(item => {
            this.modesData.series.push(parseInt(item.Count));
          })
          // console.log("this=====",this.tableData)
          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name);
            let time = new Date(this.listQuery.end_time) - new Date(this.listQuery.start_time)
            let day = parseInt(time / (1000 * 60 * 60 * 24))
            this.obj.push(Math.round(day / this.tableData[key].inspection_frequency))
          }
          
          this.chart.series[0].data = this.modesData.series
          this.chart.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.chart.xAxis.data)
         }
      })
    },
    arrayDate(array1,array2){
        var array1 = array1;
        var array2 = this.tableData;
        var result = [];
        for(var i = 0; i < array2.length; i++){
            var obj = array2[i];
            var num = obj.inspection_major;   //staff_id   就是要对比的key
            var isExist = false;
            for(var j = 0; j < array1.length; j++){
                var aj = array1[j];
                var n = aj.ProjectId;
                if(n == num){
                    isExist = true;
                    break;
             }
            }
            if(!isExist){
                result.push(obj);
            }
        }
        return result;
    },
    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()
    },
    getArrLength(result){
      if(result.length > 10){
        var dataZoom_end = (10/result.length)*100;
        this.chart.dataZoom[0].end = dataZoom_end
      }else{
        var dataZoom_end = 100;
        this.chart.dataZoom[0].end = dataZoom_end
      }
    }
  },
  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()
   
  }
};
</script>

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