<template>
  <div class="page_bloodPressure">
    <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">统计图</div>
    <!-- <div class="chart1">{{ project }}</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" :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.assessment_date)}}
          </template>
        </el-table-column>

        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            {{scope.row.patient.name}}
          </template>
        </el-table-column>

        <el-table-column label="干体重" align="center">
          <template slot-scope="scope">
            {{scope.row.dry_weight?scope.row.dry_weight:''}}
            <!--{{// scope.row.patient.lapseto == 1 ? '留治':'转出'}}-->
          </template>
        </el-table-column>

        <el-table-column label="前次透后体重" align="center">
          <template slot-scope="scope">
            {{scope.row.last_after_weight?scope.row.last_after_weight:''}}
            <!--<div v-if="scope.row.before.systolic_blood_pressure">{{scope.row.before.systolic_blood_pressure}} / {{scope.row.before.diastolic_blood_pressure}}</div>-->
          </template>
        </el-table-column>

        <el-table-column label="透前体重" align="center">
          <template slot-scope="scope">
            {{scope.row.weight_before?scope.row.weight_before:''}}
            <!--<div v-if="scope.row.min_monitor.systolic_blood_pressure">{{ scope.row.min_monitor.systolic_blood_pressure}} /{{ scope.row.min_monitor.diastolic_blood_pressure}}</div>-->
          </template>
        </el-table-column>

        <el-table-column label="透后体重" align="center">
          <template slot-scope="scope">
            <!--<div v-if="scope.row.max_monitor.systolic_blood_pressure">{{ scope.row.max_monitor.systolic_blood_pressure}} /{{ scope.row.max_monitor.diastolic_blood_pressure}}</div>-->
            {{scope.row.after.weight_after?scope.row.after.weight_after:''}}
          </template>
        </el-table-column>

        <el-table-column label="体重增加" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.weight_before && scope.row.last_after_weight">{{(scope.row.weight_before - scope.row.last_after_weight).toFixed(1)}}</div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="趋势" align="center">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="jumpDetail(scope.row.patient_id)"
              type="text"
              size="small"
              style="font-size:15px;"
            >详情</el-button>
          </template>
        </el-table-column>

      </el-table>
      <scroll-top></scroll-top>
    </div>

    <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="currentDate1"
          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="currentDate2"
          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 {GetDialysisWeightChartData,GetDialysisWeightTableData} from "@/api/statistics";
  import {
    PostSearch,
  } from "@/api/patient";
  import { uParseTime } from '@/utils/tools'


  export default {
    components: {
      BarChart,
      ScrollTop
    },
    data() {
      return {
        percent:[],
        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)),
        tableHeight: '',
        value: "",
        search_value: "",
        query: {
          patient_id: "",
          statistics_type: 1,
          start_time: "",
          end_time: "",
          limit:20,
          page:1,
        },
        project: "干体重",
        projectShow: false,
        project_columns: ["干体重", "透前体重", "体重增加","透后体重"],

        state: "全部分区",
        type: "患者姓名",
        stateShow: false,
        typeShow: false,
        startShow: false,
        endShow: false,
        currentDate: new Date(),
        startTime: "日期范围",
        endTime: "日期范围",
        maxDate: new Date(),
        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 = 8; //每项显示文字个数
                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: "bar",
              data: [],
              barWidth: 20,
              label: {
                normal: {
                  show: true,
                  position: "top",
                  formatter: (params) => {
                    if(this.percent.length > 0){
                      let str = ''
                      str = params.data  + '('+ this.percent[params.dataIndex] +'%)'
                      return str
                    }else{
                      let str = ''
                      str = params.data
                      return str
                    }
                  }
                }
              },
              //配置样式
              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] }
                    ]);
                  },
                  barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
                },

                //鼠标悬停时：
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.2)"
                }
              }
            }
          ]
        },
        tableData: [
        ]
      };
    },
    created(){
      this.tableHeight = (document.documentElement.clientHeight - (Number(document.documentElement.style.fontSize.slice(0, -2)) * 3.125)) + '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.GetDialysisWeightChartData(this.query)
      this.GetDialysisWeightTableData(this.query)

    },
    methods: {
      jumpDetail(patient_id){
        this.$router.push("/dqc/weight/detail?id="+patient_id)

      },
      getTime (time) {
        return uParseTime(time, '{y}-{m}-{d}')
      },

      GetDialysisWeightChartData(params) {
        this.options.xAxis.data = []
        this.options.series[0].data = []
        this.percent = []
        GetDialysisWeightChartData(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].name)
                this.options.series[0].data.push(resp.data.data[i].total)
                this.percent.push(resp.data.data[i].ratio)

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

          })
      },
      GetDialysisWeightTableData(params) {
        GetDialysisWeightTableData(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              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.$toast({
                message: resp.msg
              })
            }
          })
          .catch(error => {

          })
      },
      handleSelect(val) {
        this.query.patient_id = val.id
        this.query.page = 1
        this.isStop = false
        // this.GetDialysisWeightChartData(this.query)
        this.GetDialysisWeightTableData(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([]);
          }
        });
      },
      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
        }
        this.project = val;
        this.projectShow = false;
        this.GetDialysisWeightChartData(this.query)

      },

      getstartTime(value) {
        this.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.startTime = `${year}-${month}-${day}`;

        this.query.start_time = `${year}-${month}-${day}`;
        this.GetDialysisWeightChartData(this.query)
        this.GetDialysisWeightTableData(this.query)
        this.startShow = false;
      },
      getstartTime2(value) {
        this.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.endTime = `${year}-${month}-${day}`;
        this.endShow = false;

        this.query.end_time = `${year}-${month}-${day}`;
        this.GetDialysisWeightChartData(this.query)
        this.GetDialysisWeightTableData(this.query)
      },
      loadMore() {
        if(!this.isStop){
          this.isStop = true
          this.query.page++
          GetDialysisWeightTableData(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 => {

            })
        }
      }
    }
  };
</script>



<style lang="scss" scoped>
.page_bloodPressure {
  .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 {
    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_bloodPressure {
  .searchBox{
    .el-input{
      font-size: 14px !important;
    }
    .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>
