<template>
  <div class="page_statisticsAll">
    <div class="options">
      <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>
      <el-table :data="tableData" style="width: 100%" border :height="tableHeight" v-loadmore="loadMore" :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
        <el-table-column fixed prop="date" label="日期" width="100"></el-table-column>
        <el-table-column prop="number" :label="modeItem.name" min-width="100" v-for="(modeItem, index) in activeModes" :key="index">
          <template slot-scope="scope">
            {{ scope.row.data[modeItem.id].number ? scope.row.data[modeItem.id].number : "" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" prop="total" label="总次数" width="70"></el-table-column>
      </el-table>
    </div>

    <div>
      <van-popup v-model="stateShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="chooseState"
          @cancel="stateShow = false"
        />
      </van-popup>
      <van-popup v-model="startShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate1"
          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="currentDate2"
          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 '../components/BarChart'
import {getAllPatientsMode, getMobileTreatlist} from '@/api/common/common'
export default {
  components: {
    BarChart
  },
  data () {
    return {
      tableHeight: '',
      tableData: [],
      options: {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        xAxis: {
          data: [],
          axisLabel: {
            interval: 0,
            formatter: function (value) {
              var ret = '' // 拼接加\n返回的类目项
              var maxLength = 8 // 每项显示文字个数
              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: [],
            barGap: 50,
            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.5)'
              }
            }
          }
        ],
        dataZoom: [
          {
            // Y轴固定,让内容滚动
            type: 'slider',
            show: false,
            xAxisIndex: [0],
            start: 1,
            end: 40, // 设置X轴刻度之间的间隔(根据数据量来调整)
            zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 1,
            end: 40,
            zoomLock: true // 锁定区域禁止缩放
          }
        ]
      },
      state: '全部病人',
      stateShow: false,
      columns: ['全部病人', '留治', '转出'],
      startShow: false,
      endShow: false,
      currentDate: new Date(),
      startTime: '请选择',
      endTime: '请选择',
      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(),
      page: 1,
      limit: 20,
      total: 0,
      mode_id: 0,
      modesData: {
        xAxis: [],
        series: []
      },
      modeData: []
    }
  },
  created () {
    this.modeOptions = this.$store.getters.treatment_mode
    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.getAllPatientsMode()
    // 获取柱状图数据
    this.getlist()
  },
  computed: {
    activeModes: function () {
      var modes = []
      for (const key in this.modeOptions) {
        if (this.mode_id == key || this.mode_id == '') {
          modes.push(this.modeOptions[key])
        }
      }
      return modes
    }
  },
  methods: {
    chooseState (val) {
      this.state = val
      this.stateShow = false
      this.getAllPatientsMode()
      this.getlist()
    },
    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.getAllPatientsMode()
      this.getlist()
      this.startShow = false
    },
    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.getAllPatientsMode()
      this.getlist()
      this.endShow = false
    },
    loadMore () {
      if (!this.isStop) {
        this.isStop = true
        this.page++

        let stateType = 0
        if (this.state == '全部病人') {
          stateType = 0
        } else if (this.state == '留治') {
          stateType = 1
        } else if (this.state == '转出') {
          stateType = 2
        }
        getAllPatientsMode(this.startTime, this.endTime, stateType, this.limit, this.page, this.mode_id).then(response => {
          if (response.data.state === 1) {
            this.loading = false
            var treatinfo = response.data.data.treatinfo
            // console.log('treatinfo', treatinfo)
            var statistics = response.data.data.statistics
            // console.log('statistics', statistics)
            let dataInfo = {}
            treatinfo.forEach((item, index) => {
              let { date } = item
              if (!dataInfo[date]) {
                dataInfo[date] = {
                  date,
                  child: []
                }
              }
            })
            let list = Object.values(dataInfo)
            // console.log('list', list)
            list.map(item => {
              for (let i = 0; i < statistics.length; i++) {
                if (item.date == statistics[i].date) {
                  item.child.push(statistics[i])
                }
              }
            })
            var dtd = []
            list.map(item => {
              item.child.map(it => {
                dtd.push(it)
              })
            })
            var dd = {}
            for (const index in dtd) {
              if (!(dtd[index].date in dd)) {
                dd[dtd[index].date] = {}
              }
              if (!(dtd[index].mode_id in dd[dtd[index].date]) && dtd[index].mode_id != '0') {
                dd[dtd[index].date][dtd[index].mode_id] = dtd[index]
              }
            }
            var arr = []
            for (const key in dd) {
              var total = 0
              for (const mkey in this.modeOptions) {
                if (mkey in dd[key]) {
                  dd[key][mkey].mode = this.modeOptions[mkey].name
                  var number = parseInt(dd[key][mkey].number)
                  if (isNaN(number) || number == 0) {
                    dd[key][mkey].number = ''
                    number = 0
                  }
                  total += number
                } else {
                  dd[key][mkey] = {
                    mode: this.modeOptions[mkey].name,
                    mode_id: mkey,
                    number: 0
                  }
                }
              }
              arr.push({ date: key, data: dd[key], total: total })
            }

            // console.log('tabledate', arr)
            arr.map(item => {
              this.modeData.push(item)
            })
            this.tableData = []
            this.tableData = this.modeData
            if (response.data.data.treatinfo.length <= 0) {
              this.isStop = true
            } else {
              this.isStop = false
            }
          } else {
            this.loading = false

            this.$toast({
              message: response.msg
            })
          }
        }).catch(error => {
          this.loading = false
        })
      }
    },
    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}`
    },

    getAllPatientsMode () {
      this.loading = true
      let stateType = 0
      if (this.state == '全部病人') {
        stateType = 0
      } else if (this.state == '留治') {
        stateType = 1
      } else if (this.state == '转出') {
        stateType = 2
      }
      getAllPatientsMode(this.startTime, this.endTime, stateType, this.limit, this.page, this.mode_id).then(response => {
        if (response.data.state === 1) {
          this.loading = false
          var treatinfo = response.data.data.treatinfo
          var statistics = response.data.data.statistics
          // console.log('statistics', statistics)
          let dataInfo = {}
          treatinfo.forEach((item, index) => {
            let { date } = item
            if (!dataInfo[date]) {
              dataInfo[date] = {
                date,
                child: []
              }
            }
          })
          let list = Object.values(dataInfo)

          list.map(item => {
            for (let i = 0; i < statistics.length; i++) {
              if (item.date == statistics[i].date) {
                item.child.push(statistics[i])
              }
            }
          })
          var dtd = []
          list.map(item => {
            item.child.map(it => {
              dtd.push(it)
            })
          })
          // console.log('dtd', dtd)
          var dd = {}
          for (const index in dtd) {
            if (!(dtd[index].date in dd)) {
              dd[dtd[index].date] = {}
            }
            if (!(dtd[index].mode_id in dd[dtd[index].date]) && dtd[index].mode_id != '0') {
              dd[dtd[index].date][dtd[index].mode_id] = dtd[index]
            }
          }
          var arr = []
          for (const key in dd) {
            var total = 0
            for (const mkey in this.modeOptions) {
              if (mkey in dd[key]) {
                dd[key][mkey].mode = this.modeOptions[mkey].name
                var number = parseInt(dd[key][mkey].number)
                if (isNaN(number) || number == 0) {
                  dd[key][mkey].number = ''
                  number = 0
                }
                total += number
              } else {
                dd[key][mkey] = {
                  mode: this.modeOptions[mkey].name,
                  mode_id: mkey,
                  number: 0
                }
              }
            }
            arr.push({ date: key, data: dd[key], total: total })
          }
          this.tableData = arr
          this.modeData = arr
          // console.log('表', this.tableData)
          this.total = response.data.data.total
        } else {
          this.loading = false
        }
      })
    },
    getlist () {
      this.modesData.series = []
      this.modesData.xAxis = []
      let stateType = 0
      if (this.state == '全部病人') {
        stateType = 0
      } else if (this.state == '留治') {
        stateType = 1
      } else if (this.state == '转出') {
        stateType = 2
      }
      getMobileTreatlist(this.startTime, this.endTime, stateType).then(response => {
        if (response.data.state == 1) {
          var ttd = response.data.data.list
          var modeMap = {}
          var batotal = 0
          for (const index in ttd) {
            if (ttd[index].mode_id == '0') {
              continue
            }
            modeMap[ttd[index].mode_id] = ttd[index]
          }

          for (const key in this.modeOptions) {
            this.modesData.xAxis.push(this.modeOptions[key].name)
            if (key in modeMap) {
              this.modesData.series.push(parseInt(modeMap[key].number))
              batotal += parseInt(modeMap[key].number)
            } else {
              this.modesData.series.push(0)
            }
          }
          this.options.series[0].data = this.modesData.series
          this.options.xAxis.data = this.modesData.xAxis
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page_statisticsAll {
  .options {
    width: 31.25rem;
    display: flex;
    height: 3.125rem;
    align-items: center;
    flex-wrap: nowrap;
    overflow-x: auto;
    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 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_statisticsAll{
  .el-table td, .el-table th{
    text-align: center;
  }
}
</style>
