<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <panel-group :top-object-num="topObjectNum" />
      <el-row :gutter="20" style="margin-bottom:20px;height: calc(50vh - 174px);">
        <el-col :xs="24" :sm="24" :lg="12">
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              盘点日志
              <router-link :to="{ path: '/check/check/checkLog'}">
                <div style="position: absolute; right: 20px; top: 20px; color: #999;" class="el-icon-more" />
              </router-link>
            </h3>
            <div class="home-flowable" style="height: calc(100% - 54px); overflow-x: hidden;">
              <div class="home-tab">
                <span :class="{'home-tab-active': flowableTabIndex == 0}">未完成({{ stockLogIncompleteData.length !==0? stockLogIncompleteData.length: 0 }})</span>
                <span :class="{'home-tab-active': flowableTabIndex == 1}">已完成({{ stockLogCompletedData.length !==0? stockLogCompletedData.length: 0 }})</span>
                <!-- <span :class="{'home-tab-active': flowableTabIndex == 2}">已完成({{ flowableData.length !==0? flowableData.length: 0 }})</span>
                <span :class="{'home-tab-active': flowableTabIndex == 3}" @click="toMoreProcess">更多任务</span> -->
              </div>
              <div class="home-flowable-list" style="height: calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
                <el-table v-if="stockLogIncompleteData.length !== 0" height="calc(100%)" :data="stockLogIncompleteData" class="archives-table" stripe style="width: 100%">
                  <el-table-column prop="stockBill" label="盘点单号" />
                  <el-table-column prop="stockRegion" label="目标位置" />
                  <el-table-column prop="stockGridNum" label="目标数量" align="right">
                    <template slot-scope="scope">
                      <div>{{ scope.row.stockGridNum + ' / '+ (scope.row.totalGridNum?scope.row.totalGridNum:'0') +' 层位' }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="state" label="盘点状态" align="center">
                    <template slot-scope="scope">
                      <span v-if="scope.row.state === 0" class="row-state row-lending state-active">已终止</span>
                      <span v-if="scope.row.state === 1" class="row-state row-warehousing state-active">排队中</span>
                      <span v-if="scope.row.state === 2" class="row-state row-binding state-active">盘点中</span>
                      <span v-if="scope.row.state === 3" class="row-state row-physical state-active">已完成</span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="createTime" label="申请时间" width="180"> -->
                  <!-- <template slot-scope="scope"> -->
                  <!-- <div>{{ scope.row.createTime | parseTime }}</div> -->
                  <!-- </template> -->
                  <!-- </el-table-column> -->
                </el-table>
                <div v-else class="empty-main" style="height: 100%;">
                  <svg-icon icon-class="empty" class-name="empty-img" />
                  <p>暂无数据</p>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="12">
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              服务器监控
              <div style="position: absolute; right: 20px; top: 20px;  color: #999; cursor: pointer;" class="el-icon-refresh" @click="refreshSystemData" />
            </h3>
            <!-- <div class="chart-wrapper"> -->
            <serverProgress :system-data="systemData" />
            <!-- </div> -->
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="height:calc(50vh - 174px);">
        <el-col :xs="24" :sm="24" :lg="8">
          <!-- 档案借阅 -->
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              盘点概况
            </h3>
            <div v-if="lendData.otherData.length !== 0" class="chart-wrapper">
              <lend-across :lend-data="lendData" />
            </div>
            <div v-else class="empty-main">
              <svg-icon icon-class="empty" class-name="empty-img" />
              <p>暂无数据</p>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <!-- 档案类型 -->
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              流通统计
            </h3>
            <div class="refresh-date">2024-11-28 09:46</div>
            <div class="chart-wrapper" style="padding: 0 10px; margin-top: -10px;">
              <bookSwiper />
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <!-- 档案门类 -->
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              馆藏统计
            </h3>
            <div v-if="typeData.length !== 0" class="chart-wrapper">
              <type-pie :type-data="typeData" />
            </div>
            <div v-else class="empty-main">
              <svg-icon icon-class="empty" class-name="empty-img" />
              <p>暂无数据</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import PanelGroup from './dashboard/PanelGroup'
import lendAcross from '@/views/components/echarts/lendAcross.vue'
// import catePie from '@/views/components/echarts/catePie.vue'
import typePie from '@/views/components/echarts/typePie.vue'
import bookSwiper from '@/views/components/bookSwiper.vue'
import serverProgress from '@/views/components/echarts/serverProgress.vue'
import { FetchInitHomeInfo } from '@/api/stockTask/index'
import { FetchInitStockLogList } from '@/api/stockTaskLog/index'
import { FetchSystemInfo } from '@/api/home/cpu/index'
import { mapGetters } from 'vuex'

export default {
  name: 'Dashboard',
  components: {
    PanelGroup,
    lendAcross,
    // catePie,
    bookSwiper,
    typePie,
    serverProgress
  },
  data() {
    return {
      topObjectNum: {
        regionCount: 0,
        shelfCount: 0,
        gridCount: 0,
        deviceCount: 0
      },
      archivesTotalNum: 0,
      flowableData: [],
      flowableTabIndex: 0,
      lendData: {
        archivesTotalNum: null,
        otherData: []
      },
      cateData: [],
      typeData: [],
      addArcivesData: {
        addArcivesMaxCount: null,
        addArcivesMonth: [],
        addArcivesNum: [],
        addArcivesNumFile: []
      },
      echartsTimer: null,
      refreshtime: 10000,
      systemTimer: null,
      systemData: {
        cpuPercentage: 0,
        memPercentage: 0,
        sysFilesPercentage: 0
      },
      stockLogCompletedData: [],
      stockLogIncompleteData: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.handleMainData()
    this.getSystemInfo()
    this.getStockLog()
  },
  mounted() {
    // const _this = this
    // // 每隔一分钟刷新档案借阅和档案类型的数据
    // this.echartsTimer = setInterval(() => {
    //   _this.lendData = {
    //     archivesTotalNum: null,
    //     otherData: []
    //   }
    //   _this.cateData = []
    //   _this.typeData = []
    //   _this.addArcivesData = {
    //     addArcivesMaxCount: null,
    //     addArcivesMonth: [],
    //     addArcivesNum: [],
    //     addArcivesNumFile: []
    //   }
    //   _this.handleMainData()
    // }, this.refreshtime)

    // 服务器监控定时更新
    // this.systemTimer = setInterval(() => {
    //   _this.systemData = {
    //     cpuPercentage: 0,
    //     memPercentage: 0,
    //     sysFilesPercentage: 0
    //   }
    //   this.getSystemInfo()
    // }, 3000)
  },
  methods: {
    getSystemInfo() {
      FetchSystemInfo().then(res => {
        // cpu 占有率 （总的cpuTotal-空闲的cpuFree）/总的cpuTotal
        this.systemData.cpuPercentage = Math.round((res.cpuTotal - res.cpuFree) / res.cpuTotal * 100)

        // 内存占比  使用的memUsed/总的memTotal
        this.systemData.memPercentage = Math.round(res.memUsed / res.memTotal * 100)

        // 磁盘占比  多个磁盘  使用总和sysFiles[i].used的和/总的总和sysFiles[i].total的和
        let sysFilesTotalUsed = 0
        let sysFilesTotal = 0
        res.sysFiles.forEach(item => {
          sysFilesTotalUsed += parseFloat(item.used)
          sysFilesTotal += parseFloat(item.total)
        })
        this.systemData.sysFilesPercentage = Math.round((sysFilesTotalUsed / sysFilesTotal) * 100)
      })
    },
    refreshSystemData() {
      this.systemData = {
        cpuPercentage: 0,
        memPercentage: 0,
        sysFilesPercentage: 0
      }
      this.getSystemInfo()
    },
    getStockLog() {
      FetchInitStockLogList().then(res => {
        this.stockLogCompletedData = res.content.filter(item => [0, 3].includes(item.state))
        this.stockLogIncompleteData = res.content.filter(item => [1, 2].includes(item.state))
      })
    },
    toMoreProcess() {
      this.$router.push({ path: '/user/center?activeIndex=2' })
    },
    handleMainData() {
      // const fondsAffiliation = []
      // fondsAffiliation.push(this.user.fonds.id.toString())
      // const params = {
      //   fondsAffiliations: fondsAffiliation
      // }
      FetchInitHomeInfo().then(data => {
        this.topObjectNum = {
          regionCount: data.regionCount,
          shelfCount: data.shelfCount,
          gridCount: data.gridCount,
          deviceCount: data.deviceCount
        }
        // this.flowableData = data.flows

        // '标签', '装盒', '入库', '借阅', '开放', '实体', '审批'
        // "archivesTotalNum  总数  archivesTagNum 标签   installNum 已装盒   storageNum 入库   borrowNum 借阅  openNum  开放  entityNum 实体  approveNum 审批
        // 档案统计
        // this.lendData.archivesTotalNum = data.archivesTotalNum
        // this.lendData.otherData = [
        //   data.archivesTagNum, data.installNum, data.storageNum, data.borrowNum, data.openNum, data.entityNum, data.approveNum
        // ]

        // // 档案类别
        // let maxCount = 0
        // data.statisNumJSON.archives.forEach(archive => {
        //   if (archive.count > maxCount) {
        //     maxCount = archive.count
        //   }
        // })

        // data.statisNumJSON.singles.forEach(single => {
        //   if (single.count > maxCount) {
        //     maxCount = single.count
        //   }
        // })
        // this.addArcivesData.addArcivesMaxCount = maxCount

        // const currentDate = new Date() // 获取当前日期
        // const currentYear = currentDate.getFullYear() // 获取当前年份
        // const currentMonth = currentDate.getMonth() // 获取当前月份（从 0 到 11，所以要加 1）

        // let startYear = currentYear - 1 // 去年的年份
        // let startMonth = currentMonth + 1 // 当前月份加上 1

        // const result = [] // 存储每个年份和月份的组合
        // const xResult = []
        // while (startYear < currentYear || startMonth <= currentMonth) {
        //   xResult.push(startYear + '/' + startMonth)
        //   result.push({ year: startYear, month: startMonth, archivesCount: 0, singlesCount: 0 })
        //   // 计算下一个月份
        //   startMonth += 1
        //   if (startMonth > 12) {
        //     startYear += 1
        //     startMonth = 1
        //   }
        // }

        // result.forEach(yearMonthObj => {
        //   data.statisNumJSON.archives.forEach(archive => {
        //     if (parseInt(archive.month) === yearMonthObj.month) {
        //       yearMonthObj.archivesCount = archive.count
        //       return
        //     }
        //   })

        //   data.statisNumJSON.singles.forEach(single => {
        //     if (parseInt(single.month) === yearMonthObj.month) {
        //       yearMonthObj.singlesCount = single.count
        //       return
        //     }
        //   })
        // })

        // this.addArcivesData.addArcivesMonth = xResult
        // this.addArcivesData.addArcivesNum = result.map(function(obj) {
        //   return obj.archivesCount
        // })
        // this.addArcivesData.addArcivesNumFile = result.map(function(obj) {
        //   return obj.singlesCount
        // })

        // // 档案类型
        // for (const type in data.typeGroupBy) {
        //   if (data.typeGroupBy.hasOwnProperty(type)) {
        //     this.typeData.push({ name: type, value: data.typeGroupBy[type] })
        //   }
        // }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 20px;
  position: relative;

  .chart-wrapper {
    height: calc(100% - 55px);
  }
}
@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
.el-col {
  height: 100%;
}
.container-left,
.container-right,
.container-wrap,
.el-card,
.header-container-wrap {
  min-height: 100%;
}
.container-wrap {
  min-height: auto;
  height: 100%;
}
.home-item-title{
  position: relative;
  padding: 18px 0 18px 15px;
  font-size: 16px;
  color: #0C0E1E;
  &::before{
    position: absolute;
    left: 0;
    top: 50%;
    content: "";
    width: 3px;
    height: 16px;
    background-color: #0348F3;
    transform: translateY(-50%);
  }
}
.home-flowable{
  padding: 0 20px;
}
.home-tab{
  display: flex;
  justify-content: flex-start;
  span{
    display: block;
    margin-right: 30px;
    padding-bottom: 3px;
    border-bottom: 3px solid #fff;
    &.home-tab-active{
      color: #0348F3;
      // border-bottom: 3px solid #0348F3;
    }
  }
}
::v-deep .home-flowable-list .el-table__body-wrapper::-webkit-scrollbar {
  width: 5px !important;
  height: 5px !important;
  background-color: #DDE8FB !important;
}

::v-deep .home-flowable-list .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #4578F6 !important;
}

::v-deep .home-flowable-list .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #4578F6 !important;
}

::v-deep .home-flowable-list .el-table__body-wrapper::-webkit-scrollbar-corner {
  background-color: #DDE8FB !important;
}
.refresh-date{
  position: absolute;
  right: 14px;
  top: 10px;
  font-size: 12px;
  line-height: 30px;
}
</style>
