<template>
  <div class="page_dialysisMonitor">
    <div class="searchBox">
      <el-autocomplete
        class="checkSearch"
        popper-class="my-autocomplete"
        v-model="search_value"
        :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>
    </div>


    <div class="optionsBox">
      <div class="toolOne" @click="startShow = true">
        <div style="display: flex;align-items: center;">
          {{  query.start_time }}

          <van-icon name="arrow-down" />
        </div>
      </div>
      <div class="toolOne" @click="endShow = true">
        <div style="display: flex;align-items: center;">
          {{ query.end_time }}

          <van-icon name="arrow-down" />
        </div>
      </div>
      <div class="optionsOne" @click="projectShow = true">
        <div style="display: flex;align-items: center;">
          {{ project }}
          <van-icon name="arrow-down" />
        </div>
      </div>
    </div>
    
    <div class="chart1">统计图&nbsp;&nbsp;<span style="font-weight:normal">（患者姓名:{{patient_name}}）</span></div>
    <div class="rangeBox" style="margin-top:.625rem">
      <p class="range"></p>
      <span>{{ project }}</span>
    </div>

    <div>
      <bar-chart :options="options"></bar-chart>
    </div>
    <div class="chart1" style="margin-bottom:0.625rem">统计表</div>
    <div>

      <el-table ref="tab" :data="tableData" style="width: 100%" :height="tableHeight" v-loadmore="loadMore" v-loading="loading" border :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
        <el-table-column fixed width="110" label="监测时间" align="center">
          <template slot-scope="scope">
            {{getTime(scope.row.operate_time)}}
          </template>
        </el-table-column>

        <el-table-column label="收缩压" align="center">
          <template slot-scope="scope">
            {{scope.row.systolic_blood_pressure?scope.row.systolic_blood_pressure:''}}
          </template>
        </el-table-column>

        <el-table-column label="舒张压" align="center">
          <template slot-scope="scope">
            {{scope.row.diastolic_blood_pressure?scope.row.diastolic_blood_pressure:''}}
          </template>
        </el-table-column>

        <el-table-column label="脉搏" align="center">
          <template slot-scope="scope">
            {{scope.row.pulse_frequency?scope.row.pulse_frequency:''}}
          </template>
        </el-table-column>

        <el-table-column label="呼吸" align="center">
          <template slot-scope="scope">
            {{scope.row.breathing_rate?scope.row.breathing_rate:''}}
          </template>
        </el-table-column>

        <el-table-column label="体温" align="center">
          <template slot-scope="scope">
            {{ scope.row.temperature?scope.row.temperature:''}}
          </template>
        </el-table-column>

        <el-table-column label="血流量" align="center">
          <template slot-scope="scope">
            {{ scope.row.blood_flow_volume?scope.row.blood_flow_volume:''}}
          </template>
        </el-table-column>

        <el-table-column label="静脉压" align="center">
          <template slot-scope="scope">
            {{ scope.row.venous_pressure?scope.row.venous_pressure:''}}
          </template>
        </el-table-column>


        <el-table-column label="动脉压" align="center">
          <template slot-scope="scope">
            {{ scope.row.arterial_pressure?scope.row.arterial_pressure:''}}

          </template>
        </el-table-column>

        <el-table-column label="跨膜压" align="center">
          <template slot-scope="scope">
            {{ scope.row.transmembrane_pressure?scope.row.transmembrane_pressure:''}}
          </template>
        </el-table-column>


        <el-table-column width='110' label="透析液温度" align="center">
          <template slot-scope="scope">
            {{ scope.row.dialysate_temperature?scope.row.dialysate_temperature:''}}
          </template>
        </el-table-column>

        <el-table-column label="超滤率" align="center">
          <template slot-scope="scope">
            {{ scope.row.ultrafiltration_rate?scope.row.ultrafiltration_rate:''}}
          </template>
        </el-table-column>

        <el-table-column label="超滤量" align="center">
          <template slot-scope="scope">
            {{ scope.row.ultrafiltration_volume?scope.row.ultrafiltration_volume:''}}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <scroll-top></scroll-top>

    <div>
      <van-popup v-model="projectShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="project_columns"
          @confirm="chooseProject"
          @cancel="projectShow = false"
        />
      </van-popup>
      <van-popup v-model="startShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime"
          @cancel="startShow = false"
        />
      </van-popup>
      <van-popup v-model="endShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime2"
          @cancel="endShow = false"
        />
      </van-popup>
    </div>
  </div>
</template>


<script>
import echarts from "echarts";
import BarChart from "../components/BarChart";
import ScrollTop from "../components/ScrollTop";
import {GetDialysisWatchChartData,GetDialysisWatchTableData,GetDefalutPatient} from "@/api/statistics";
import { uParseTime } from '@/utils/tools'
import {
  PostSearch,
} from "@/api/patient";

