<template>
  <div class="page_checkStatisticsPersonal">
    <div class="searchBox">
      <el-autocomplete
        class="checkSearch"
        popper-class="my-autocomplete"
        v-model="search_value"
        :fetch-suggestions="querySearchAsync"
        :trigger-on-focus="false"
        placeholder="输入病人透析号/姓名"
        @select="handleSelect"
      >
        <i class="el-icon-search el-input__icon" slot="suffix"></i>
        <template slot-scope="{ item }">
          <div class="name">{{ item.name }}</div>
        </template>
      </el-autocomplete>
    </div>
    <div class="options">
      <div class="optionsOne" @click="typeShow = true">
        <div style="display: flex;align-items: center;">
          {{ type }}
          <van-icon name="arrow-down" />
        </div>
      </div>
      <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>
      <van-popup v-model="typeShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="patientArr"
          @confirm="chooseState"
          @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 { PostSearch } from '@/api/patient'
import echarts from 'echarts'
import BarChart from '../components/BarChart'
import {getMobilePatientList, getMobileInspectionList, getPatientInspectionDetail, GetSearchPatientDetail} from '@/api/common/common'
export default {
  components: {
    BarChart
  },
  data () {
    return {
      modesData: {
        xAxis: [],
        series: []
      },
      tableData: [],
      type: '请选择患者',
      typeShow: false,
      columns: ['A区', 'B区'],
      columns1: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
      startShow: false,
      endShow: false,
      currentDate: new Date(),
      startTime: '请选择',
      endTime: '请选择',
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2025, 10, 1),
      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: (params) => {
                  if (this.obj.length > 0) {
                    let str = ''
                    str = params.data + '次' + '\n(参考值' + this.obj[params.dataIndex] + '次)'
                    return str
                  } else {
                    let str = ''
                    str = params.data + '次'
                    return str
                  }
                }
              }
            },
            // 配置样式
            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.5)'
              }
            }
          }
        ],
        dataZoom: [
          {
            // Y轴固定,让内容滚动
            type: 'slider',
            show: false,
            xAxisIndex: [0],
            start: 1,
            end: 50, // 设置X轴刻度之间的间隔(根据数据量来调整)
            zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 1,
            end: 20,
            zoomLock: true // 锁定区域禁止缩放
          }
        ]
      },
      currentDate1: new Date(new Date().setMonth(new Date().getMonth() - 3)),
      currentDate2: new Date(),
      minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      maxDate: new Date(),
      patientArr: [],
      tableData: [],
      searchValue: '',
      search_value: '',
      patient_id: 0,
      obj: [],
      patientid: 0
    }
  },
  methods: {
    chooseState (val) {
      // console.log(val)
      this.modesData.series = []
      this.modesData.xAxis = []
      this.type = val
      this.typeShow = false
      let id = ''
      this.patients.map(item => {
        if (item.name == val) {
          id = item.id
        }
      })
      getPatientInspectionDetail(id, this.startTime, this.endTime).then(response => {
        if (response.data.state === 1) {
          var patientdetail = response.data.data.patientdetail
          var arr = []
          for (let i = 0; i < this.tableData.length; i++) {
            for (let j = 0; j < patientdetail.length; j++) {
              if (this.tableData[i].inspection_major == patientdetail[j].ProjectId) {
                arr.push(patientdetail[j])
              }
            }
          }
          let time = new Date(this.endTime) - new Date(this.startTime)
          let day = parseInt(time / (1000 * 60 * 60 * 24))
          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name)
            if (key in arr) {
              this.modesData.series.push(parseInt(arr[key].Count))
              this.obj.push(Math.round(day / arr[key].InspectionFrequency))
              // batotal += parseInt(res[key].Count);
            } else {
              this.modesData.series.push(0)
              this.obj.push(0)
            }
          }
          this.options.series[0].data = this.modesData.series
          this.options.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.options.xAxis.data)
        }
      })
    },
    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.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.endShow = false
      this.getList()
    },
    loadMore () {
      if (this.aq == false) {
        return
      }
      if (this.page == 1) {
        this.page++
      }
      let res = {
        date: '123',
        name: '记录卡sad',
        province: '接口',
        city: '萨达',
        address: '广东省深圳市',
        zip: 1111111
      }
      this.tableData.push(res)
    },
    onCancel () {},
    // 搜索
    onSearch () {
      this.modesData.series = []
      this.modesData.xAxis = []
      GetSearchPatientDetail(this.patient_id, this.startTime, this.endTime).then(response => {
        if (response.data.state === 1) {
          var PatientsInfo = response.data.data.PatientsInfo
          this.isStop = true
          var arr = []
          for (let i = 0; i < this.tableData.length; i++) {
            for (let j = 0; j < PatientsInfo.length; j++) {
              if (this.tableData[i].inspection_major == PatientsInfo[j].ProjectId) {
                arr.push(PatientsInfo[j])
              }
            }
          }

          let time = new Date(this.endTime) - new Date(this.startTime)
          let day = parseInt(time / (1000 * 60 * 60 * 24))

          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name)
            if (key in arr) {
              this.modesData.series.push(parseInt(arr[key].Count))
              this.obj.push(Math.round(day / arr[key].InspectionFrequency))
              // batotal += parseInt(res[key].Count);
            } else {
              this.modesData.series.push(0)
              this.obj.push(0)
            }
          }
          this.options.series[0].data = this.modesData.series
          this.options.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.options.xAxis.data)
        }
      })
    },
    initStartTime (value) {
      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}`
    },
    initEndTime (value) {
      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}`
    },
    // 获取病人列表
    getMobilePatientList () {
      getMobilePatientList().then(response => {
        if (response.data.state === 1) {
          var patients = response.data.data.patients
          this.patients = patients
          for (let i = 0; i < patients.length; i++) {
            this.patientid = patients[0].id
            this.type = patients[0].name
          }
          patients.map(item => {
            this.patientArr.push(item.name)
          })
          this.getList()
          // console.log('病人列表', patients)
        }
      })
    },
    getList () {
      getMobileInspectionList(this.startTime, this.endTime, this.patientid).then(response => {
        if (response.data.state === 1) {
          var Inspection = response.data.data.Inspection
          // console.log('Inspection', Inspection)
          this.tableData = Inspection
          var counts = response.data.data.counts
          // console.log('counts', counts)
          var arr = []
          for (let i = 0; i < Inspection.length; i++) {
            for (let j = 0; j < counts.length; j++) {
              if (Inspection[i].inspection_major == counts[j].ProjectId) {
                arr.push(counts[j])
              }
            }
          }
          // console.log('arr', arr)

          var arrtwo = this.arrayDate(counts, this.normData)
          // console.log('arrtwo', arrtwo)
          var hash = {}
          var i = 0
          var res = []
          arr.forEach(function (item) {
            var ProjectName = item.ProjectName
            hash[ProjectName] ? res[hash[ProjectName] - 1].Count.push(item.Count) : hash[ProjectName] = ++i && res.push({
              Count: [item.Count],
              ProjectName: ProjectName,
              ProjectId: item.ProjectId,
              Sort: item.Sort
            })
          })

          res.map(item => {
            item.Count = eval(item.Count.join('+'))
          })

          let arr1 = []
          this.tableData.map(it => {
            arr1.push(it.project_name)
          })

          arr1.forEach((item, index) => {
            if (!(res[index] && item == res[index].ProjectName)) {
              res.splice(index, 0, {Count: 0, ProjectName: item, Sort: index + 1})
            }
          })
          res.map(item => {
            this.modesData.series.push(parseInt(item.Count))
          })
          let time = new Date(this.endTime) - new Date(this.startTime)
          let day = parseInt(time / (1000 * 60 * 60 * 24))

          for (const key in this.tableData) {
            this.modesData.xAxis.push(this.tableData[key].project_name)
            this.obj.push(Math.round(day / this.tableData[key].inspection_frequency))
          }

          this.options.series[0].data = this.modesData.series
          this.options.xAxis.data = this.modesData.xAxis
          this.getArrLength(this.options.xAxis.data)
        }
      })
    },

    arrayDate (array1, array2) {
      var array1 = array1
      var array2 = this.tableData
      var result = []
      for (var i = 0; i < array2.length; i++) {
        var obj = array2[i]
        var num = obj.inspection_major // staff_id   就是要对比的key
        var isExist = false
        for (var j = 0; j < array1.length; j++) {
          var aj = array1[j]
          var n = aj.ProjectId
          if (n == num) {
            isExist = true
            break
          }
        }
        if (!isExist) {
          result.push(obj)
        }
      }
      return result
    },
    querySearchAsync (keyword, cb) {
      let key = ''
      if (keyword != undefined) {
        key = keyword
      }
      let searchArray = []
      PostSearch(key).then(response => {
        if (response.data.state == 1) {
          searchArray = response.data.data.patient
          cb(searchArray)
        } else {
          cb([])
        }
      })
    },
    handleSelect (val) {
      this.type = val.name
      this.search_value = val.name
      this.patient_id = val.id
      this.onSearch()
    },
    getArrLength (result) {
      if (result.length > 4) {
        var dataZoom_end = (4 / result.length) * 100
        this.options.dataZoom[0].end = dataZoom_end
      } else {
        var dataZoom_end = 100
        this.options.dataZoom[0].end = dataZoom_end
      }
    }

  },
  created () {
    this.initStartTime(this.currentDate1)
    this.initEndTime(this.currentDate2)
    this.tableHeight = (document.documentElement.clientHeight - (Number(document.documentElement.style.fontSize.slice(0, -2)) * 2.75)) + 'px'

    // 获取病人列表
    this.getMobilePatientList()

    // // 统计列表
    // this.getList()
  }
}
</script>

