<!-- eslint-disable no-prototype-builtins -->
<template>
  <div class="page-wrapper ">
    <div class="page-three">
      <div class="three-item three01">
        <div class="database-title">本年累计借阅数量</div>
        <div class="three-lending">
          <div class="three-lending-left">
            <h5>本年累计借阅</h5>
            <ul class="totalItem">
              <li
                v-for="(item, index) in yearTotal"
                :key="index"
                :class="[{'yearTotal': item.id === 'yearTotal'}]"
              >
                <div class="pageLeft-flop-box">
                  <div>
                    <span v-for="(ls, i) in item.valueArr" :key="item.id + i" :class="[{'flop-figure': !isNaN(ls)}, {'flop-comma': isNaN(ls)}]">
                      <i v-if="!isNaN(ls)">0123456789</i>
                      <!-- <span v-else>{{ ls }}</span> -->
                    </span>
                  </div>
                </div>
              </li>
            </ul>
            <YearCircle :year-all-num="yearAllNum" />
          </div>
          <div class="three-lending-right lending-ranking">
            <h5>分馆累计借阅排行榜</h5>
            <div class="ranking-cont">
              <ul class="ranking-title">
                <li style="width: 0.625rem;">排名</li>
                <li style="width: 1.5rem; text-align: left;">图书馆名称</li>
                <li style="flex:1;" />
                <li style="width: 1.25rem; padding-right: .125rem; text-align: right;">借阅数量</li>
              </ul>
              <ul class="ranking-list">
                <li v-for="(item,index) in rankingYearWithPercentage" :key="index" :class="{ 'hovered': index === currentHover }">
                  <div style="width: .625rem; color: #79B8FF;" :class="[{'ranking-num1':index===0},{'ranking-num2':index===1},{'ranking-num3':index===2}]">{{ index>=3 ? index+1 : null }}</div>
                  <div style="width: 1.5rem; text-align: left;">{{ item.name }}</div>
                  <div class="ranking-progress" style="flex:1;  align-self: center;">
                    <el-progress :percentage="item.percentage" :stroke-width="8" :show-text="false" color="#009afb" />
                  </div>
                  <div style="width: 1.25rem; padding-right: .125rem; text-align: right;">{{ item.JCC_YEAR }}<i style="padding-left:.0625rem;">本</i></div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="three-item  three02">
        <div class="database-title">今日借阅数量</div>
        <div class="three-lending">
          <div class="three-lending-left">
            <h5>今日累计借阅</h5>
            <ul class="totalItem">
              <li
                v-for="(item, index) in todayTotal"
                :key="index"
                :class="[{'todayTotal': item.id === 'todayTotal'}]"
              >
                <div class="pageLeft-flop-box">
                  <div>
                    <span v-for="(ls, i) in item.valueArr" :key="item.id + i" :class="[{'flop-figure': !isNaN(ls)}, {'flop-comma': isNaN(ls)}]">
                      <i v-if="!isNaN(ls)">0123456789</i>
                      <!-- <span v-else>{{ ls }}</span> -->
                    </span>
                  </div>
                </div>
              </li>
            </ul>
            <TodayCircle :today-all-num="todayAllNum" />
          </div>
          <div class="three-lending-right lending-ranking">
            <h5>分馆今日借阅排行榜 </h5>
            <div class="ranking-cont">
              <ul class="ranking-title">
                <li style="width: 0.625rem;">排名</li>
                <li style="width: 1.5rem; text-align: left;">图书馆名称</li>
                <li style="flex:1;" />
                <li style="width: 1.25rem; padding-right: .125rem; text-align: right;">借阅数量</li>
              </ul>
              <ul class="ranking-list">
                <li v-for="(item,index) in rankingTodayWithPercentage" :key="index" :class="{ 'hovered': index === currentHover }">
                  <div style="width: 0.625rem; color: #79B8FF;" :class="[{'ranking-num1':index===0},{'ranking-num2':index===1},{'ranking-num3':index===2}]">{{ index>=3 ? index+1 : null }}</div>
                  <div style="width: 1.5rem; text-align: left;">{{ item.name }}</div>
                  <div class="ranking-progress" style="flex:1;  align-self: center;">
                    <el-progress :percentage="item.percentage" :stroke-width="8" :show-text="false" color="#009afb" />
                  </div>
                  <div style="width: 1.25rem; padding-right: .125rem; text-align: right;">{{ item.JCC_DAY }}<i style="padding-left:.0625rem;">本</i></div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="three-item three03">
        <div class="database-title">今日借阅趋势</div>
        <div class="chart-wrapper" style="width: 11.25rem;height: calc(100% - 35px);">
          <LineChart :chart-day-data="chartDayData" />
        </div>
      </div>
      <div class="three-item three04">
        <div class="database-title">近7日借阅统计</div>
        <div class="chart-wrapper" style="width: 11.25rem;height: calc(100% - 20px);">
          <BarEcharts ref="weeklyRef" :chart-weekly-data="chartWeeklyData" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { FetchLibcodeDetails, FetchLendingTotal, FetchTodayJH, FetchWeekJH } from '@/api/library'
