<template>
  <div class="containerCount">
    <div class="showEach">
      <ul v-loading="parameterLoading" class="ovfd">
        <li>
          <h5>发布数据集数量</h5>
          <h4>{{ countList.getDataSetNumber }}</h4>
          <p>今日新增：{{ countList.todayDataSetNumber }}</p>
        </li>
        <li>
          <h5>发布文件数量</h5>
          <h4>{{ countList.getFileInfoNumber }}</h4>
          <p>今日新增：{{ countList.todayFileInfoNumber }}</p>
        </li>
        <li>
          <h5>发布文件体量</h5>
          <h4>{{ formatFileSize(countList.getPublishDataVolume) }}</h4>
          <p>今日新增：{{ countList.todayPublishDataVolume }}</p>
        </li>
        <li>
          <h5>下载量</h5>
          <h4>{{ countList.getDownLoadCountOfDataSet }}</h4>
          <p>今日新增：{{ countList.todayDownLoadCountOfDataSet }}</p>
        </li>
        <li>
          <h5>访问量</h5>
          <h4>{{ countList.getVisitInfoNumber }}</h4>
          <p>今日新增：{{ countList.todayVisitInfoNumber }}</p>
        </li>
      </ul>
    </div>
    <div class="con-content ovfd">
      <div class="ovfd">
        <div class="tabTurn">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="下载量" name="downloads" />
            <el-tab-pane label="访问量" name="views" />
          </el-tabs>
          <!-- <ul>
							<li>Downloads</li>
							<li>Views</li>
						</ul> -->
        </div>
        <div class="dateBox">
          <div class="block">
            <span class="demonstration" />
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="StartDate"
              end-placeholder="EndDate"
              unlink-panels
            />
          </div>
        </div>
      </div>
      <div style="width:100%;height:aoto;">
        <div v-loading="topLoading" class="countRight">
          <div v-if="activeName=='downloads'">
            <p>下载总体量 &nbsp;&nbsp;{{ formatFileSize(downLoadSum) }} &nbsp;&nbsp;&nbsp;下载总次数 &nbsp;&nbsp; {{ downloadCount }}</p>
            <!-- <p>下载排名(top 5)</p> -->
          </div>
          <div v-else>
            <p>访问总量 &nbsp;&nbsp;{{ visitCount }}</p>
            <!-- <p>访问排名(top 5)</p> -->
          </div>
          <!-- <ul>
            <li v-for="(item,index) in topList" :key="index" @click="handleDetail(item.datasetId)">
              <h3 class="turnLink">{{ item.dataNameCN }}</h3>
              <h4>{{ item.total }}</h4>
            </li>
          </ul> -->
        </div>
        <div class="countLeft">
          <div id="echartsDraw" style="width: 100%; height: 700px;" />
        </div>

      </div>

    </div>
  </div>
