<template>
  <div class="main-contain">
    <div class="position">
      <div>
        <span>
          <el-button @click="return_click" type="text" icon="el-icon-arrow-left">返回</el-button>
        </span>&nbsp;&nbsp;
        <span>患者血压详情</span>
      </div>
    </div>
    <div class="app-container">
      <div class="page_patientControlAnalysis">
        <div style="display: flex;margin-bottom: 20px;">
          <div style="flex: 2;display: flex;flex-wrap:wrap">
            <div>
              日期：
              <el-select v-model="date_value" @change="datachange" placeholder="请选择" style="width: 100px;">
                <el-option
                  v-for="item in date_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div style="margin:0 10px;">
              <el-date-picker
                v-model="start_date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 150px;">
              </el-date-picker>
              <span>-</span>
              <el-date-picker
                v-model="end_date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 150px;">
              </el-date-picker>
            </div>
            <div>
              状态:
              <el-select v-model="status_value" placeholder="请选择" style="width: 100px;">
                <el-option :key="0" label="不限" :value="0"></el-option>
                <el-option
                  v-for="item in status_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>

          </div>
          <div style="flex: 1;">
            <div>
              <el-button type="primary" @click="deil_click">查询</el-button>
              <el-button type="primary" @click="exportExcel">导出</el-button>
            </div>
          </div>
        </div>

        <el-table :data="tableData" border style="width: 100%"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{ textAlign: 'center' }"
        height="380">
          <el-table-column
            prop="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            prop="dialysis_no"
            label="透析号"
            width="70">
          </el-table-column>
          <el-table-column
            prop="patient_name"
            label="患者姓名"
            width="80">
          </el-table-column>
          <el-table-column
            prop="gender"
            label="性别"
            width="50">
          </el-table-column>
          <el-table-column
            prop="age"
            label="年龄"
            width="50">
          </el-table-column>
          <el-table-column
            prop="dialysis_date"
            label="透析日期"
            width="100">
          </el-table-column>
          <el-table-column
            prop="dryweight"
            label="干体重"
            width="70">
          </el-table-column>
          <el-table-column
            prop="UltrafiltrationVol"
            label="超滤总量(L)"
            width="90">
          </el-table-column>
          <el-table-column
            prop="actual_ultrafiltration"
            label="实际超滤量(ml)"
            width="100">
          </el-table-column>
          <el-table-column
            prop="ultrafiltration_rate"
            label="超滤率"
            width="70">
          </el-table-column>
          <el-table-column
            prop="preDialysisBP"
            label="透前血压"
            width="90">
          </el-table-column>
          <el-table-column
            prop="monitoringbp"
            label="监测记录血压">
          </el-table-column>
          <el-table-column
            prop="PostDialysisBP"
            label="透后血压"
            width="90">
          </el-table-column>
        </el-table>
        <div style="text-align: right;margin-top: 10px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[50,100, 200, 300, 400]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->

  </div>
