<template>
  <div class="page_time">
    <div class="optionsBox">

      <div class="optionsOne" @click="typeShow = true">
        <div style="display: flex;align-items: center;">
          {{ type }}
          <van-icon name="arrow-down" />
        </div>
      </div>
    </div>
    <div class="quarterBox" v-if="type == '按季度统计对比'">
      <p :class="Num == 1 ? 'active' : ''" @click="onClick(1)">第一季度</p>
      <p :class="Num == 2 ? 'active' : ''" @click="onClick(2)">第二季度</p>
      <p :class="Num == 3 ? 'active' : ''" @click="onClick(3)">第三季度</p>
      <p :class="Num == 4 ? 'active' : ''" @click="onClick(4)">第四季度</p>
    </div>
    <div class="month" v-if="type == '按月份统计对比'">
      <div class="monthBox" ref="nav">
        <p
          v-for="(item, index) in monthArr"
          :key="index"
          :class="month == index ? 'active' : ''"
          @click="clickMonth(index)"
        >{{ item }}</p>
      </div>
    </div>
    <div class="toolBox" v-if="type == '自定义'">
      <div class="toolOne" @click="startShow = true">
        <div style="display: flex;align-items: center;">
          {{ startTime }}
          <van-icon name="arrow-down" />
        </div>
      </div>
      <div class="toolOne" @click="endShow = true">
        <div style="display: flex;align-items: center;">
          {{ endTime }}
          <van-icon name="arrow-down" />
        </div>
      </div>
    </div>
    <div class="chart1">统计图</div>
    <div>
      <bar-chart :options="options"></bar-chart>
    </div>
    <div class="rangeBox">
      <p class="range"></p>
      <span>指标正常范围值</span>
    </div>
    <div class="rangeMain">
      <p v-for="(item,index) in this.normData" :key="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>
      </p>
    </div>

    <div>
      <van-popup v-model="stateShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="stateShow = false"
        />
      </van-popup>
      <van-popup v-model="typeShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="columns1"
          @confirm="chooseType"
          @cancel="typeShow = false"
        />
      </van-popup>
      <van-popup v-model="startShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime"
          @cancel="startShow = false"
        />
      </van-popup>
      <van-popup v-model="endShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime2"
          @cancel="endShow = false"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import BarChart from '../../dqc/components/BarChart'
