<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">
              公文传阅
              <div style="position: absolute; right: 20px; top: 0; display: flex; justify-content: flex-end; align-items: center;">
                <el-checkbox v-model="isOriginal" @change="handleOriginalChange">仅显示原件</el-checkbox>
                <span v-if="miodTableData.length !== 0" style=" display: block; line-height: 54px; font-weight: normal; color: rgb(153, 153, 153); margin-left: 10px;"><i class="el-icon-receiving" style="margin-right: 6px;" />{{ miodTableData.length }}</span>
              </div>
            </h3>
            <div class="home-flowable" style="height: calc(100% - 54px); overflow-x: hidden;">
              <!-- <div class="home-tab">
                <span :class="{'home-tab-active': flowableTabIndex == 0}">待处理({{ flowableData.length !==0? flowableData.length: 0 }})</span>
                <span :class="{'home-tab-active': flowableTabIndex == 1}" @click="toMoreProcess">更多流程</span>
              </div> -->
              <div class="home-flowable-list" style="height: calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
                <el-table v-if="miodTableData.length !== 0" height="calc(100%)" :data="miodTableData" stripe style="width: 100%" :show-header="false" @cell-dblclick="tableDoubleClick">
                  <el-table-column prop="title" label="标题" width="450" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>[{{ scope.row.reg_no }}] - {{ scope.row.borrow_name }} - {{ scope.row.maintitle }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="latest_time" label="申请时间" width="180">
                    <template slot-scope="scope">
                      <div>{{ scope.row.latest_time }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="100" align="right">
                    <template slot-scope="scope">
                      <div>
                        <span v-if="scope.row.status==='逾期'" class="row-state cancel-state">{{ scope.row.status }}</span>
                        <span v-if="scope.row.status==='即将到期'" class="row-state soon-state">{{ scope.row.status }}</span>
                        <span v-if="scope.row.status==='传阅中'" class="row-state end-state">{{ scope.row.status }}</span>
                      </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">
              办理时限提醒
              <span v-if="remindData.length !== 0" style="position: absolute; right: 20px; top: 0; display: block; line-height: 54px; font-weight: normal; color: rgb(153, 153, 153);"><i class="el-icon-receiving" style="margin-right: 6px;" />{{ remindData.length }}</span>
            </h3>
            <!-- <serverProgress :system-data="systemData" /> -->
            <div class="home-flowable" style="height: calc(100% - 54px); overflow-x: hidden;">
              <div class="home-flowable-list" style="height: calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
                <el-table v-if="remindData.length !== 0" height="calc(100%)" :data="remindData" stripe style="width: 100%" :show-header="false" @cell-dblclick="tableDoubleClick">
                  <el-table-column prop="title" label="标题" min-width="450" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>[{{ scope.row.reg_no }}] - {{ scope.row.maintitle }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="latest_time" label="申请时间" width="180" align="right">
                    <template slot-scope="scope">
                      <div>{{ scope.row.latest_time }}</div>
                    </template>
                  </el-table-column>
                <!-- <el-table-column prop="status" label="状态" width="100" align="right">
                  <template slot-scope="scope">
                    <div>
                      <span v-if="scope.row.status==='逾期'" class="row-state cancel-state">{{ scope.row.status }}</span>
                      <span v-if="scope.row.status==='即将到期'" class="row-state soon-state">{{ scope.row.status }}</span>
                      <span v-if="scope.row.status==='传阅中'" class="row-state end-state">{{ scope.row.status }}</span>
                    </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-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="12">
          <!-- 档案类型 -->
          <div class="container-wrap">
            <span class="right-top-line" />
            <span class="left-bottom-line" />
            <h3 class="home-item-title">
              公文新增
            </h3>
            <div class="chart-wrapper">
              <cate-pie :add-arcives-data="addArcivesData" />
            </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">
              公文统计
            </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>

    <MidoArchivesInfo ref="archivesInfo" :is-mido-record="true" :parent-info="parentInfo" :page-type="pageType" />
  </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 serverProgress from '@/views/components/echarts/serverProgress.vue'
import { FetchInitStatisBase, FetchDocumentTypeByTime, FetchDocumentByDocDepartment, FetchHomeBorrowLog, FetchHomeRemindHandle } from '@/api/system/documentArchives'
import { FetchSystemInfo } from '@/api/home/cpu/index'
import { mapGetters } from 'vuex'
import MidoArchivesInfo from '@/views/archivesMIOD/miodLibrary/module/detail'

export default {
  name: 'Dashboard',
  components: {
    PanelGroup,
    // lendAcross,
    catePie,
    typePie,
    MidoArchivesInfo
    // serverProgress
  },
  data() {
    return {
      topObjectNum: {
        documentTotal: 0,
        notCirculate: 0,
        circulateing: 0,
        circulated: 0
      },
      archivesTotalNum: 0,
      miodTableData: [],
      flowableTabIndex: 0,
      lendData: {
        archivesTotalNum: null,
        otherData: []
      },
      cateData: [],
      typeData: [],
      addArcivesData: {
        addArcivesMaxCount: null,
        addArcivesMonth: [],
        addArcivesNum: []
      },
      echartsTimer: null,
      refreshtime: 10000,
      systemTimer: null,
      systemData: {
        cpuPercentage: 0,
        memPercentage: 0,
        sysFilesPercentage: 0
      },
      remindData: [],
      parentInfo: null,
      pageType: 'miodRecord',
      isOriginal: true
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.getTopData()
    this.getHomeBorrowLog()
    this.getHomeRemindHandle()
    this.getSystemInfo()
    this.getDocumentTypeByTime()
    this.getDocumentByDocDepartment()
  },
  mounted() {
    // const _this = this
    // // 每隔一分钟刷新档案借阅和档案类型的数据
    // this.echartsTimer = setInterval(() => {
    //   _this.lendData = {
    //     archivesTotalNum: null,
    //     otherData: []
    //   }
    //   _this.cateData = []
    //   _this.typeData = []
    //   _this.addArcivesData = {
    //     addArcivesMaxCount: null,
    //     addArcivesMonth: [],
    //     addArcivesNum: [],
    //     addArcivesNumFile: []
    //   }
    // }, this.refreshtime)

    // 服务器监控定时更新
    // this.systemTimer = setInterval(() => {
    //   _this.systemData = {
    //     cpuPercentage: 0,
    //     memPercentage: 0,
    //     sysFilesPercentage: 0
    //   }
    //   this.getSystemInfo()
    // }, 3000)
  },
  methods: {
    handleOriginalChange() {
      this.getHomeBorrowLog()
    },
    getHomeBorrowLog() {
      // detailsType  null全部 1.原件 2.复印件
      const param = {
        'detailsType': this.isOriginal ? 1 : null
      }
      FetchHomeBorrowLog(param).then(res => {
        if (res && Array.isArray(res)) {
          this.miodTableData = res
        } else {
          this.miodTableData = []
        }
      })
    },
    getHomeRemindHandle() {
      FetchHomeRemindHandle().then(res => {
        if (res && Array.isArray(res)) {
          this.remindData = res.map(item => {
            return {
              reg_no: item[0],
              maintitle: item[1],
              latest_time: item[2],
              document_id: item[3],
              parents_id: item[4]
            }
          })
        } else {
          this.remindData = []
        }
      })
    },
    tableDoubleClick(row) {
      console.log('row', row)
      this.parentInfo = row
      this.$nextTick(() => {
        this.$refs.archivesInfo.archivesInfoVisible = true
        this.$refs.archivesInfo.archivesTabIndex = 0
        this.$refs.archivesInfo.getDetial()
      })
    },
    getSystemInfo() {
      FetchSystemInfo().then(res => {
        console.log('res', res)
        if (res && Object.keys(res).length) {
          // cpu 占有率 （总的cpuTotal-空闲的cpuFree）/总的cpuTotal
          // cpuSy cpu使用率 cpuFree cpu空闲率
          // this.systemData.cpuPercentage = Math.round((res.cpuTotal - res.cpuFree) / res.cpuTotal * 100)
          this.systemData.cpuPercentage = Math.round(res.cpuSy / (res.cpuSy + res.cpuFree) * 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)
        } else {
          this.systemData = {
            cpuPercentage: 0,
            memPercentage: 0,
            sysFilesPercentage: 0
          }
        }
      })
    },
    toMoreProcess() {
      this.$router.push({ path: '/user/center?activeIndex=2' })
    },
    getTopData() {
      FetchInitStatisBase().then(data => {
        this.topObjectNum = {
          notCirculate: data.notCirculate, // 未传阅数量
          documentTotal: data.documentTotal, // 公文总数
          circulateing: data.circulateing, // 传阅中
          circulated: data.circulated // 已完成
        }
      })
    },
    getDocumentTypeByTime() {
      FetchDocumentTypeByTime().then(data => {
        let maxCount = 0
        data.forEach(archive => {
          if (archive.count > maxCount) {
            maxCount = archive.count
          }
        })

        this.addArcivesData.addArcivesMaxCount = maxCount

        // 获取当前日期信息
        const currentDate = new Date()
        const currentYear = currentDate.getFullYear()
        const currentMonth = currentDate.getMonth() + 1 // 月份从1开始

        // 生成包含本月的近12个月数据
        const result = [] // 存储完整月份数据
        const xResult = [] // 存储x轴标签

        for (let i = 11; i >= 0; i--) {
          // 计算当前循环的年月（从当前月向前推i个月）
          let year = currentYear
          let month = currentMonth - i

          // 调整年月，如果月份小于等于0，减少年份并调整月份
          while (month <= 0) {
            month += 12
            year -= 1
          }

          // 格式化月份为两位数字
          const formattedMonth = month.toString().padStart(2, '0')

          // 添加到x轴标签
          xResult.push(`${year}/${month}`)

          // 查找对应月份的数据（假设数据结构包含year和month字段）
          const found = data.find(archive =>
            archive.month === formattedMonth && (archive.year === undefined || parseInt(archive.year) === year)
          )

          // 添加到结果数组，有数据则使用，没有则为0
          result.push({
            year,
            month,
            archivesCount: found ? found.count : 0,
            singlesCount: 0
          })
        }

        // 更新数据
        this.addArcivesData.addArcivesMonth = xResult
        this.addArcivesData.addArcivesNum = result.map(obj => obj.archivesCount)
      })
    },
    getDocumentByDocDepartment() {
      FetchDocumentByDocDepartment().then(data => {
        this.typeData = data.map(item => ({
          name: item.docDepartment,
          value: item.count
        }))
      })
    }

  }
}
</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;
    cursor: pointer;
    &.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;
}
</style>
