<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;">
          <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-button type="primary" @click="sete_click">查询</el-button>
            <el-button type="primary" @click="Download_click">下载</el-button>
          </div>
        </div>
        <!-- 图表 -->
        <div ref="mychart">
          <div class="echart" id="mychart"  style="width:100%;height:60vh"></div>
        </div>

          <div style="position: fixed;right: 5%;top: 50vh;">
            <el-popover
              placement="left"
              title="提示"
              width="500"
              trigger="click"
              content="1. 统计时间段内所有患者每次透析时的年龄和透前血压，根据不同年龄的标准值计算达标率。
                        2. 患者＜60 岁的透前血压以收缩压＜140 或舒张压＜90 为达标值；患者≥60岁的透前血压以收缩压＜160 或舒张压＜90 为达标值。
                        3. 控制率=（≥60 岁患者的达标例次+＜60 岁患者的达标例次）/时间段内总例次 x100%。">
              <img src="@/assets/img/xiang.png" alt="" style="height: 20px;width: 20px;" slot="reference">
              <!-- <el-button slot="reference">click 激活</el-button> -->
            </el-popover>
          </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <div>
      <el-dialog
        title="提示"
        :visible.sync="complete_dialog"
        width="80%">
        <div>
          <div style="display: flex;margin-bottom: 20px;">
            <div style="flex: 2;display: flex;">
              <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: 130px;">
                  <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="detil_click">查询</el-button>

                <el-button type="primary" @click="derive_click">导出</el-button>
              </div>
            </div>
          </div>
          <div>
            <el-table :data="tableData"
              border
              style="width: 100%;"
              :header-cell-style = "{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              height="380">
              <el-table-column
                prop="index"
                label="序号"
                width="">
              </el-table-column>
              <el-table-column
                prop="dialysis_no"
                label="透析号"
                width="">
              </el-table-column>
              <el-table-column
                prop="patient_name"
                label="患者姓名">
              </el-table-column>
              <el-table-column
                prop="age"
                label="年龄">
              </el-table-column>
              <el-table-column
                prop="dialysis_date"
                label="透析日期"
                width="">
              </el-table-column>
              <el-table-column
                prop="PostDialysisBP"
                label="透后血压"
                width="">
              </el-table-column>
            </el-table>
          </div>
          <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>
        <span slot="footer" class="dialog-footer">
          <el-button @click="complete_dialog = false">取 消</el-button>
          <el-button type="primary" @click="complete_dialog = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import XLSX from 'xlsx';