import { getMobileNormData, getMobileFirstQuarter } from '@/api/common/common'
const moment = require('moment')
let autoScrollInstance = null
export default {
  components: {
    BarChart
  },
  data () {
    return {
      modesData: {
        xAxis: [],
        series: []
      },
      quarterType: 0,
      monthType: 0,
      normData: [],
      state: '归转状态',
      type: '按季度统计对比',
      stateShow: false,
      typeShow: false,
      columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
      columns1: [
        '按季度统计对比',
        '按月份统计对比',
        '自定义(时间范围只能查询最近一年数据)'
      ],
      Num: 1,
      month: 0,
      monthArr: [
        '一月',
        '二月',
        '三月',
        '四月',
        '五月',
        '六月',
        '七月',
        '八月',
        '九月',
        '十月',
        '十一月',
        '十二月'
      ],
      startShow: false,
      endShow: false,
      currentDate: new Date(),
      startTime: '请选择',
      endTime: '请选择',
      options: {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        xAxis: {
          data: [],
          axisLabel: {
            interval: 0,
            formatter: function (value) {
              var ret = '' // 拼接加\n返回的类目项
              var maxLength = 4 // 每项显示文字个数
              var valLength = value.length // X轴类目项的文字个数
              var rowN = Math.ceil(valLength / maxLength) // 类目项需要换行的行数
              if (rowN > 1) {
                // 如果类目项的文字大于3,
                for (var i = 0; i < rowN; i++) {
                  var temp = '' // 每次截取的字符串
                  var start = i * maxLength // 开始截取的位置
                  var end = start + maxLength // 结束截取的位置
                  // 这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                  temp = value.substring(start, end) + '\n'
                  ret += temp // 凭借最终的字符串
                }
                return ret
              } else {
                return value
              }
            }
          }
        },
        yAxis: {
          axisLabel: {
            formatter: '{value} %'
          },
          show: false
        },
        series: [
          {
            name: '达标率%',
            type: 'bar',
            data: [],
            barWidth: 20,
            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: 50, // 设置X轴刻度之间的间隔(根据数据量来调整)
            zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 1,
            end: 50,
            zoomLock: true // 锁定区域禁止缩放
          }
        ]
      },
      startime: 0,
      endtime: 0,
      currentDate1: new Date(),
      currentDate2: new Date(),
      minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      maxDate: new Date(),
      sortOne: 0,
      sortTwo: 0,
      syslarge: 0,
      sysmin: 0,
      dialarge: 0,
      diamin: 0
    }
  },
  methods: {
    onClick (id) {
      if (id == 1) {
        this.Num = 1
        this.getlist()
      } else if (id == 2) {
        this.Num = 2
        this.getlist()
      } else if (id == 3) {
        this.Num = 3
        this.getlist()
      } else if (id == 4) {
        this.Num = 4
        this.getlist()
      }
    },
    clickMonth (index) {
      this.month = index
      // 1月
      if (index == 0) {
        this.monthType = 0
        this.getlist()
        return false
      }
      // 2月
      if (index == 1) {
        this.monthType = 1
        this.getlist()
        return false
      }
      // 3月
      if (index == 2) {
        this.monthType = 2
        this.getlist()
        return false
      }
      // 4月
      if (index == 3) {
        this.monthType = 3
        this.getlist()
        return false
      }
      // 5月
      if (index == 4) {
        this.monthType = 4
        this.getlist()
        return false
      }
      // 6月
      if (index == 5) {
        this.monthType = 5
        this.getlist()
        return false
      }
      // 7月
      if (index == 6) {
        this.monthType = 6
        this.getlist()
        return false
      }
      // 8月
      if (index == 7) {
        this.monthType = 7
        this.getlist()
        return false
      }
      // 9月
      if (index == 8) {
        this.monthType = 8
        this.getlist()
        return false
      }
      // 10月
      if (index == 9) {
        this.monthType = 9
        this.getlist()
        return false
      }
      // 11月
      if (index == 10) {
        this.monthType = 10
        this.getlist()
        return false
      }
      // 12月
      if (index == 11) {
        this.monthType = 11
        this.getlist()
        return false
      }
    },
    chooseType (val) {
      if (val == '按季度统计对比') {
        this.type = '按季度统计对比'
        this.quarterType = 0
        this.getlist()
        this.typeShow = false
      }
      if (val == '按月份统计对比') {
        this.type = '按月份统计对比'
        this.monthType = 0
        this.quarterType = 1
        this.getlist()
        this.typeShow = false
      }
      if (val == '自定义(时间范围只能查询最近一年数据)') {
        this.type = '自定义'
        this.quarterType = 2
        this.getlist()
        this.typeShow = false
      }
    },
    getstartTime (value) {
      this.page = 1
      let year = value.getFullYear()
      let month = value.getMonth() + 1
      let day = value.getDate()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }

      this.startTime = `${year}-${month}-${day}`

      this.startShow = false
      this.startime = `${year}-${month}-${day}`
      this.getlist()
    },
    getstartTime2 (value) {
      this.page = 1
      let year = value.getFullYear()
      let month = value.getMonth() + 1
      let day = value.getDate()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }

      this.endTime = `${year}-${month}-${day}`
      this.endtime = `${year}-${month}-${day}`
      this.endShow = false
      this.getlist()
    },
    onConfirm () {

    },
    getMobileNormData () {
      getMobileNormData().then(response => {
        if (response.data.state == 1) {
          var newArr = []
          var normdata = response.data.data.normdata
          // console.log('normdata', normdata)
          newArr = normdata
          var bloodPressure = response.data.data.bloodPressure
          for (let i = 0; i < bloodPressure.length; i++) {
            if (bloodPressure[i].is_status == 0 && bloodPressure[i].inspection_major == 0 && bloodPressure[i].inspection_minor == -1) {
              bloodPressure[i].item_name = '收缩压'
              this.sortOne = bloodPressure[i].sort
              this.sysmin = bloodPressure[i].min_range
              this.syslarge = bloodPressure[i].large_range
            }
            if (bloodPressure[i].is_status == 0 && bloodPressure[i].inspection_major == 0 && bloodPressure[i].inspection_minor == -2) {
              bloodPressure[i].item_name = '舒张压'
              this.sortTwo = bloodPressure[i].sort
              this.diamin = bloodPressure[i].min_range
              this.dialarge = bloodPressure[i].large_range
            }
          }
          bloodPressure.map(item => {
            newArr.push(item)
          })
          var newarr = newArr.sort((a, b) => { return a.sort - b.sort })
          this.normData = newarr
          // console.log('pressuree', bloodPressure)
          this.getlist()
        }
      })
    },
    getlist () {
      this.modesData.series = []
      this.modesData.xAxis = []
      // console.log('number', this.Num)
      // console.log('quarterType', this.quarterType)
      // 第一季度
      if (this.Num == 1 && 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.Num == 2 && this.quarterType == 0) {
        this.startime = moment().month(3).startOf('month').format('YYYY-MM-DD')
        this.endtime = moment().month(5).endOf('month').format('YYYY-MM-DD')
      }
      // 第三季度
      if (this.Num == 3 && this.quarterType == 0) {
        this.startime = moment().month(6).startOf('month').format('YYYY-MM-DD')
        this.endtime = moment().month(8).endOf('month').format('YYYY-MM-DD')
      }

      // 第四季度
      if (this.Num == 4 && this.quarterType == 0) {
        this.startime = moment().month(8).startOf('month').format('YYYY-MM-DD')
        this.endtime = moment().month(11).endOf('month').format('YYYY-MM-DD')
      }

      if (this.monthType == 0 && this.quarterType == 1) {
        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.monthType == 1 && this.quarterType == 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.monthType == 2 && this.quarterType == 1) {
        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.monthType == 3 && this.quarterType == 1) {
        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.monthType == 4 && this.quarterType == 1) {
        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.monthType == 5 && this.quarterType == 1) {
        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.monthType == 6 && this.quarterType == 1) {
        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.monthType == 7 && this.quarterType == 1) {
        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.monthType == 8 && this.quarterType == 1) {
        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.monthType == 9 && this.quarterType == 1) {
        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.monthType == 10 && this.quarterType == 1) {
        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.monthType == 11 && this.quarterType == 1) {
        this.startime = moment().month(11).startOf('month').format('YYYY-MM-DD')
        this.endtime = moment().month(11).endOf('month').format('YYYY-MM-DD')
      }
      const params = {
        startime: this.startime,
        endtime: this.endtime
      }
      getMobileFirstQuarter(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

          var sysstandTotal = 0

          var systolic = response.data.data.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
          var diastotal = response.data.data.diastotal

          var diasstandtotal = 0
          var diastolic = response.data.data.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.options.series[0].data = this.modesData.series
          this.options.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.options.xAxis.data)
        }
      })
    },
    getArrLength (result) {
      if (result.length > 5) {
        var dataZoom_end = (5 / result.length) * 100
        this.options.dataZoom[0].end = dataZoom_end
      } else {
        var dataZoom_end = 100
        this.options.dataZoom[0].end = dataZoom_end
      }
    },
    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
    },
    compare (property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    }
  },
  created () {
    this.getMobileNormData()
  }
}
</script>

