<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div class="app-container">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="按时间分组" name="first"></el-tab-pane>
        <el-tab-pane label="按项目分组" name="second"></el-tab-pane>
      </el-tabs>
      <div class="cell clearfix">
        <!-- <el-select v-model="lapseto" placeholder="请选择" style="width:120px;margin-right:10px" @change="changeLapseto">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select> -->
        <el-select v-model="type" placeholder="请选择" @change="chooseType" style="margin-right:10px">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <div v-if="type == '自定义'">
          <label class="title">
            <span class="name">日期查询</span> :
          </label>
          <el-date-picker
            v-model="listQuery.start_time"
            prefix-icon="el-icon-date"
            @change="changeTime"
            :editable="false"
            style="width: 196px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
          <span class>-</span>
          <el-date-picker
            v-model="listQuery.end_time"
            prefix-icon="el-icon-date"
            @change="changeEndTime"
            :editable="false"
            style="width: 196px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </div>
      </div>
      <div class="cell clearfix">
        <div class="time newLi" v-if="type == '按季度统计对比'">
          <ul class>
            <li
              :class="item.state == quarterType ? 'active' : ''"
              @click="chooseQuarter(item.state)"
              v-for="item in quarter"
              :key="item.value"
            >{{ item.label }}</li>
          </ul>
        </div>
        <div class="time newLi" v-if="type == '按月份统计对比'">
          <ul class>
            <li
              :class="item.state == monthType ? 'active' : ''"
              @click="chooseMonth(item.state)"
              v-for="item in month"
              :key="item.value"
            >{{ item.label }}</li>
          </ul>
        </div>
      </div>
      <div class="cell clearfix">
        <p class="chartTitle">统计图</p>
      </div>
      <div class="cell clearfix">
        <p class="point"></p>
        <p class="pointTitle">达标率</p>
      </div>
      <div>
        <line-chart :options="chart"></line-chart>
      </div>
      <div class="cell clearfix">
        <p class="point"></p>
        <p class="pointTitle">指标正常范围值</p>
      </div>
      <div class="cell clearfix newDisplay">
         <span v-for="(item,index) in normData" :key="index" class="index">
           <span v-if="item.is_status == 1">{{item.item_name}}</span> 
           <span v-if="item.is_status == 0 && item.inspection_major == 0  && item.inspection_minor == -1">收缩压</span>
            <span v-if="item.is_status == 0 && item.inspection_major == 0  && item.inspection_minor == -2">舒张压</span>
           <span v-if="item.range_type == 1 && item.is_status == 1">({{item.min_range}}-{{item.large_range}})</span>
           <span v-if="item.range_type == 2 && item.is_status == 1">({{item.range_value}})</span>
          <span v-if="item.range_type == 0 && item.is_status == 0">({{item.min_range}}-{{item.large_range}})</span>
        </span> 
      </div>
    </div>
  </div>
</template>

