<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <el-button type="primary" @click="$router.back(-1)">返回</el-button>
    </div>
    <div class="app-container">
      <div class="page_weightDetails">
        <div class="cell clearfix" style="margin:0">
          <el-form :inline="true" :model="listQuery">
            <el-form-item label>
              <el-autocomplete
                class="checkSearch"
                popper-class="my-autocomplete"
                v-model="search_value"
                :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-select v-model="query.statistics_type" placeholder="请选择" style="width:110px;margin-right:10px" @change="changeProject">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"

                ></el-option>
              </el-select>
              <label class="title">
                <span class="name">日期查询</span> :
              </label>
              <el-date-picker
                v-model="query.start_time"
                prefix-icon="el-icon-date"
                @change="changeTime"
                :editable="false"
                style="width: 150px;"
                type="date"
                :picker-options="pickerOptions"
                placeholder="选择日期时间"
                align="right"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
              <span class>-</span>
              <el-date-picker
                v-model="query.end_time"
                prefix-icon="el-icon-date"
                @change="changeEndTime"
                :editable="false"
                :picker-options="pickerOptions"
                style="width: 150px;"
                type="date"
                placeholder="选择日期时间"
                align="right"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
        </div>
        <el-container>
          <div style="width:160px">
            <div class="tableTitle">患者列表</div>
            
            <el-table ref="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="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 class="containerRight" style="flex:1;overflow: hidden">
            
            <div class="tableTitle">指标趋势</div>
            <div>
              <line-chart :options="chart"></line-chart>
            </div>
            <div class="tableTitle">统计表</div>
            <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 fixed label="日期" align="center">
                  <template slot-scope="scope">
                    {{scope.row.assessment_date | parseTime("{y}-{m}-{d}") }}
                  </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>

                    <!--{{scope.row.weight_before - scope.row.last_after_weight}}-->
                    <!--<div v-if="scope.row.after.systolic_blood_pressure"> {{ scope.row.after.systolic_blood_pressure}} /{{scope.row.after.diastolic_blood_pressure}}</div>-->
                  </template>
                </el-table-column>

              </el-table>

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

<script>
import echarts from "echarts";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import LineChart from "../../qcd/components/LineChart";

import { getCurrentOrgPatients } from "@/api/common/common";
import {GetDialysisPatientWeightChartData,GetDialysisWeightTableData} from "@/api/common/statistics"
import { PostSearch } from '@/api/patient'
import { uParseTime } from "@/utils/tools";


export default {
  components: {
    LineChart,
    BreadCrumb
  },
  data() {
    return {
      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;;
        }
      },
      patientsData:[],
      tableData: [],
      loading: false,
      search_value: '',
      total: 0,
      patient_name:'',
      query: {
        patient_id: '',
        statistics_type: 1,
        start_time: '',
        end_time: '',
        limit: 10,
        page: 1
      },
      options: [
        { value: 1, name: '干体重' },
        { value: 2, name: '透前体重' },
        { value: 3, name: '体重增加' },
        { value: 4, name: '透后体重' },
      ],

      crumbs: [
        { path: false, name: "质控管理" },
        { path: false, name: "患者血压详情" }
      ],

      chart: {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: [],
          left: 0
        },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} %"
          },
          show: false
        },
        series: [
          {
            name: "",
            type: "line",
            data: [

            ],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: "{c}"
              }
            },
            //配置样式
            itemStyle: {
              normal: {
                color: "#5b98ff", //折点颜色
                lineStyle: {
                  color: "#5b98ff" //折线颜色
                }
              }
            }
          },
        ],
        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 // 锁定区域禁止缩放
          }
        ]
      },
    };
  },
  methods: {
    chooseMonth(month) {
      this.monthType = month;
    },
    clickQuality(index) {
      this.quality = index;
    },  changeProject(val){
      this.query.statistics_type = val
      this.query.page = 1
      this.GetDialysisPatientWeightChartData(this.query)

    },
    handleChange(val){
      this.patient_name = val.name
      this.query.patient_id = val.id
      this.query.page = 1
      this.GetDialysisWeightTableData(this.query)
      this.GetDialysisPatientWeightChartData(this.query)
    },
    handleSizeChange(limit) {
      this.query.limit = limit;
      this.GetDialysisWeightTableData(this.query)


    },
    handleCurrentChange(page) {
      this.query.page = page;
      this.GetDialysisWeightTableData(this.query)


    },
    changeTime(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.query.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.query.start_time = "";
      } else {
        // this.getDialysisList()
        this.query.page = 1;
        this.GetDialysisPatientWeightChartData(this.query)
        this.GetDialysisWeightTableData(this.query)

      }

    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.query.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.query.end_time = "";
      } else {
        this.query.page = 1;
        this.GetDialysisPatientWeightChartData(this.query)
        this.GetDialysisWeightTableData(this.query)

      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },GetDialysisWeightTableData(params) {
      this.loading = true
      GetDialysisWeightTableData(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.total = resp.data.total
          } else {
            this.loading = false
          }
        })
        .catch(error => {

        })
    },
    GetDialysisPatientWeightChartData(params) {
      this.chart.xAxis.data = []
      this.chart.series[0].data = []
      GetDialysisPatientWeightChartData(params)
        .then(rs => {
          var resp = rs.data
          if (resp.state == 1) {
            for (let i = 0; i < resp.data.data.length; i++) {
              this.chart.xAxis.data.push(resp.data.data[i].date)
              this.chart.series[0].data.push(parseFloat(resp.data.data[i].value).toFixed(1))
            }
            this.getArrLength(this.chart.xAxis.data)
          } else {
          }
        })
        .catch(error => {
        })
    },
    handleSelect(val) {
      this.query.patient_id = val.id
      this.query.page = 1
      this.patient_name = val.name
      // this.GetDialysisPatientWeightChartData(this.query)
      // this.GetDialysisWeightTableData(this.query)
      for (let i = 0;i < this.patientsData.length; i++){
        if (this.patientsData[i].id == val.id){
          this.$refs.table.setCurrentRow(this.patientsData[i])
        }
      }

    },
    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([])
        }
      })
    }, getCurrentOrgPatients(){
      getCurrentOrgPatients().then(response=>{
        if(response.data.state == 1){
          var patients = response.data.data.patients
          this.patientsData = patients
          for (let i = 0;i < this.patientsData.length; i++){
            if (this.patientsData[i].id == this.query.patient_id){
              this.patient_name = this.patientsData[i].name
              this.$refs.table.setCurrentRow(this.patientsData[i])
            }
          }

        }
      })
    },
    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 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 = this.$route.query.id
    this.query.end_time = year + '-' + month + '-' + day
    this.query.start_time = year + '-' + last_month + '-' + day
    this.query.statistics_type = 1
    this.GetDialysisPatientWeightChartData(this.query)
    this.GetDialysisWeightTableData(this.query)
    this.getCurrentOrgPatients()

  }
};
</script>

<style lang="scss" scoped>
.containerRight {
  padding-left: 10px;
}
.tableTitle {
  font-size: 16px;
  color: #000;
  font-weight: bold;
  margin-bottom: 10px;
  margin-top: 8px;
}
</style>


<style lang="scss">
.page_weightDetails {
  .cell {
    text-align: center;
  }
  .el-form-item {
    margin-bottom: 0;
  }
  ::-webkit-scrollbar{
    height: 15px !important;
  }
}
</style>