<style lang="scss" scoped>
.page_assayTemplate {

  .chart1 {
    font-size: 1rem;
    font-weight: bold;
    color: #000;
    margin: 0.625rem 0 0.625rem 0.8125rem;
  }

  .chart {
    font-size: 1rem;
    font-weight: bold;
    margin-left: 0.8125rem;
    color: #000;
  }

  }
.page_checkStatisticsPersonal {
   .searchBox{
    background: #F6F6F6;
    height: 3rem;
    display: flex;
    align-items: center;
    padding:0 0.625rem;
  }
  .options {
    width: 31.25rem;
    display: flex;
    height: 3.125rem;
    align-items: center;
    flex-wrap: nowrap;
    overflow-x: auto;
    .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;
    }
    .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: 0 0 0 0.8125rem;
  }
  .chart {
    font-size: 1rem;
    font-weight: bold;
    margin-left: 0.8125rem;
    color: #000;
  }
}
::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>
<style lang="scss">
  .page_checkStatisticsPersonal {
     .searchBox{
      .el-input{
        font-size: 14px !important;
      }
      .el-autocomplete{
        width: 100%;
      }
      .el-input__inner{
        border-radius:1rem;
        line-height: 2rem;
        height:2rem;
        border:none;
      }
      .el-input__icon{
        line-height:2rem;
      }
    }
    .van-field__body{
    width:100%;
  }
  .van-cell__value {
    display: flex;
    align-items: center;
  }
  .van-search__content {
    border-radius: 1.875rem;
  }
  .el-table__fixed-body-wrapper {
    top: 2.625rem;
  }
  .el-table {
    ::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
    .el-table__fixed-right {
      right: 0 !important;
    }
    // .el-table__fixed {
    //   height: 15.625rem !important;
    // }
    // .el-table__fixed-right {
    //   height: 15.625rem !important;
    // }

  }
  .el-table td, .el-table th{
    text-align: center;
  }
  }
</style>