import { uParseTime } from "@/utils/tools";
import {Getpatinetbp,Getbpdetail} from '../../../../api/qcd'
import {getAllNurseList} from '@/api/fallassement'
import { getAllDoctorList} from "@/api/device"
import html2canvas from "html2canvas"
  export default {
    components:{
    },
    data(){
      return{
        date_value:4,
        start_date:'',
        end_date:this.getTime(new Date()),
        mode:'',
        date_mode:'',
        source:'',
        status_value:0,
        complete_dialog:false,
        currentPage:1,
        limit:50,
        total:0,
        tableData:[],
        nurseList:[],
        operators:[],
        docList:[],
        status_options:[],

        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:'以排班为准'}],
        status_id:"",
      }
    },
    methods:{
      // 返回
      return_click(){
        this.$router.push('/Dialysisanalysis/qualitycontrol/weightblood')
      },
      // 数据源
      getecharts(){
        var chartDom = document.getElementById('mychart')
        var myChart = echarts.init(chartDom);
        const params={
          start_time:this.start_date,
          end_time:this.end_date,
          statistics_type:2
        }
        Getpatinetbp(params).then(response =>{
          if(response.data.state ==1){
            const list = response.data.data.list
            const xAxis = []
            const yAxis = []
            var option = []
            var total =0
            for(let key in list){
              const obj={
                name:list[key].name,
                value:list[key].total
              }
              xAxis.push(obj)
              yAxis.push(list[key].name)
              total = total + list[key].total
              const obj2 ={
                value:(key*1)+1,
                label:list[key].name
              }
              option.push(obj2)
            }
            this.status_options = option
            console.log('this.status_options',response.data.data);
            const option = {
                title:{
                  text:'总数'+total,
                  left:'5%',
                  bottom:'5%',
                  textStyle:{
                    fontSize:30
                  }
                },
                tooltip: {
                  trigger: 'item',

                },
                legend: {
                  data:yAxis,
                  left: '10%',
                  top: '30%',
                  orient: 'vertical'
                },
                color:['#FFD7C0','#9FBDFC',"#A9E0F3", "#FF9994",'aquamarine','gold'],
                series: [
                  {
                    name: '',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: true,
                    itemStyle: {
                      borderRadius: 10,
                      borderColor: '#fff',
                      borderWidth: 2
                    },
                    label: {
                      show: true,
                      position: 'center',
                      normal : {
                        formatter: '{b}:{c}: ({d}%)',
                        textStyle : {
                          fontWeight : 'normal',
                          fontSize : 15,
                          color : "black"
                        }
                      }
                    },
                    emphasis: {
                      label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                      }
                    },
                    labelLine: {
                      show: false
                    },
                    data: xAxis
                  }
                ]
              };
            myChart.setOption(option);
            myChart.on('click',params =>{
              this.complete_dialog = true
              console.log('bbbb',params);

              for(let i in this.status_options){
                if(params.data.name == this.status_options[i].label){
                  this.status_value = this.status_options[i].value
                }
              }
              this.getdetail(this.status_value)
            })
          }
        })

      },
      // 查询
      sete_click(){
        this.getecharts()
      },
      // 详情查询
      detil_click(){
        this.currentPage =1
        this.getdetail(this.status_value)
      },
       // 下载
      Download_click(){
        const options ={
          allowTaint: true,
          useCORS: true
        }
        html2canvas(this.$refs.mychart,options).then(canvas =>{
          // const imageSrc = canvas.toDataURL();
          const imageUrl = canvas.toDataURL("image/png");
          const blob = this.dataURLtoBlob(imageUrl)
          const url = URL.createObjectURL(blob);
          var link= document.createElement("a");
        //   //将生成的图片url赋值给a标签的href属性
          link.href = url;
        //   //设置下载的文件名
          link.download = "透析完成率统计.jpg";
          // // 将a标签插入dom中
          console.log('link',link);
          document.body.appendChild(link);
          //模拟点击事件触发下载
          link.click();
          // 完成之后销毁创建的a标签
          document.body.removeChild(link);

        })
      },
      // 导出excel
      derive_click(){
        let tableData = [
          ['序号', '透析号', '患者姓名', '年龄','透析日期', '透后血压']//导出表头
        ]
        this.tableData.forEach((item,index) =>{
          let rowdata=[]
          rowdata=[
            item.index,
            item.dialysis_no,
            item.patient_name,
            item.age,
            item.dialysis_date,
            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) // 保存的文件名
      },
      // 详情数据源
      getdetail(value){
        const params ={
          start_time:this.start_date,
          end_time:this.end_date,
          status_type:value,
          statistics_type:2,
          page:this.currentPage,
          limit:this.limit,
        }
        Getbpdetail(params).then(response =>{
          if(response.data.state ==1){
            const list = response.data.data.list
            const xAxis = []
            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,
                  age:item.age,
                  dialysis_date:this.getTime(item.assessment_date),
                  PostDialysisBP:item.post_dialysis_bp,
                }
                table.push(obj)
              })
              this.tableData = table
              this.total = response.data.data.total
            }
          }
          console.log('55555透后',response);
        })
      },
      // 选择日期
      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);
      },
      // 首先定义一个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()<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.getdetail(this.status_value)
      },
      handleSizeChange(val){
        this.limit = val
        this.getdetail(this.status_value)
      },
       // 转换时间
      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 });
      },
      // 计算年龄
      analyzeIDCard(IDCard){
        var age = 0,yearBirth,monthBirth,dayBirth;
        //获取用户身份证号码
        var userCard = IDCard;
        //如果身份证号码为undefind则返回空
        if(!userCard){
          return age;
        }
        var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/; //验证身份证号码的正则
        if (reg.test(userCard)) {
          if (userCard.length == 15) {
              var org_birthday = userCard.substring(6, 12);
              //获取出生年月日
              yearBirth = "19" + org_birthday.substring(0, 2);
              monthBirth = org_birthday.substring(2, 4);
              dayBirth = org_birthday.substring(4, 6);
              } else if (userCard.length == 18) {
              //获取出生年月日
              yearBirth = userCard.substring(6,10);
              monthBirth = userCard.substring(10,12);
              dayBirth = userCard.substring(12,14);

            }
            //获取当前年月日并计算年龄
            var myDate = new Date();
            var monthNow = myDate.getMonth() + 1;
            var dayNow = myDate.getDate();
            var age = myDate.getFullYear() - yearBirth;
            if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
              age--;
            }
            //返回年龄
            return age;
        } else {
          return ''
        }

      },
      // 护士
      getAllNurseList(){
        getAllNurseList().then(response=>{
           if(response.data.state ==1){
             var nurseList  = response.data.data.nurseList
            console.log('0000',nurseList);
             this.nurseList =nurseList
           }
        })
      },
      // 医生
      getAllDoctorList(){
        getAllDoctorList().then(response=>{
          if(response.data.state == 1){
              var list = response.data.data.list
              console.log("list222222",list)
              this.docList = list
              this.operators = response.data.data.operators
          }
        })
      },
      getnurse(ids){
        const nurse = this.nurseList
        for(let i in nurse){
          if(ids==nurse[i].admin_user_id){
            return nurse[i].user_name
          }
        }
      },
      getdoctor(ids){
        const doctor = this.docList
        for(let i in doctor){
          if(ids == doctor[i].admin_user_id){
            return doctor[i].user_name
          }
        }
      }
    },
    mounted(){
      this.getecharts()
    },
    created(){
      this.start_date = this.getFirstDayOfMonth(new Date())
      this.getAllNurseList()
      this.getAllDoctorList()
    },

  }
</script>