export default {
  components: {
    BarChart,
    ScrollTop
  },
  data() {
    return {
      patient_name:"",
      isStop:false,
      currentDate1: new Date(new Date().setMonth(new Date().getMonth() - 1)),
      currentDate2: new Date(),
      minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      currentDate: new Date(),
      maxDate: new Date(),
      search_value:'',
      loading:true,
      query: {
        patient_id: "",
        statistics_type: 1,
        start_time: "",
        end_time: "",
        limit:20,
        page:1,
      },

      tableHeight:'',
      value: "",
      project: "收缩压",
      projectShow: false,
      project_columns: ["收缩压", "舒张压", "脉搏", "呼吸", "体温","血流量", "静脉压","动脉压","跨膜压","透析液温度","超滤率","超滤量"],
      startShow: false,
      endShow: false,
      startTime: "日期范围",
      endTime: "日期范围",
      options: {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["次数"],
          left: 0
        },
        xAxis: {
          data: [],
          axisLine: {
            lineStyle: {
              color: "#FF0000",
              width: 8 //这里是为了突出显示加上的
            }
          },
          axisLabel: {
            interval: 0,
            formatter: function(value) {
              var ret = ""; //拼接加\n返回的类目项
              var maxLength = 4; //每项显示文字个数
              var valLength = value.length; //X轴类目项的文字个数
              var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
              if (rowN > 1) {
                //如果类目项的文字大于3,
                for (var i = 0; i < rowN; i++) {
                  var temp = ""; //每次截取的字符串
                  var start = i * maxLength; //开始截取的位置
                  var end = start + maxLength; //结束截取的位置
                  //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                  temp = value.substring(start, end) + "\n";
                  ret += temp; //凭借最终的字符串
                }
                return ret;
              } else {
                return value;
              }
            },
          }
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} %"
          },
          show: false,
          axisLine: {
            lineStyle: {
              color: "#00FF00",
              width: 8 //这里是为了突出显示加上的
            }
          }
        },
        series: [
          {
            name: "",
            type: "line",
            data: [

            ],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: "{c}"
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

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

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

                  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] }
                  ]);
                },
                lineStyle: {
                  color: '#5B98FF' //改变折线颜色
                },
                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 //锁定区域禁止缩放
          }
        ],
      },
      tableData: [
      ]
    };
  },
  created(){
    this.tableHeight = (document.documentElement.clientHeight - 50) + "px"

    var date = new Date();
    var year = date.getFullYear(); //获取完整的年份(4位)
    var month = date.getMonth() + 1 < 10 ? "0"+(date.getMonth()+1).toString(): date.getMonth()+1; //获取当前月份(0-11,0代表1月)
    var day =date.getDate() < 10 ? "0"+date.getDate().toString():date.getDate(); //获取当前日(1-31)

    var last_month = date.getMonth() < 10 ? "0"+date.getMonth().toString(): date.getMonth(); //获取当前月份(0-11,0代表1月)
    this.query.patient_id = 0
    this.query.end_time = year+"-"+month+"-"+day
    this.query.start_time = year+"-"+last_month+"-"+day
    this.query.statistics_type = 1
    this.GetDialysisWatchChartData(this.query)
    this.GetDialysisWatchTableData(this.query)


    GetDefalutPatient()
      .then(rs => {
        var resp = rs.data
        if (resp.state == 1) {
          this.patient_name =resp.data.patient.name
        } else {
          this.$toast({
            message: resp.msg
          })
        }
      })
      .catch(error => {

      })


  },
  methods: {
    getTime (time) {
      return uParseTime(time, '{y}-{m}-{d} {h}:{i}')
    },
    chooseProject(val) {
      switch (val) {
        case "收缩压":
          this.query.statistics_type = 1
          break
        case "舒张压":
          this.query.statistics_type = 2
          break
        case "脉搏":
          this.query.statistics_type = 3
          break
        case "呼吸":
          this.query.statistics_type = 4

          break
        case "体温":
          this.query.statistics_type = 5

          break
        case "血流量":
          this.query.statistics_type = 6

          break
        case "静脉压":
          this.query.statistics_type = 7

          break
        case "动脉压":
          this.query.statistics_type = 8

          break
        case "跨膜压":
          this.query.statistics_type = 9

          break
        case "透析液温度":
          this.query.statistics_type = 10
          break
        case "超滤率":
          this.query.statistics_type = 11
          break
        case "超滤量":
          this.query.statistics_type = 12
          break

      }
      this.project = val;
      this.projectShow = false;
      this.GetDialysisWatchChartData(this.query)

    },

    handleSelect(val) {
      this.query.patient_id = val.id
      this.patient_name = val.name
      this.query.page = 1
      this.isStop = false
      this.GetDialysisWatchChartData(this.query)
      this.GetDialysisWatchTableData(this.query)
    },
    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;
          cb(searchArray);
        } else {
          cb([]);
        }
      });
    },


    GetDialysisWatchChartData(params) {
      this.options.xAxis.data = []
      this.options.series[0].data = []

      GetDialysisWatchChartData(params)
        .then(rs => {
          var resp = rs.data
          if (resp.state == 1) {
            for (let i = 0;  i < resp.data.data.length;i++){
              this.options.xAxis.data.push(resp.data.data[i].date)
              this.options.series[0].data.push(resp.data.data[i].value)
              this.getArrLength(this.options.xAxis.data)
            }
          } else {
            this.$toast({
              message: resp.msg
            })
          }
        })
        .catch(error => {

        })
    },

    GetDialysisWatchTableData(params) {
      this.loading = true

      GetDialysisWatchTableData(params)
        .then(rs => {
          var resp = rs.data
          if (resp.state == 1) {
            this.loading = false
            this.tableData = []
            for (let i = 0; i < resp.data.data.length; i++){
              this.tableData.push( resp.data.data[i])
            }
            this.$nextTick(() => {
              this.$refs.tab.doLayout()
            })
          } else {
            this.loading = false

            this.$toast({
              message: resp.msg
            })
          }
        })
        .catch(error => {
          this.loading = false


        })
    },

    getstartTime(value) {

      this.query.page = 1
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let day = value.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }

      this.query.start_time = `${year}-${month}-${day}`;
      this.GetDialysisWatchChartData(this.query)
      this.GetDialysisWatchTableData(this.query)
      this.startShow = false;

    },
    getstartTime2(value) {
      this.query.page = 1

      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let day = value.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }

      this.query.end_time = `${year}-${month}-${day}`;
      this.GetDialysisWatchChartData(this.query)
      this.GetDialysisWatchTableData(this.query)
      this.endShow = false;
    },
    loadMore() {
      if(!this.isStop){
        this.isStop = true
        this.query.page++
        GetDialysisWatchTableData(this.query)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              for (let i = 0; i < resp.data.data.length; i++){
                this.tableData.push( resp.data.data[i])
              }
              this.$nextTick(() => {
                this.$refs.tab.doLayout()
              })
              if (resp.data.data.length <= 0){
                this.isStop = true
              }else{
                this.isStop = false
              }
            } else {
              this.$toast({
                message: resp.msg
              })
            }
          })
          .catch(error => {
          })
      }
    },
    getArrLength(result){
      if(result.length > 6){
        var dataZoom_end = (6/result.length)*100;
        this.options.dataZoom[0].end = dataZoom_end
      }else{
        var dataZoom_end = 100;
        this.options.dataZoom[0].end = dataZoom_end
      }
    }
  }
};
</script>