</template>
<script>
import * as echarts from 'echarts';
import XLSX from 'xlsx';
import { uParseTime } from "@/utils/tools";
import {Getbpdetail} from '../../../../api/qcd'
import { forEach } from 'jszip';
import html2canvas from "html2canvas"
  export default {
    components:{
    },
    data(){
      return{
        date_value:4,
        start_date:'',
        end_date:this.getTime(new Date()),
        mode:'',
        date_mode:'',
        source:'',
        dialyze_value:0,
        dialyze_dialog:false,
        currentPage:1,
        limit:50,
        total:0,
        tableData:[],
        status_value:1,
        status_options:[{value:1,label:'达标'},{value:2,label:'不达标'}],
        date_options:[{value:1,label:'最近七天'},{value:2,label:'本周'},{value:3,label:'上周'},{value:4,label:'本月'},
                      {value:5,label:'上月'},{value:6,label:'本年'},{value:7,label:'上一年'}
        ],

        date_mode_options:[{value:1,label:'按周'},{value:2,label:'按天'},{value:3,label:'按月'},{value:4,label:'按年'}],
        source_options:[{value:1,label:'以开始透析为准'},{value:2,label:'以排班为准'}],


        input:'',
      }
    },
    methods:{
      // 返回
      return_click(){
        this.$router.push('/Dialysisanalysis/qualitycontrol/weightblood')
      },
      // 导出excel
      exportExcel(){
        let tableData = [
          ['序号', '透析号', '患者姓名','性别','年龄', '透析日期','干体重', '超滤总量','实际超滤量','超滤率','透前血压','监测记录血压','透后血压']//导出表头
        ]
        this.tableData.forEach((item,index) =>{
          let rowdata=[]
          rowdata=[
            item.index,
            item.dialysis_no,
            item.patient_name,
            item.gender,
            item.age,
            item.dialysis_date,
            item.dryweight,
            item.UltrafiltrationVol,
            item.actual_ultrafiltration,
            item.ultrafiltration_rate,
            item.preDialysisBP,
            item.monitoringbp,
            item.PostDialysisBP,
          ]
          tableData.push(rowdata)
        })
        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
        let bookNew = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(bookNew, workSheet, '患者血压详情') // 工作簿名称
        let name = '患者血压详情'+ '.xlsx'
        XLSX.writeFile(bookNew, name) // 保存的文件名
      },
      // 详情查询
      deil_click(){
        this.Getdialyzerdetail(this.status_value)
      },

      // 选择日期
      datachange(eve){
        if(eve ==1){
          this.start_date = this.getPreviousDate(7)
          this.end_date = this.getTime(new Date())
        }else if(eve==2){
          this.start_date = this.getFirstDayOfWeek(new Date())
          this.end_date = this.getTime(new Date())
          console.log('this.start_date', this.start_date);
        }else if(eve ==3){
          var date=new Date()
          date.setDate(date.getDate()-7 - date.getDay() + 1);
          var m =''
          var d = ''
          if(date.getMonth() + 1<10){
            m = '0'+(date.getMonth() + 1)
          }else{
             m = date.getMonth() + 1
          }
          if(date.getDate()<10){
             d = '0'+date.getDate()
          }else{
            d = date.getDate()
          }
          // this.start_date = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() ;
          this.start_date = date.getFullYear() + "-" + m + "-" + d ;
          date.setDate(date.getDate() +6);
          var mm = ''
          var dd = ''
          if(date.getMonth() + 1<10){
            mm = '0'+(date.getMonth() + 1)
          }else{
            mm = date.getMonth() + 1
          }
          if(date.getDate()<10){
            dd = '0'+date.getDate()
          }else{
            dd = date.getDate()
          }
          // if(date.getMonth() + 1<10)
          // this.end_date = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
          this.end_date = date.getFullYear() + "-" + mm + "-" + dd ;
          console.log('this.end_date',this.end_date);

        }else if(eve ==4){
          this.start_date = this.getFirstDayOfMonth(new Date())
          this.end_date = this.getTime(new Date())
        }else if(eve ==5){
          this.getLastMonthFirstDay()
          this.getLastMonthLastDay()
        }else if(eve == 6){
          this.start_date = this.getFirstDayOfYear(new Date())
          this.end_date = this.getTime(new Date())
        }else if(eve == 7){
          this.getLastYearFirstDay()
          this.getLastYearLastDay()
        }
        console.log('eve',eve);
      },
      // 详情数据源
      Getdialyzerdetail(value){
        const params={
          status_type:value,
          start_time:this.start_date,
          end_time:this.end_date,
          page:this.currentPage,
          limit:this.limit,
        }
        Getbpdetail(params).then(response =>{
          if(response.data.state == 1){
            const list = response.data.data.list
            const table=[]
            if(list.length > 0){
              list.forEach((item,index)=>{
                const obj ={
                  index:index+1,
                  dialysis_no:item.dialysis_no,
                  patient_name:item.patient_name,
                  gender:this.getgender(item.gender),
                  age:item.age,
                  dialysis_date:this.getTime(item.assessment_date),
                  dryweight:item.dry_weight,
                  UltrafiltrationVol:item.ultrafiltration_vol/1000,
                  actual_ultrafiltration:item.actual_ultrafiltration,
                  ultrafiltration_rate:item.ultrafiltration_rate,
                  preDialysisBP:item.pre_dialysis_bp,
                  monitoringbp:item.monitoring_bp,
                  PostDialysisBP:item.post_dialysis_bp,
                }
                table.push(obj)
              })
              this.tableData = table
              this.total = response.data.data.total
            }
          }
          console.log('77777血压表格',response);
        })
      },
       // 首先定义一个getPreviousDate函数，方便调用
      getPreviousDate(numOfDays) {
        var date = new Date();
        date.setDate(date.getDate() - numOfDays);
        var year = date.getFullYear();
        if(date.getMonth() + 1<10){
          var month = '0'+(date.getMonth() + 1);
        }else{
          var month = date.getMonth() + 1;
        }

        if(date.getDate()<10){
          var day = '0'+date.getDate();
        }else{
          var day = date.getDate();
        }
        return year + "-" + month + "-" + day;
      },
      // 本周
      getFirstDayOfWeek(date){
        var weekday = date.getDay()
        date.setDate(date.getDate()-weekday+1);//往前算（weekday-1）天，年份、月份会自动变化
        return this.timeFormat(date);
      },
      // 本月
      getFirstDayOfMonth (date) {
        date.setDate(1);
        return this.timeFormat(date);
      },
       //上个月第一天
      getLastMonthFirstDay() {
          var date = new Date();
          date.setDate(0);
          var y = date.getFullYear(); //获取年份
          var m = date.getMonth() + 1; //获取月份
          m = m < 10 ? "0" + m : m;
          this.start_date = [y, m, '01'].join("-")
          // return [y, m, '01'].join("-");
      },
      // 上个月最后一天
      getLastMonthLastDay() {
          var date = new Date();
          date.setDate(0);
          var y = date.getFullYear(); //获取年份
          var m = date.getMonth() + 1; //获取月份
          var d = new Date(y, m, 0).getDate(); //获取当月最后一日
          m = m < 10 ? "0" + m : m; //月份补 0
          d = d < 10 ? "0" + d : d; //日数补 0
          this.end_date = [y, m, d].join("-")
          // return [y, m, d].join("-");
      },
      // 本年
      getFirstDayOfYear (date) {
        date.setDate(1);
        date.setMonth(0);
        return this.timeFormat(date);
      },
      // 上一年第一天
      getLastYearFirstDay() {
          let date = new Date();
         const year= date.setFullYear(date.getFullYear() - 1); // 设置年份为前一年
         const start_month= date.setMonth(0); // 设置月份为1月（注意月份是从0开始的）
         const start_day = date.setDate(1); // 设置日期为1日
        //  const last_month = date.setMonth(11); // 设置月份为12月
        //  const last_day = date.setDate(0); // 设置日期为0，这将自动设置为该月的最后一天
        //  this.start_date = year+ "-" +start_month+ "-" +start_day
         this.start_date = this.getTime(start_day)
        //  return this.start_date
      },
      // 上一年最后一天
      getLastYearLastDay() {
          let date = new Date();
          const year= date.setFullYear(date.getFullYear() - 1); // 设置年份为前一年
          const last_month = date.setMonth(12); // 设置月份为12月
          const last_day = date.setDate(0);// 设置日期为0，这将自动设置为该月的最后一天
          // this.end_date =  year+ "-" +last_month+ "-" +last_day
          this.end_date = this.getTime(last_day)
          console.log('this.end_date',this.end_date);
          // return this.end_date;
      },
      // 日期格式化
      timeFormat(date) {
          if (!date || typeof(date) === "string") {
            this.error("参数异常，请检查...");
          }
          var y = date.getFullYear(); //年
          if(date.getMonth() + 1<10){
            var m ='0'+(date.getMonth() + 1); //月
          }else{
            var m =date.getMonth() + 1; //月
          }
          if(date.getDate() + 1<10){
            var d ='0'+date.getDate(); //日
          }else{
            var d = date.getDate(); //日
          }
          // var d = date.getDate(); //日

          return y + "-" + m + "-" + d;
      },
      handleCurrentChange(val){
        this.currentPage = val
        this.Getdialyzerdetail(this.status_value)
      },
      handleSizeChange(val){
        this.limit = val
        this.Getdialyzerdetail(this.status_value)
      },
       // 性别
       getgender(ids){
        if(ids ==1){
          return "男"
        }else{
          return "女"
        }
      },
      // getVol(value){
      //   if(value >1000){

      //   }
      // },
       // 转换时间
      getTime(val) {
        if(val < 0){
          return ""
        }
        if(val == ""){
          return ""
        }else {
          return uParseTime(val, '{y}-{m}-{d}')
        }
      },
      dataURLtoBlob(dataURL) {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },

    },
    mounted(){

    },
    created(){
      this.start_date = this.getFirstDayOfMonth(new Date())
      this.Getdialyzerdetail(this.status_value)
    },

  }
</script>
