<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.统计时间段内所有患者每次透析后，透后体重是否在干体重的±0.3范围内。">
            <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="dialyze_dialog"
        width="90%">
        <div>
          <div style="display: flex;margin-bottom: 20px;">
            <div style="flex: 5;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="weight_value" placeholder="请选择" style="width: 100px;">
                  <el-option :key="0" label="不限" :value="0"></el-option>
                  <el-option
                    v-for="item in weight_gain"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div>
                干体重:
                <el-select v-model="dry_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>
                透后体重:
                <el-select v-model="after_value" placeholder="请选择" style="width: 100px;">
                  <el-option :key="0" label="不限" :value="0"></el-option>
                  <el-option
                    v-for="item in after_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div >
                <el-input v-model="Patient_name" placeholder="搜索患者姓名" style="width: 120px;"></el-input>
              </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="">
            </el-table-column>
            <el-table-column
              prop="dialysis_no"
              label="透析号"
              width="">
            </el-table-column>
            <el-table-column
              prop="name"
              label="患者姓名">
            </el-table-column>
            <el-table-column
              prop="sex"
              label="性别"
              width="">
            </el-table-column>
            <el-table-column
              prop="age"
              label="年龄"
              width="">
            </el-table-column>
            <el-table-column
              prop="date"
              label="透析日期"
              width="">
            </el-table-column>
            <el-table-column
              prop="dry_weight"
              label="干体重"
              width="">
            </el-table-column>
            <el-table-column
              prop="last_weight_after"
              label="前次透后体重">
            </el-table-column>
            <el-table-column
              prop="weight_before"
              label="透前体重"
              width="">
            </el-table-column>
            <el-table-column
              prop="weight_add"
              label="体重增加"
              width="">
            </el-table-column>
            <el-table-column
              prop="weight_after"
              label="透后体重">
            </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>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialyze_dialog = false">取 消</el-button>
          <el-button type="primary" @click="dialyze_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 {Getpatinetweight,Getweightdetail} 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_dialog:false,
        currentPage:1,
        limit:50,
        total:0,
        tableData:[],
        weight_gain:[{value:1,label:'体重增长<=3%'},{value:2,label:'3%<体重增长<5%'},{value:3,label:'体重增长>=5%'}],
        weight_value:0,
        dry_value:0,
        after_value:0,
        after_options:[],
        Patient_name:'',
        date_options:[{value:1,label:'最近七天'},{value:2,label:'本周'},{value:3,label:'上周'},{value:4,label:'本月'},
                      {value:5,label:'上月'},{value:6,label:'本年'},{value:7,label:'上一年'}
        ],
        status_options:[{value:1,label:'40~50kg'},{value:2,label:'50~60kg'},{value:3,label:'60~70kg'},
                        {value:4,label:'大于70kg'},{value:5,label:'小于40kg'},{value:6,label:'未知'}],

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

        Patient_name:'',
      }
    },
    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:4,
        }
        Getpatinetweight(params).then(response =>{
          console.log('ressponse',response.data.data);
          if(response.data.state ==1){
            console.log('bbbbbbbbb',response.data.data);
            const list = response.data.data.list
            const xAxis =[]
            const yAxis = []
            var weight = []
            for(let i in list){
              xAxis.push(list[i].name)
              yAxis.push(list[i].total)
               const obj ={
                value:(i*1)+1,
                label:list[i].name
              }
              weight.push(obj)
            }
            this.after_options = weight
            const option = {
              xAxis: {
                type: 'category',
                data: xAxis,
                axisLabel:{
                  interval:0,
                }
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  data:yAxis ,
                  type: 'bar',
                  barWidth: '25%',
                  label: {
                    normal: {
                      show: true,
                      position: 'top',
                      formatter: '{c}',
                      textStyle:{
                        color: 'black',//字体颜色
                        fontSize: 13//字体大小
                      }
                    },
                  },
                  itemStyle:{
                    normal:{
                      color:function (params){
                        // const colorarr=['#FFA333','#A155E8','#6D91FF','#A233A2'];
                        var colorarr = [["#A9E0F3", "#9FBDFC"],["#FFD7C0", "#FF9994"]]
                        var index = params.dataIndex;
                        if (params.dataIndex >= colorarr.length) {
                          index = params.dataIndex % colorarr.length;
                        }
                        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                          { offset: 0, color: colorarr[index][0] },
                          // { offset: 0.5, color: colorList[index][1] },
                          { offset: 1, color: colorarr[index][1] }
                        ]);
                      }
                    }
                  }
                }
              ]
            }
            myChart.setOption(option);
            myChart.on('click',params =>{
              this.dialyze_dialog = true
              console.log('vvvvv',params,this.after_options);
              for(let i in this.after_options){
                if(params.name == this.after_options[i].label){
                  this.after_value = this.after_options[i].value
                }
              }
              this.Getdialyzerdetail(this.after_value)
            })
          }

        })

      },
      // 导出excel
      exportExcel(){
        let tableData = [
          ['序号', '透析号', '患者姓名','性别','年龄','透析日期','干体重','前次透后体重','透前体重','体重增加','透后体重',]//导出表头
        ]
        this.tableData.forEach((item,index) =>{
          let rowdata=[]
          rowdata=[
            item.index,
            item.dialysis_no,
            item.name,
            item.sex,
            item.age,
            item.date,

            item.dry_weight,
            item.last_weight_after,
            item.weight_before,
            item.weight_add,
            item.weight_after

          ]
          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) // 保存的文件名
      },
      // 查询
      sete_click(){
        this.getecharts()
      },
      // 详情查询
      deil_click(){
        this.currentPage =1
        this.Getdialyzerdetail(this.after_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");
          // console.log('5555',imageUrl);
        //   // const base = this.url.split(',')[1]
        //   // console.log('2222',base);
          const blob = this.dataURLtoBlob(imageUrl)
          // console.log('4444',blob);
          const url = URL.createObjectURL(blob);
          // const file = (this.url).blob();
          // console.log('1111',url);
          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);

        })
      },
      // 选择日期
      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(after){
        const params ={
          start_time:this.start_date,
          end_time:this.end_date,
          add_type:this.weight_value,
          dry_type:this.dry_value,
          after_type:after,
          keyword:this.Patient_name,
          page:this.currentPage,
          limit:this.limit,
        }
        Getweightdetail(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,
                  name:item.patient_name,
                  sex:this.getgender(item.gender),
                  age:item.age,
                  date:this.getTime(item.assessment_date),
                  dry_weight:item.dry_weight,
                  last_weight_after:item.last_weight_after,
                  weight_before:item.weight_before,
                  weight_add:(item.weight_add*1).toFixed(2),
                  weight_after:item.weight_after
                }
                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()<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.after_value)
      },
      handleSizeChange(val){
        this.limit = val
        this.Getdialyzerdetail(this.after_value)
      },
      // 性别
      getgender(ids){
        if(ids ==1){
          return "男"
        }else{
          return "女"
        }
      },
       // 转换时间
      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 });
      },
      getdialyze(val){
        const option = this.dialyze_options
        for(let i in option){
          if(val == option[i].id){
            return option[i].name
          }
        }
      }
    },
    mounted(){
      this.getecharts()
    },
    created(){
      this.start_date = this.getFirstDayOfMonth(new Date())
    },

  }
</script>