</template>
<script>
import {
  countTotal,
  statisticsByMonth,
  getTopData
} from '@/api/releaseCount'
import {
  getToken,
  getUser,
  getUserID
} from '@/utils/auth' // get token from cookie
export default {
  name: 'ReleaseCount',
  components: {},
  props: {},
  data() {
    return {
      topLoading: false,
      activeName: 'downloads',
      dateRange: null,
      parameterLoading: false,
      loading: false,
      startDate: null,
      endDate: null,
      downLoadInfoList: [],
      topList: [],
      countList: {
        getBurstEventNumber: 0,
        getDataSetNumber: 0,
        getFileInfoNumber: 0,
        getPublishDataVolume: 0,
        getTrigEventNumber: 0,
        getVisitInfoNumber: 0,
        getdownLoadCountOfDataSet: 0,
        todayDataSetNumber: 0,
        todayDownLoadCountOfDataSet: 0,
        todayFileInfoNumber: 0,
        todayPublishDataVolume: 0,
        todayVisitInfoNumber: 0
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      downLoadMonth: [],
      viewMonth: [],
      sizeList: [],
      downLoadSum: 0,
      downloadCount: 0,
      visitCount: 0
    }
  },
  watch: {
    dateRange(newValue) {
      if (newValue && newValue.length) {
        // debugger
        if (newValue[0] && typeof (newValue[0]) !== 'string') {
          this.startDate = this.time(newValue[0])
        }
        if (newValue[1] && typeof (newValue[1]) !== 'string') {
          this.endDate = this.time(newValue[1])
        }

        this.handleClick()
      } else {
        this.startDate = null
        this.endDate = null
      }
    }
  },
  created() {},
  mounted() {
    this.endDate = this.time(new Date(), 'lastMonth')
    this.startDate = this.time(new Date(), 'lastYear')
    this.dateRange = [this.startDate, this.endDate]
    console.log(this.startDate, this.endDate)
    this.handleClick()
    this.getCount()
  },
  methods: {
    formatFileSize(limit) {
      var size = ''
      if (!limit) {
        return '0B'
      }
      if (limit < 0.1 * 1024) { // 小于0.1KB，则转化成B
        size = limit.toFixed(2) + 'B'
      } else if (limit < 0.1 * 1024 * 1024) { // 小于0.1MB，则转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
      } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 小于0.1GB，则转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
      } else { // 其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }

      var sizeStr = size + '' // 转成字符串
      var index = sizeStr.indexOf('.') // 获取小数点处的索引
      var dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
      // eslint-disable-next-line eqeqeq
      if (dou == '00') { // 判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size
    },
    // 获取统计列表
    async getCount() {
      const _this = this
      this.parameterLoading = true
      const data = {
        webInfo: window.sessionStorage.getItem('webInfo')
      }
      try {
        const res = await countTotal(data)
        if (res.data) {
          _this.countList = JSON.parse(JSON.stringify(res.data))
          console.log(_this.countList)
          // this.countList.getDownLoadCountOfDataSet=res.data.getDownLoadCountOfDataSet
        }
      } catch (error) {
        console.log(error)
      }
      this.parameterLoading = false
    },
    async init(data) {
      this.topLoading = true
      try {
        const res = await getTopData(data)
        if (res.downLoadInfoList) {
          this.topList = res.downLoadInfoList
          this.downLoadSum = res.downLoadSum
          this.downloadCount = res.downloadCount
        } else if (res.visitInfoList) {
          this.topList = res.visitInfoList
          this.visitCount = res.visitCount
          // this.topList = []
          // this.downLoadSum = 0
          // this.downloadCount = 0
        }
        this.topLoading = false
      } catch (error) {
        console.log(error)
        this.topLoading = false
      }
    },
    handleDetail(datasetId) {
      const jsid = getToken()
      const cu = getUser()
      const userID = getUserID()
      // this.$router.push({name:"baseDetail",query:{dataSetName:row.dataSetName,userID:window.sessionStorage.getItem("userID")}})
      window.open(process.env.VUE_APP_BASE_API_FRONT + '?jsessionid=' + jsid + '&cu=' + cu + '&userId=' + userID + '#/container/dataSetDetail' + '?datasetId=' + datasetId)
    },
    // 传入一个需要排序的数组
    MsgSort(obj) {
      obj.sort((a, b) => {
        const t1 = new Date(Date.parse(a.date.replace(/-/g, '/')))
        const t2 = new Date(Date.parse(b.date.replace(/-/g, '/')))
        return t1.getTime() - t2.getTime()
      })
      return obj
    },
    async handleClick() {
      this.loading = true
      const countList = []; const sizeList = []; const downLoadMonth = []; const viewMonth = []
      if (this.activeName === 'downloads') {
        const data = {
          startTime: this.startDate,
          endTime: this.endDate,
          webInfo: window.sessionStorage.getItem('webInfo'),
          statisticsFlag: 'downLoad'
        }
        this.init(data)
        try {
          const res = await statisticsByMonth(data)
          if (res) {
            const array = []
            let obj = {}; let arrary1 = []
            for (const a in res) {
              obj = {}
              obj.date = a
              obj.downSum = res[a].downSum
              obj.downloadCount = res[a].downloadCount
              array.push(obj)
            }
            arrary1 = this.MsgSort(array)
            arrary1.map(item => {
              downLoadMonth.push(item.date)
              countList.push(item.downloadCount)
              sizeList.push(item.downSum)
            })

            // this.downLoadInfoList = res
            // res.data.map(item => {
            //   downLoadMonth.push(item.time)
            //   countList.push(item.count)
            //   sizeList.push(item.size)
            // })

            const myChart = this.$echarts.init(
              document.getElementById('echartsDraw')
            )
            const option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  crossStyle: {
                    color: '#999'
                  }
                }
              },
              toolbox: {
                feature: {
                  // dataView: { show: true, readOnly: false },
                  // magicType: { show: true, type: ["line", "bar"] },
                  // restore: { show: true },
                  // saveAsImage: { show: true },
                }
              },
              // legend: {
              //   data: ['蒸发量', '平均温度']
              // },
              xAxis: [
                {
                  type: 'category',
                  data: downLoadMonth,
                  axisPointer: {
                    type: 'shadow'
                  }
                }
              ],
              yAxis: [
                {
                  type: 'value',
                  name: '下载趋势',
                  min: 0,
                  max: 250,
                  interval: 50,
                  axisLabel: {
                    // formatter: "{value} ml",
                    formatter: '{value}'
                  }
                },
                {
                  type: 'value',
                  name: 'MB',
                  min: 0,
                  max: 25,
                  interval: 5,
                  axisLabel: {
                    // formatter: "{value} °C",
                    formatter: '{value}'
                  }
                }
              ],
              dataZoom: [{
                show: true
              }],
              series: [
                {
                  // name: "蒸发量",
                  type: 'bar',
                  data: countList
                },
                {
                  // name: "平均温度",
                  type: 'line',
                  yAxisIndex: 1,
                  data: sizeList
                }
              ]
            }
            myChart.setOption(option, true)
          }
        } catch (error) {
          console.log(error)
        }
        this.loading = false
      } else {
        const data = {
          startTime: this.startDate,
          endTime: this.endDate,
          webInfo: window.sessionStorage.getItem('webInfo'),
          statisticsFlag: 'visit'
        }
        this.init(data)
        try {
          const res = await statisticsByMonth(data)
          if (res) {
            const array = []
            let obj = {}; let arrary1 = []
            for (const a in res) {
              obj = {}
              obj.date = a
              obj.visitCount = res[a].visitCount
              array.push(obj)
            }
            arrary1 = this.MsgSort(array)
            arrary1.map(item => {
              viewMonth.push(item.date)
              countList.push(item.visitCount)
            })
            const myChart = this.$echarts.init(
              document.getElementById('echartsDraw')
            )
            const option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  crossStyle: {
                    color: '#999'
                  }
                }
              },
              xAxis: {
                type: 'category',
                data: viewMonth
              },
              yAxis:
                  [
                    {
                      type: 'value',
                      name: '访问趋势',
                      min: 0,
                      max: 250,
                      interval: 50,
                      axisLabel: {
                        // formatter: "{value} ml",
                        formatter: '{value}'
                      }
                    }
                  ],
              dataZoom: [{
                show: true
              }],
              series: [
                {
                  data: countList,
                  type: 'line',
                  smooth: true
                }
              ]
            }
            myChart.setOption(option, true)
          }
        } catch (error) {
          console.log(error)
        }
        this.loading = false
      }
    },
    time(date, value) {
      var y, m
      // if(value=='lastMonth'){
      //   m = date.getMonth()
      // }else{
      //   m = date.getMonth() + 1;
      // }
      m = date.getMonth() + 1
      if (value === 'lastYear') {
        y = date.getFullYear() - 1
      } else {
        y = date.getFullYear()
      }

      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      var h = date.getHours()
      h = h < 10 ? '0' + h : h
      var minute = date.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      var second = date.getSeconds()
      second = second < 10 ? '0' + second : second
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
    },
    getLastYearYestdy(date) {
      let datastr = ''
      var strYear = date.getFullYear() - 1
      var strDay = date.getDate()
      var strMonth = date.getMonth() + 1
      if (strMonth < 10) {
        strMonth = '0' + strMonth
      }
      if (strDay < 10) {
        strDay = '0' + strDay
      }
      datastr = strYear + '-' + strMonth + '-' + strDay
      return datastr
    }
  }
}
</script>
<style scoped>
  .countLeft{
    /* float:left; */
    width:100%;
    overflow:hidden;
  }
  .countRight{
    /* float:right;
    width:30%; */
      width:100%;
    padding-right:5%;
    padding-top:2%;
  }
  .countRight p{
    /* padding-bottom:8%; */
  }
  .countRight li{
    height:40px;
    overflow: hidden;
    width:100%;

  }
  .countRight h3{
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    float:left;
    width:70%;
    font-size:16px;
    font-weight: normal;
  }
  .countRight h4{
    float:right;
    font-size:16px;
    font-weight: normal;
  }
  .con-content .tabTurn {
    float: left;
    width: 60%;
    padding-right: 5%;
    margin-top: 12px;
}
.con-content .dateBox {
    float: left;
    width: 32%;
    padding-top: 10px;
}
.con-content {
    background: #fff;
}
</style>>

