<template>
  <div class="page_checkStatisticsAll">
     <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="stateShow = true">
        <div style="display: flex;align-items: center;">
          {{ state }}
          <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>
      <el-table ref="tab" :data="tableData" style="width: 100%" :height="tableHeight" v-loadmore="loadMore" border :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
        <el-table-column fixed="left" prop="name" label="姓名" width="70" align="center"></el-table-column>
        <el-table-column
          :label="modeItem.project_name+'('+modeItem.inspection_frequency+'天)'"
          property="number"
          align="center"
          min-width="110"
          v-for="(modeItem, index) in tableName"
          :key="index"
        >
          <template slot-scope="scope">
              <span v-if="Math.floor(90/modeItem.inspection_frequency) <= scope.row.data[index].Count" style="color:black">{{ scope.row.data[index].Count}}</span>
              <span v-if="Math.floor(90/modeItem.inspection_frequency) > scope.row.data[index].Count" style="color:red">{{ scope.row.data[index].Count}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <van-popup v-model="stateShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="patientArr"
          @confirm="chooseState"
          @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 { PostSearch } from '@/api/patient'
import echarts from 'echarts'
import BarChart from '../components/BarChart'
import { getMobilePatientList, getAllMobileMajorInspection, getMobilePatientTwo, getMobilePatientDetailCheck } from '@/api/common/common'
export default {
  components: {
    BarChart
  },
  data () {
    return {
      search_value: '',
      patient_id: 0,
      tableHeight: '',
      value: '',
      tableData: [],
      ObjectData: {},
      tableName: [],
      typeShow: false,
      state: '请选择病人',
      stateShow: false,
      columns: ['A区', 'B区'],
      columns1: ['化验次数', '下次化验时间'],
      startShow: false,
      endShow: false,
      currentDate: new Date(),
      startTime: '请选择',
      endTime: '请选择',
      patientArr: [],
      // minDate: new Date(1970, 0, 1),
      // maxDate: new Date(2025, 10, 1),
      minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      maxDate: new Date(),
      currentDate1: new Date(new Date().setMonth(new Date().getMonth() - 3)),
      currentDate2: new Date(),
      page: 1,
      limit: 20,
      options: {
        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'],

                    ['#FFD7C0', '#FF9994']
                  ]

                  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)'
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    chooseType (val) {
    },
    chooseState (val) {
      this.state = val
      this.stateShow = false
      let id = ''
      this.patients.map(item => {
        if (item.name == val) {
          id = item.id
        }
      })
      this.tableData = []
      getMobilePatientDetailCheck(id, this.startTime, this.endTime).then(response => {
        if (response.data.state == 1) {
          var checkDetail = response.data.data.checkDetail
          this.isStop = true
          // console.log('checkDetail', checkDetail)
          var arr = []
          for (let i = 0; i < checkDetail.length; i++) {
            for (let j = 0; j < this.tableName.length; j++) {
              if (checkDetail[i].ProjectId == this.tableName[j].inspection_major) {
                arr.push(checkDetail[i])
              }
            }
          }
          let projectArr = []
          this.newArr.map(item => {
            projectArr.push(item.project_name)
          })
          // console.log('projectArr', projectArr)
          projectArr.forEach((item, index) => {
            if (!(arr[index] && item == arr[index].ProjectName)) {
              arr.splice(index, 0, {Count: 0, ProjectName: item, name: val})
            }
          })
          this.tableData = []
          let obj = {}
          obj.name = val
          obj.data = arr
          this.tableData.push(obj)
          this.total = 1
          // console.log('arr', this.tableData)
        }
      })
    },
    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.tableData = []
      this.getMobilePatientTwo()
    },
    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.tableData = []
      this.getMobilePatientTwo()
    },
    loadMore () {
      if (!this.isStop) {
        this.isStop = true
        this.page++
        getMobilePatientTwo(this.startTime, this.endTime, this.limit, this.page).then(response => {
          if (response.data.state === 1) {
            this.loading = false
            var patientInfo = response.data.data.patientInfo
            // console.log('patientInfo', patientInfo)
            var total = response.data.data.total
            // console.log('total', total)
            var list = response.data.data.list
            // console.log('list', list)

            var dtd = []
            for (let i = 0; i < list.length; i++) {
              for (let j = 0; j < this.tableName.length; j++) {
                if (list[i].ProjectId == this.tableName[j].inspection_major) {
                  dtd.push(list[i])
                }
              }
            }
            // console.log('dtd', dtd)
            var dd = {}
            for (const index in dtd) {
              if (!(dtd[index].name in dd)) {
                dd[dtd[index].name] = {}
              }
              if (!(dtd[index].ProjectId in dd[dtd[index].name]) && dtd[index].ProjectId != 0) {
                dd[dtd[index].name][dtd[index].ProjectName] = dtd[index]
              }
            }
            for (const key in dd) {
              for (const mkey in this.ObjectData) {
                if (!(this.ObjectData[mkey].project_name in dd[key])) {
                  dd[key][this.ObjectData[mkey].project_name] = {
                    ProjectName: this.ObjectData[mkey].project_name,
                    name: mkey,
                    Count: 0
                  }
                }
              }
              this.tableData.push({ name: key, data: dd[key]})
            }
            // console.log('表', this.tableData)
            let projectArr = []
            this.newArr.map(item => {
              projectArr.push(item.project_name)
            })
            this.tableData.map(item => {
              let arr = Object.values(item.data)
              arr.sort((a, b) => {
                return projectArr.indexOf(a.ProjectName) - projectArr.indexOf(b.ProjectName)
              })
              item.data = arr
            })
            let newData = this.tableData
            this.tableData = []
            newData.map(item => {
              this.tableData.push(item)
            })
            if (response.data.data.list.length <= 0) {
              this.isStop = true
            } else {
              this.isStop = false
            }
            // this.patientData = list
          } else {
            this.loading = false

            this.$toast({
              message: response.msg
            })
          }
        })
          .catch(error => {
            this.loading = false
          })
      }
    },
    onCancel () {},
    onSearch () {
      getMobilePatientDetailCheck(this.patient_id, this.startTime, this.endTime).then(response => {
        if (response.data.state == 1) {
          var checkDetail = response.data.data.checkDetail
          // console.log('checkDetail', checkDetail)
          var arr = []
          for (let i = 0; i < checkDetail.length; i++) {
            for (let j = 0; j < this.tableName.length; j++) {
              if (checkDetail[i].ProjectId == this.tableName[j].inspection_major) {
                arr.push(checkDetail[i])
              }
            }
          }
          let projectArr = []
          this.newArr.map(item => {
            projectArr.push(item.project_name)
          })
          // console.log('projectArr', projectArr)
          projectArr.forEach((item, index) => {
            if (!(arr[index] && item == arr[index].ProjectName)) {
              arr.splice(index, 0, {Count: 0, ProjectName: item, name: this.search_value})
            }
          })
          this.tableData = []
          let obj = {}
          obj.name = this.search_value
          obj.data = arr
          this.tableData.push(obj)
          this.total = 1
          // console.log('arr', this.tableData)
        }
      })
    },
    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
          patients.map(item => {
            this.patientArr.push(item.name)
          })
          // console.log('病人列表', patients)
        }
      })
    },
    getAllMobileMajorInspection () {
      getAllMobileMajorInspection().then(response => {
        var inspection = response.data.data.inspection
        // console.log('inspection', inspection)
        var a = []
        for (let i = 0; i < inspection.length; i++) {
          a.push(inspection[i])
        }
        // console.log('a', a)
        this.newArr = a
        var arr = this.arrayToObj(a)

        // console.log('arr', arr)
        this.ObjectData = arr
        this.tableName = inspection
      })
    },
    arrayToObj (arr) {
      return Object.assign({}, arr)
    },

    getMobilePatientTwo () {
      getMobilePatientTwo(this.startTime, this.endTime, this.limit, this.page).then(response => {
        if (response.data.state === 1) {
          var patientInfo = response.data.data.patientInfo
          var total = response.data.data.total
          // console.log('total', total)
          var list = response.data.data.list
          // console.log('list', list)

          var dtd = []
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < this.tableName.length; j++) {
              if (list[i].ProjectId == this.tableName[j].inspection_major) {
                dtd.push(list[i])
              }
            }
          }
          // console.log('dtd', dtd)
          var dd = {}
          for (const index in dtd) {
            if (!(dtd[index].name in dd)) {
              dd[dtd[index].name] = {}
            }
            if (!(dtd[index].ProjectId in dd[dtd[index].name]) && dtd[index].ProjectId != 0) {
              dd[dtd[index].name][dtd[index].ProjectName] = dtd[index]
            }
          }
          // console.log('ddd', dd)

          // console.log('this.ObjectData', this.ObjectData)
          for (const key in dd) {
            for (const mkey in this.ObjectData) {
              if (!(this.ObjectData[mkey].project_name in dd[key])) {
                dd[key][this.ObjectData[mkey].project_name] = {
                  ProjectName: this.ObjectData[mkey].project_name,
                  name: mkey,
                  Count: 0
                }
              }
            }
            this.tableData.push({ name: key, data: dd[key]})
          }
          // console.log('表', this.tableData)
          let projectArr = []
          this.newArr.map(item => {
            projectArr.push(item.project_name)
          })
          this.tableData.map(item => {
            let arr = Object.values(item.data)
            arr.sort((a, b) => {
              return projectArr.indexOf(a.ProjectName) - projectArr.indexOf(b.ProjectName)
            })
            item.data = arr
          })
          this.$nextTick(() => {
            this.$refs.tab.doLayout()
          })
        }
      })
    },
    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.search_value = val.name
      this.patient_id = val.id
      this.onSearch()
    }
  },
  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.getMobilePatientTwo()
    // 获取病人列表
    this.getMobilePatientList()
    // 获取检验检查项目
    this.getAllMobileMajorInspection()
  }
}
</script>

<style lang="scss" scoped>
.page_checkStatisticsAll {
   .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;
    background: #fff;
    .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: #646566;
      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: #646566;
      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.625rem 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_checkStatisticsAll {
   .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-cell__value {
    display: flex;
    align-items: center;
  }
}
</style>