import LineChart from '@/components/echart/lineChart'
import BarEcharts from '@/components/echart/barEcharts'
import YearCircle from '@/components/echart/yearCircle'
import TodayCircle from '@/components/echart/todayCircle'
export default {
  name: 'PageThree',
  components: {
    LineChart,
    BarEcharts,
    YearCircle,
    TodayCircle
  },
  data() {
    return {
      currentHover: -1,
      chartDayData: {
        timeData: [],
        returnData: [],
        borrowedData: []
      },
      chartWeeklyData: {
        date: [],
        inchartWeeklyData: [],
        outchartWeeklyData: []
      },
      todayTotal: [],
      yearTotal: [],
      rankingYearData: [],
      rankingTodayData: [],
      rankingYearWithPercentage: [],
      rankingTodayWithPercentage: [],
      yearAllNum: {
        headerLib: 0,
        branchLib: 0
      },
      todayAllNum: {
        headerLib: 0,
        branchLib: 0
      },
      rankInterval: null
    }
  },
  computed: {
  },
  beforeDestroy() {
    clearInterval(this.rankInterval)
    this.rankInterval = null
  },
  created() {

  },
  activated() {
    this.getLendingTotal()
    this.getTodayJH()
    // if (this.rankingYearWithPercentage.length !== 0) {
    //   this.currentHover = -1
    //   this.rankInterval = setInterval(() => {
    //     this.currentHover = (this.currentHover + 1) % this.rankingYearWithPercentage.length
    //   }, 1000)
    // }
  },
  deactivated() {
    clearInterval(this.rankInterval)
    this.rankInterval = null
  },
  mounted() {
    // this.getLendingTotal()
    // this.getTodayJH()
    this.getWeekJH()
  },
  methods: {
    paddingNum(num, length) {
      for (var len = (num + '').length; len < length; len = num.length) {
        num = '0' + num
      }
      return num
    },
    // 获取本年今年借阅情况
    getLendingTotal() {
      this.todayTotal = []
      this.yearTotal = []
      FetchLendingTotal().then(res => {
        const result = JSON.parse(res.data)
        if (result.success & result.resultlist.length !== 0) {
          // console.log('result.resultlist', result.resultlist)
          // JCC_YEAR  本年借阅册数
          // JCC_DAY  今日借阅册数
          const dayNum = result.resultlist.filter(item => item.LIBCODE !== '999').reduce((acc, obj) => acc + obj.JCC_DAY, 0)
          const yearNum = result.resultlist.filter(item => item.LIBCODE !== '999').reduce((acc, obj) => acc + obj.JCC_YEAR, 0)
          this.todayTotal.push({
            id: 'todayTotal',
            name: '今日累计借阅',
            value: this.$parent.formatter(this.paddingNum(dayNum, 5)),
            valueArr: this.$parent.formatter(this.paddingNum(dayNum, 5)).split('')
          })
          this.yearTotal.push({
            id: 'yearTotal',
            name: '本年累计借阅',
            value: this.$parent.formatter(yearNum),
            valueArr: this.$parent.formatter(yearNum).split('')
          })

          // 总管就是QYTSG的数据，分馆就是其他除去999以为的合计
          this.yearAllNum = {
            'headerLib': result.resultlist.filter(item => item.LIBCODE === 'QYTSG')[0].JCC_YEAR,
            'branchLib': result.resultlist.filter(item => item.LIBCODE !== 'QYTSG' && item.LIBCODE !== '999').reduce((acc, obj) => acc + obj.JCC_YEAR, 0)
          }
          this.todayAllNum = {
            'headerLib': result.resultlist.filter(item => item.LIBCODE === 'QYTSG')[0].JCC_DAY,
            'branchLib': result.resultlist.filter(item => item.LIBCODE !== 'QYTSG' && item.LIBCODE !== '999').reduce((acc, obj) => acc + obj.JCC_DAY, 0)
          }

          // 排行榜显示前6的
          this.getLibcodeDetails(result.resultlist)

          this.$parent.timedRefresh(this.todayTotal, 'todayTotal')
          this.$parent.timedRefresh(this.yearTotal, 'yearTotal')

          console.log('this.todayTotal', this.todayTotal)
          console.log('this.yearTotal', this.yearTotal)
        } else {
          this.todayTotal = []
          this.yearTotal = []
        }
      }).catch(error => {
        console.error('Error', error)
      })
    },
    // 分管显示内容
    getLibcodeDetails(data) {
      FetchLibcodeDetails().then(res => {
        const result = JSON.parse(res.data)
        if (result.length !== 0) {
          const newDataArray = []
          data.forEach(item => {
            const foundItem = result.find(library => library.tcId === item.LIBCODE)
            if (foundItem) {
              const yearValue = item.JCC_YEAR || 0
              const dayValue = item.JCC_DAY || 0
              const newObj = {
                name: foundItem.name,
                JCC_YEAR: yearValue,
                JCC_DAY: dayValue
              }
              newDataArray.push(newObj)
            }
          })
          // 2. 根据JCC_YEAR的值进行降序排序
          this.rankingYearData = newDataArray.sort((a, b) => b.JCC_YEAR - a.JCC_YEAR).slice(0, 6)
          this.rankingYearWithPercentage = this.rankingDataComputed(this.rankingYearData, 'JCC_YEAR')
          // 3. 根据JCC_DAY的值进行降序排序
          this.rankingTodayData = newDataArray.sort((a, b) => b.JCC_DAY - a.JCC_DAY).slice(0, 6)
          this.rankingTodayWithPercentage = this.rankingDataComputed(this.rankingTodayData, 'JCC_DAY')

          this.rankInterval = setInterval(() => {
            this.currentHover = (this.currentHover + 1) % this.rankingYearWithPercentage.length
          }, 1000)
        }
      }).catch(error => {
        console.error('Error', error)
      })
    },
    rankingDataComputed(rankingData, numType) {
      if (!rankingData || rankingData.length === 0) {
        console.log('没有数据')
        return []
      }

      // eslint-disable-next-line no-prototype-builtins
      if (typeof rankingData[0] !== 'object' || !rankingData[0].hasOwnProperty(numType)) {
        return []
      }

      const firstPlaceNum = rankingData[0][numType] // NAN

      if (firstPlaceNum === 0) {
        // 处理除数为0的情况
        console.log('firstPlaceNum为0，不可用于被除')
        return []
      }
      return rankingData.map(item => {
        const percentage = (item[numType] / firstPlaceNum) * 100
        return { ...item, percentage }
      })
    },
    // 今日借还
    getTodayJH() {
      FetchTodayJH().then(res => {
        const result = res.data
        if (result.length !== 0) {
          this.chartDayData = {
            timeData: [],
            returnData: [],
            borrowedData: []
          }
          const time = ['07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00']
          time.forEach((hour, index) => {
            // 查找 result 中是否有对应的 logHour
            const foundItem = result.find(item => item.logHour === index + 7) // 因为 logHour 是从 7 开始，所以需要加上 7
            if (foundItem) {
              // 如果找到了对应的 logHour，则将数据加入 chartDayData
              this.chartDayData.timeData.push(`${foundItem.logHour}:00`)
              this.chartDayData.returnData.push(foundItem.hccDay)
              this.chartDayData.borrowedData.push(foundItem.jccDay)
            } else {
              // 如果没找到对应的 logHour，则将默认值加入 chartDayData
              this.chartDayData.timeData.push(`${hour}`)
              this.chartDayData.returnData.push(0) // 默认值为 0
              this.chartDayData.borrowedData.push(0) // 默认值为 0
            }
          })
        } else {
          this.chartDayData = {
            timeData: [],
            returnData: [],
            borrowedData: []
          }
        }
      }).catch(error => {
        console.error('Error', error)
      })
    },
    getWeekJH() {
      FetchWeekJH().then(res => {
        const result = res.data
        if (result.length !== 0) {
          // 获取当天日期
          const currentDate = new Date()
          const today = currentDate.toISOString().slice(0, 10)
          // 根据数据排除当天的数据
          const filteredData = result.filter(entry => {
            const entryDate = new Date(entry.createTime).toISOString().slice(0, 10)
            return entryDate !== today
          })
          // 获取过去一周的
          const pastWeekDates = []
          for (let i = 1; i <= 7; i++) {
            const date = new Date()
            date.setDate(currentDate.getDate() - i)
            pastWeekDates.push(date.toISOString().slice(0, 10))
          }

          const matchData = filteredData.reduce((accData, item) => {
            // 根据已有的数据获取相关日期
            const entryDate = new Date(item.createTime).toISOString().slice(0, 10)
            if (accData[entryDate]) {
              accData[entryDate].jccDayTotal += item.jccDayTotal
              accData[entryDate].hccDayTotal += item.hccDayTotal
            } else {
              accData[entryDate] = {
                jccDayTotal: item.jccDayTotal,
                hccDayTotal: item.hccDayTotal
              }
            }
            return accData
          }, {})

          const completeData = pastWeekDates.map(date => ({
            date: date.split('-').join('/'),
            jccDayTotal: matchData[date] ? matchData[date].jccDayTotal : 0,
            hccDayTotal: matchData[date] ? matchData[date].hccDayTotal : 0
          }))

          // 根据时间排序
          completeData.sort((a, b) => new Date(a.date) - new Date(b.date))
          // 日期X轴数据
          this.chartWeeklyData.date = completeData.map(item => item.date)
          // in 归还
          this.chartWeeklyData.inchartWeeklyData = completeData.map(item => item.hccDayTotal)
          // // out 借出
          this.chartWeeklyData.outchartWeeklyData = completeData.map(item => item.jccDayTotal)

          console.log(this.chartWeeklyData.date)
        } else {
          this.chartWeeklyData = {
            date: [],
            inchartWeeklyData: [],
            outchartWeeklyData: []
          }
        }
      }).catch(error => {
        console.error('Error', error)
      })
    }
  }
}

</script>

<style lang="scss">
@import "~@/assets/styles/index.scss";
@import "~@/assets/styles/font-some.css";

</style>