<style lang="scss" scoped>
.page_dialysisMonitor {
  .searchBox{
    background: #F6F6F6;
    height: 3rem;
    display: flex;
    align-items: center;
    padding:0 0.625rem;
  }
  .optionsBox {
    display: flex;
    height: 3.125rem;
    align-items: center;
    width: 37.5rem;
    background: #fff;
    .optionsOne {
      //   max-width: 8.75rem;
      //   min-width: 6.25rem;
      padding: 0 0.75rem;
      height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      border-radius: 5px;
      text-align: center;
      font-size: 0.8125rem;
      color: #646566;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 0.8125rem;
    }
    .toolOne {
      width: 6.25rem;
      height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      border-radius: 5px;
      text-align: center;
      font-size: 0.8125rem;
      color: #646566;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 0.8125rem;
    }
  }
  .chart1 {
    font-size: 1rem;
    font-weight: bold;
    color: #000;
    margin: 0 0 0 0.8125rem;
  }
  .chart {
    font-size: 1rem;
    font-weight: bold;
    margin-left: 0.8125rem;
    color: #000;
  }
  .rangeBox {
    margin-left: 0.8125rem;
    display: flex;
    align-items: center;
    .range {
      width: 0.8125rem;
      height: 0.8125rem;
      background: linear-gradient(
        0deg,
        rgba(169, 224, 243, 1),
        rgba(159, 189, 252, 1)
      );
      border-radius: 0.25rem;
      margin-right: 0.5rem;
    }
    span {
      color: #5d5a5f;
      font-size: 0.75rem;
    }
  }
}
::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>


<style lang="scss">
.page_dialysisMonitor {
  .el-input{
    font-size: 14px !important;
  }
  .searchBox{
    .el-autocomplete{
      width: 100%;
    }
    .el-input__inner{
      border-radius:1rem;
      line-height: 2rem;
      height:2rem;
      border:none;
    }
    .el-input__icon{
      line-height:2rem;
    }
  }
  .el-table {
    ::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
    .el-table__fixed-right {
      right: 0 !important;
    }
  }
  .van-cell__value {
    display: flex;
    align-items: center;
  }
  .van-search__content {
    border-radius: 1.875rem;
  }
}
</style>