<script>
const moment = require('moment')
import echarts from "echarts";
import { GetOICData } from "@/api/qcd";
import LineChart from "../../qcd/components/LineChart";
import { uParseTime } from "@/utils/tools";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import {getNormData,getFirstQuarter}from "@/api/common/common"
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;;
        }
      },  
      sortOne:0,
      sortTwo:0,
      modetype:0,
      startime:"",
      endtime:"",
      activeName: "first",
      modesData: {
        xAxis: [],
        series: []
       },
      crumbs: [
        { path: false, name: "质控管理" },
        { path: false, name: "科室质控达标统计" },
        { path: false, name: "按时间分组" }
      ],
      normData:[],
      newArrData:[],
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 10
      },
      lapseto:0,
      options: [
        {
          value: 0,
          label: "全部"
        }, 
        {
          value: 1,
          label: "留治"
        }, 
        {
          value: 2,
          label: "转出"
        }, 
      ],
      value: "请选项",
      options1: [
        {
          value: "按季度统计对比",
          label: "按季度统计对比"
        },
        {
          value: "按月份统计对比",
          label: "按月份统计对比"
        },
        {
          value: "自定义",
          label: "自定义"
        }
      ],
      type: "按季度统计对比",
      quarter: [
        { value: 0, label: "第一季度", state: 0 },
        { value: 1, label: "第二季度", state: 1 },
        { value: 2, label: "第三季度", state: 2 },
        { value: 3, label: "第四季度", state: 3 }
      ],
      quarterType: 0,
      month: [
        { value: 0, label: "一月", state: 0 },
        { value: 1, label: "二月", state: 1 },
        { value: 2, label: "三月", state: 2 },
        { value: 3, label: "四月", state: 3 },
        { value: 4, label: "五月", state: 4 },
        { value: 5, label: "六月", state: 5 },
        { value: 6, label: "七月", state: 6 },
        { value: 7, label: "八月", state: 7 },
        { value: 8, label: "九月", state: 8 },
        { value: 9, label: "十月", state: 9 },
        { value: 10, label: "十一月", state: 10 },
        { value: 11, label: "十二月", state: 11 }
      ],
      monthType: 0,
      chart: {
        // title: {
        //   text: "ECharts 入门示例"
        // },
        tooltip: {},
        // legend: {
        //   data: ["达标率"],
        //   left: 0
        // },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: "{value}%"
          },
          show: false
        },
        series: [
          {
            name: "达标率",
            type: "bar",
            data: [],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: "{c}%"
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

              //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
              normal: {
                color: function(params) {
                  //我这边就两个柱子，大体就两个柱子颜色渐变，所以数组只有两个值，多个颜色就多个值
                  var colorList = [
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],

                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"]
                  ];

                  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)"
              }
            }
          }
        ],
        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 // 锁定区域禁止缩放
          }
        ]
      },
      syslarge:0,
      sysmin:0,
      dialarge:0,
      diamin:0,
    };
  },
  methods: {
    handleClick() {
      if (this.activeName == "second") {
        this.$router.push({ path: "/qcd/officesControlAnalysis/project" });
      }
    },
    changeTime(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.listQuery.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.start_time = "";
      } else {
        this.getlist()
      }

    },
    changeLapseto(val){
      if(val == 0){
        this.lapseto = 0
        this.getlist()
      }
      if(val == 1){
       this.lapseto =1
       this.getlist()
      }
      if(val == 2){
        this.lapseto = 2
        this.getlist()
      }
    },
     
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.end_time = "";
      } else {
        this.getlist()
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    selectLapseTo(state) {
      this.stateType = state;
      this.listQuery.state = state;
    },
    chooseType(val) {
       this.modesData.series = []
       this.modesData.xAxis = []
      this.type = val;
      if(val == "按月份统计对比"){ 
         this.modetype = 1
         this.monthType = 0
         this.getlist() 
      }
       if(val == "按季度统计对比"){
         this.modetype = 0
         this.getlist()
      }
      if(val == "自定义"){
        this.modetype = 2
        
      }
     
    },
    chooseQuarter(quarter) {
      this.quarterType = quarter;
      //第一季度
      if(quarter === 0){
         this.modetype = 0
        this.getlist()
        return false
      }

      //第二季度
      if(quarter === 1){
         this.modetype = 0
         this.getlist()
         return false
      }

      //第三季度
      if(quarter === 2){
        this.modetype = 0
        this.getlist()
        return false
      }

      //第四季度
      if(quarter === 3){
       this.modetype = 0
        this.getlist()
        return false
      }

      
    },
    chooseMonth(month) {  
      //1月
      if(month == 0){
        this.modetype = 1
         this.monthType = month;
        this.getlist()
         return false
      }
      //2月
      if(month == 1){
         this.modetype = 1
          this.monthType = month;
        this.getlist()
        return false
      }
      //
     //3月
      if(month == 2){
       this.modetype = 1
        this.monthType = month;
       this.getlist()
       return false
      }
      //4月
       if(month == 3){
         this.modetype = 1
          this.monthType = month;
         this.getlist()
         return false
      }
      //5月
       if(month == 4){
        this.modetype = 1
         this.monthType = month;
         this.getlist()
         return false
      }
      //6月
       if(month == 5){
         this.modetype = 1
          this.monthType = month;
        this.getlist()
        return false
      }
      //7月
       if(month == 6){
        this.monthType = month;
       this.modetype = 1
        this.getlist()
        return false
      }
      //8月
       if(month == 7){
        this.monthType = month;
        this.modetype = 1
        this.getlist()
        return false
      }
      //9月
       if(month == 8){
        this.monthType = month;
        this.modetype = 1
        this.getlist()
        return false
      }
      //10月
       if(month == 9){
        this.monthType = month;
        this.modetype = 1
        this.getlist()
        return false
      }
      //11月
       if(month == 10){
        this.monthType = month;
        this.modetype = 1
        this.getlist()
        return false
      }
       //12月
       if(month == 11){
        this.monthType = month;
        this.modetype = 1
         this.getlist()
         return false
      }
    },
    getNormData(){
      getNormData().then(response=>{
         if(response.data.state === 1){
           var newArr = []
           var normdata = response.data.data.normdata
           newArr  = normdata
          //  console.log("指标正常范围",normdata)
           var bloodpressure = response.data.data.bloodPressure
          console.log("bloodPressure",bloodpressure)
           for(let i=0;i<bloodpressure.length;i++){
              if(bloodpressure[i].inspection_major == 0 && bloodpressure[i].inspection_minor == -1 && bloodpressure[i].is_status == 0){
                 bloodpressure[i].item_name = "收缩压"
                 this.sortOne = bloodpressure[i].sort
                 this.syslarge = parseInt(bloodpressure[i].large_range)
                 this.sysmin = parseInt(bloodpressure[i].min_range)
              }
               if(bloodpressure[i].inspection_major == 0 && bloodpressure[i].inspection_minor == -2 && bloodpressure[i].is_status == 0){
                 bloodpressure[i].item_name = "舒张压"
                 this.sortTwo = bloodpressure[i].sort
                 this.dialarge = parseInt(bloodpressure[i].large_range)
                 this.diamin = parseInt(bloodpressure[i].min_range)
              }
           }

          //  console.log("血压数据",bloodpressure)
           bloodpressure.map(item=>{
             newArr.push(item)
           })
           var newarr  =  newArr.sort((a,b)=>{ return a.sort-b.sort})
          // console.log("normdata",newarr)
           this.normData = newarr
           this.getlist()
         }
      })
    },
    //第一季度
    getlist(){
       this.modesData.series = []
       this.modesData.xAxis = []
         //本月的开始时间
         //第一季度
         if(this.modetype == 0 && this.quarterType == 0){
            
             this.startime =  moment().startOf('year').format('YYYY-MM-DD')
             this.endtime = moment().month(2).endOf('month').format("YYYY-MM-DD")
             
         }
         //第二季度
         if(this.modetype ==0 && this.quarterType == 1){
             this.startime = moment().month(3).startOf('month').format("YYYY-MM-DD")   
             this.endtime = moment().month(5).endOf('month').format("YYYY-MM-DD")
         }
         //第三季度
         if( this.modetype ==0 && this.quarterType == 2){
           this.startime = moment().month(6).startOf('month').format("YYYY-MM-DD")
           this.endtime = moment().month(8).endOf('month').format("YYYY-MM-DD")
         }
         //第四季度
         if( this.modetype ==0 && this.quarterType == 3){
             this.startime = moment().month(8).startOf('month').format("YYYY-MM-DD")
             this.endtime = moment().month(11).endOf('month').format("YYYY-MM-DD")
         }
         
         //1月
         if(this.modetype == 1 && this.monthType == 0){
          this.startime = moment().month(0).startOf('month').format("YYYY-MM-DD")
          this.endtime = moment().month(0).endOf('month').format("YYYY-MM-DD")
         
         }
         //2 月
         if( this.modetype == 1 && this.monthType == 1){
            this.startime = moment().month(1).startOf('month').format("YYYY-MM-DD")
            this.endtime = moment().month(1).endOf('month').format("YYYY-MM-DD")
         }
          //3 月
         if(this.modetype == 1 && this.monthType == 2){
           this.startime = moment().month(2).startOf('month').format("YYYY-MM-DD") 
           this.endtime = moment().month(2).endOf('month').format("YYYY-MM-DD")
          
         }
          //4月
         if(this.modetype == 1 && this.monthType == 3){
           this.startime = moment().month(3).startOf('month').format("YYYY-MM-DD")
           this.endtime = moment().month(3).endOf('month').format("YYYY-MM-DD")
         }
           //5月
         if(this.modetype == 1 && this.monthType == 4){
          this.startime = moment().month(4).startOf('month').format("YYYY-MM-DD")
          this.endtime= moment().month(4).endOf('month').format("YYYY-MM-DD")
          }
            //6月
         if(this.modetype == 1 && this.monthType == 5){
           this.startime = moment().month(5).startOf('month').format("YYYY-MM-DD")
          this.endtime = moment().month(5).endOf('month').format("YYYY-MM-DD")
           
         }
            //7月
         if(this.modetype == 1 && this.monthType == 6){
          this.startime = moment().month(6).startOf('month').format("YYYY-MM-DD")
          this.endtime = moment().month(6).endOf('month').format("YYYY-MM-DD")
         }
            //8月
         if(this.modetype==1 && this.monthType == 7){
            this.startime = moment().month(7).startOf('month').format("YYYY-MM-DD")
            this.endtime = moment().month(7).endOf('month').format("YYYY-MM-DD")
         }
         //9月
          if(this.modetype == 1 && this.monthType == 8){
             this.startime = moment().month(8).startOf('month').format("YYYY-MM-DD")
            this.endtime = moment().month(8).endOf('month').format("YYYY-MM-DD")
            
         }
          //10月
          if(this.modetype == 1 && this.monthType == 9){
           this.startime = moment().month(9).startOf('month').format("YYYY-MM-DD")
           this.endtime = moment().month(9).endOf('month').format("YYYY-MM-DD")
            
         }
         //11月
         if(this.modetype == 1 && this.monthType == 10){
            this.startime = moment().month(10).startOf('month').format("YYYY-MM-DD")       
            this.endtime = moment().month(10).endOf('month').format("YYYY-MM-DD")
         }
          //12月
         if(this.modetype == 1 && this.monthType == 11){
          
           this.startime = moment().month(11).startOf('month').format("YYYY-MM-DD")
           this.endtime = moment().month(11).endOf('month').format("YYYY-MM-DD")
         }

         if(this.modetype == 2){
            this.startime = this.listQuery.start_time
            this.endtime = this.listQuery.end_time
         }
        const params = {
          lapseto:this.lapseto,
          startime:this.startime,
          endtime:this.endtime
        }
      getFirstQuarter(params).then(response=>{
         if(response.data.state === 1){
            var count =  response.data.data.count
    
            var countwo = response.data.data.countwo 
           
            var systolicTotal =  response.data.data.systolicTotal
            console.log("systolictotal",systolicTotal)
            var sysstandTotal = 0
            var systolic = response.data.data.systolic
           console.log("systolic",systolic)
            var sysarr = []
            for(let i=0;i<systolic.length;i++){
              if(systolic[i].systolic_blood_pressure >= this.sysmin && systolic[i].systolic_blood_pressure<=this.syslarge){
                  sysarr.push(systolic[i])
              }
            } 
            sysstandTotal = sysarr.length
           console.log("sysarr",sysarr)

            var diastotal =  response.data.data.diastotal
            var diasstandtotal = 0
          
            var diastolic = response.data.data.diastolic
            // console.log("diastolic",diastolic)
            var diaArr=[]
            for(let i=0;i<diastolic.length;i++){
             if(diastolic[i].diastolic_blood_pressure>=this.diamin && diastolic[i].diastolic_blood_pressure<=this.dialarge){
                  diaArr.push(diastolic[i])
             }
            }
            // console.log("diaArr",diaArr)
            diasstandtotal = diaArr.length
            var normData = response.data.data.normData
          
            var newArr = [
              {item_id:0,Total:0,Count:0,sort:0},
              {item_id:0,Total:0,Count:0,sort:0}
            ]
     
            for(let i=0;i<newArr.length;i++){
               if(sysstandTotal == 0){
                  newArr[0].Total = 1
                  newArr[0].Count = sysstandTotal
                  newArr[0].sort = this.sortOne

               }else{
                newArr[0].Total = systolicTotal
                newArr[0].Count = sysstandTotal
                newArr[0].sort = this.sortOne
               }
               if(diasstandtotal == 0){
                  newArr[1].Total = 1
                  newArr[1].Count = diasstandtotal
                  newArr[1].sort = this.sortTwo
               }else{
                newArr[1].Total = diastotal
                newArr[1].Count = diasstandtotal
                newArr[1].sort = this.sortTwo
               }
            }
 
            countwo.map(item=>{
              count.push(item)
            })
         
            //获取已经配置的数据 
            var arr=[]
            for(let i=0;i<count.length;i++){  
               for(let j=0;j<normData.length;j++){
                if(count[i].item_id == normData[j].inspection_minor){
                     arr.push(count[i])
                }
              }
            }
      
           
            var arrtwo =  this.arrayDate(count,normData)
           
            for(let i=0;i<arrtwo.length;i++){
                this.$set(arrtwo[i], 'Count', 0)
              }
           for(let i=0;i<arrtwo.length;i++){
                this.$set(arrtwo[i], 'Total', 1)
              }
            arrtwo.map(item => {
              arr.push(item)
            })
          
            newArr.map(item=>{
              arr.push(item)
            }) 
            arr.sort(this.compare('sort'))  
            

            for(const key in this.normData ){
               this.modesData.xAxis.push(this.normData[key].item_name);
                if(key in arr){
                    this.modesData.series.push(((parseInt(arr[key].Count)/parseInt(arr[key].Total))*100).toFixed(1));
                } else {
                 this.modesData.series.push(0);
              }
            }
            this.chart.series[0].data = this.modesData.series
            this.chart.xAxis.data = this.modesData.xAxis
            this.getArrLength(this.chart.xAxis.data)
          
         }
      })
    },
    compare(property){
      return function(a,b){
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
      }
    },
    arrayDate(array1,array2){
        var array1 = array1;
        var array2 = array2;
        var result = [];
        for(var i = 0; i < array2.length; i++){
            var obj = array2[i];
            var num = obj.inspection_minor;   //staff_id   就是要对比的key
            var isExist = false;
            for(var j = 0; j < array1.length; j++){
                var aj = array1[j];
                var n = aj.item_id;
                if(n == num){
                    isExist = true;
                    break;
             }
            }
            if(!isExist){
                result.push(obj);
            }
        }
        return result;
    },
    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(){
     //获取指标正常范围值
     this.getNormData()
    // this.getFirstQuarter(this.lapseto,firstQuarterStart,firstQuarterEnd)
  }
};
</script>

<style lang="scss" scoped>
.newLi {
  li {
    background: #f5f5f6;
  }
}
.chartTitle {
  font-size: 16px;
  font-weight: bold;
  color: #000000;
}
.point {
  width: 13px;
  height: 13px;
  background: linear-gradient(
    0deg,
    rgba(169, 224, 243, 1),
    rgba(159, 189, 252, 1)
  );
  border-radius: 7px;
  margin-right: 8px;
}
.pointTitle {
  font-size: 13px;
}
.index {
  color: #a09ba3;
  font-size: 13px;
  margin-right: 36px;
  margin-bottom: 20px;
}
.newDisplay {
  flex-wrap: wrap;
  padding-left: 20px;
}
</style>