<style lang="scss" scoped>
.page_time {
  .optionsBox {
    display: flex;
    height: 3.125rem;
    align-items: center;
    .optionsOne {
      //   max-width: 8.75rem;
      //   min-width: 6.25rem;
      padding: 0 0.75rem;
      height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      border-radius: 5px;
      text-align: center;
      font-size: 0.8125rem;
      color: #8d8d8d;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 0.8125rem;
    }
  }
  .quarterBox {
    display: flex;
    justify-content: space-around;
    p {
      width: 4.6875rem;
      height: 1.875rem;
      line-height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      // opacity: 0.8;
      border-radius: 0.3125rem;
      color: #8d8d8d;
      cursor: pointer;
      text-align: center;
      font-size: 0.8125rem;
    }
    .active {
      background: rgba(51, 138, 251, 1);
      color: #fff;
      border: 1px solid #338afb;
    }
  }
  .month {
    overflow-x: auto;
  }
  .monthBox {
    width: 50rem;
    overflow-x: auto;
    display: flex;
    flex-wrap: nowrap;
    p {
      //   width: 2.5rem;
      padding: 0 0.875rem;
      height: 1.875rem;
      line-height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      opacity: 0.8;
      border-radius: 0.3125rem;
      color: #8d8d8d;
      cursor: pointer;
      text-align: center;
      font-size: 0.8125rem;
      margin-left: 0.625rem;
    }
    .active {
      background: rgba(51, 138, 251, 1);
      color: #fff;
      border: 1px solid #338afb;
    }
  }
  .toolBox {
    display: flex;
    height: 2.5rem;
    align-items: center;
    .toolOne {
      width: 6.25rem;
      height: 1.875rem;
      background: rgba(246, 246, 246, 1);
      border-radius: 5px;
      text-align: center;
      font-size: 0.8125rem;
      color: #8d8d8d;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 0.8125rem;
    }
  }
  .chart1 {
    font-size: 1rem;
    font-weight: bold;
    color: #000;
    margin: .625rem 0 0 0.8125rem;
  }
  .chart {
    font-size: 1rem;
    font-weight: bold;
    margin-left: 0.8125rem;
    color: #000;
    // margin-top: 1.375rem;
  }
  .rangeBox {
    margin-left: 0.8125rem;
    display: flex;
    align-items: center;
    margin-bottom: 0.5rem;
    .range {
      width: 0.8125rem;
      height: 0.8125rem;
      background: linear-gradient(
        0deg,
        rgba(169, 224, 243, 1),
        rgba(159, 189, 252, 1)
      );
      border-radius: 0.25rem;
      margin-right: 0.5rem;
    }
    span {
      color: #5d5a5f;
      font-size: 0.75rem;
    }
  }
  .rangeMain {
    display: flex;
    flex-wrap: wrap;
    padding-left: 2.125rem;
    margin-top: 0.5rem;
    p {
      margin-right: 1.625rem;
      font-size: 0.75rem;
      color: #a09ba3;
      margin-bottom: 0.5rem;
    }
  }
}
::-webkit-scrollbar {
  height: 0 !important;
  width: 0;
}
</style>
<style lang="scss">
::-webkit-scrollbar {
  height: 0 !important;
  width: 0;
}
</style>
