<template>
  <div class="app-container home" style="overflow: auto">
    <el-row :gutter="15">
      <el-col :sm="24" :lg="12" style="padding-left: 15px; padding-bottom: 10px">
        <el-card>
          <template #header>
            <div class="flex items-center justify-between">
              <h2>常用功能</h2>
              <el-button type="primary" link @click="handleSetting">
                <template #icon>
                  <el-icon :size="30" color="red"><Setting /></el-icon>
                </template>
              </el-button>
            </div>
          </template>
          <div v-if="selectedMenus.length > 0" class="h-45 text-center">
            <div class="menu-container">
              <div v-for="(item, index) in selectedMenus" :key="index" @click="clickDiv(item)">
                <img :src="'/src/assets/icons/svg/' + item.icon + '.svg'" />
                <br />
                <span>{{ item.menuName }}</span>
              </div>
            </div>
          </div>
          <div v-else class="h-45 text-center flex items-center justify-center">
            <span>请点击右上方按钮，添加常用功能模块！</span>
          </div>
        </el-card>
      </el-col>

      <el-col :sm="24" :lg="12" style="padding-left: 15px; padding-bottom: 10px">
        <el-card>
          <template #header><h2>我的一卡通</h2></template>
          <div class="h-45 text-center flex items-center justify-center leading-7">
            <img class="w-150px h-150px mr-10px" :src="baseUrl + userStore.avatar" @error="$event.target.src = defaultPhoto" />
            <div class="text-left">
              <p>
                学/工号：<span style="color: #1c87bb">{{ userStore.userNumb }}</span>
                <br />
                用户名：<span style="color: #1c87bb">{{ userStore.nickname }}</span>
                <br />
                主部门：<span style="color: #1c87bb">{{ deptName }}</span>
                <br />
                主岗位：<span style="color: #1c87bb">{{ postName }}</span>
                <br />
                余额：<span style="color: #1c87bb">￥</span><span style="color: #1c87bb">{{ accountBalance }}</span>
                <br />
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :sm="24" :lg="12" style="padding-left: 15px">
        <el-card class="h-100">
          <template #header><h2>服务器资源占用</h2></template>
          <div class="pt-8 h-95" style="overflow-y: auto; overflow-x: hidden">
            <el-row :gutter="15">
              <el-col :sm="24" :lg="12">
                <div id="cpu" ref="cpu" class="h-75"></div>
              </el-col>
              <el-col :sm="24" :lg="12">
                <div id="mem" ref="mem" class="h-75"></div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <el-col :sm="24" :lg="12" style="padding-left: 15px">
        <el-card class="h-100" style="overflow-y: auto">
          <template #header><h2>消费充值数据</h2></template>
          <div class="h-70" style="overflow-y: auto; overflow-x: hidden">
            <el-tabs>
              <el-tab-pane label="消费">
                <el-table
                  v-loading="consumptionLoading"
                  :data="consumptionList"
                  height="205"
                  border
                  :row-style="{ 'height': '35px' }"
                  :cell-style="{ 'padding': '0px', 'height': '30px' }"
                >
                  <el-table-column label="消费时间" align="center" header-align="center" prop="consumeDate" show-overflow-tooltip />
                  <el-table-column label="消费金额" align="center" header-align="center" prop="consumeMoney" show-overflow-tooltip width="100" />
                  <el-table-column label="设备机号" align="center" header-align="center" prop="termNo" width="100" />
                  <el-table-column label="设备名称" align="left" header-align="center" prop="termName" show-overflow-tooltip />
                  <el-table-column label="卡上余额" align="center" header-align="center" prop="cardValue" show-overflow-tooltip width="100" />
                  <template #empty>
                    <!-- 自定义没有数据时的显示 -->
                    <p style="color: #303133">暂无消费数据...</p>
                  </template>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="充值/补贴">
                <el-table
                  v-loading="rechargeLoading"
                  :data="rechargeList"
                  height="205"
                  border
                  :row-style="{ 'height': '35px' }"
                  :cell-style="{ 'padding': '0px', 'height': '30px' }"
                >
                  <el-table-column label="充值时间" align="center" header-align="center" prop="creditTime" show-overflow-tooltip />
                  <el-table-column label="充值/补贴金额" align="center" header-align="center" prop="receiptMoney" show-overflow-tooltip />
                  <el-table-column label="收支类型" align="center" header-align="center" prop="creditType" show-overflow-tooltip>
                    <template #default="scope">
                      <dict-tag :options="CREDITTYPE" :value="scope.row.creditType" />
                    </template>
                  </el-table-column>
                  <el-table-column label="卡上余额" align="center" header-align="center" prop="cardValue" show-overflow-tooltip />
                  <template #empty>
                    <!-- 自定义没有数据时的显示 -->
                    <p style="color: #303133">暂无充值/补贴数据...</p>
                  </template>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider />
    <SelectUsedMenu ref="menuSetting" @close="refreshSetting"></SelectUsedMenu>
    <CopyrightIcp></CopyrightIcp>
  </div>
</template>

<script setup name="Index" lang="ts">
import SelectUsedMenu from '@/components/SelectUsedMenu/index.vue';
import defaultPhoto from '@/assets/images/defaultPhoto.jpg';
import { Setting } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import CopyrightIcp from '@/components/copyright-icp.vue';
import useUserStore from '@/store/modules/user';
import { monitorServer } from '@/api/monitor/server';
import Decimal from 'decimal.js';
import { getDept } from '@/api/system/dept';
import { getPost } from '@/api/system/params/post';
import { selectAccountBalanceByIds } from '@/api/payment/bag';
import { listXfConsumedetail } from '@/api/consumption/report/xfConsumedetail';
import { listXfCreditaccount } from '@/api/cardCenter/report/xfCreditaccount';
import { getSelectedMenu } from '@/api/system/menu';
import { MenuVO } from '@/api/system/menu/types';
import router from '@/router';
/* const goTarget = (url: string) => {
  window.open(url, '__blank');
};
 */
type EChartsOption = echarts.EChartsOption;

const consumptionLoading = ref(false);

const rechargeLoading = ref(false);

const consumptionList = ref([]);
const rechargeList = ref([]);

const userStore = useUserStore();

const postName = ref('');
const deptName = ref('');
const accountBalance = ref('0');
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { CREDITTYPE } = toRefs<any>(proxy?.useDict('CREDITTYPE'));
const menuSetting = ref();
const selectedMenus = ref([]);
const handleSetting = () => {
  menuSetting.value.open('dddd');
};

onMounted(() => {
  initCpu();
  initMem();
  monitorServer().then((res) => {
    // console.log(res);
    if (res.data) {
      const onhandrad = new Decimal(100);
      cpuUsed.value = onhandrad.minus(new Decimal(res.data.cpu.free)).toNumber();
      cpuUnUsed.value = res.data.cpu.free;

      memUsed.value = res.data.mem.usage;
      memUnUsed.value = onhandrad.minus(new Decimal(res.data.mem.usage)).toNumber();
      option.series[0].data = [
        { value: cpuUnUsed.value, name: 'CPU空闲率' },
        { value: cpuUsed.value, name: 'CPU使用率' }
      ];
      optionMeM.series[0].data = [
        { value: memUnUsed.value, name: '内存空闲率' },
        { value: memUsed.value, name: '内存使用率' }
      ];
      myChart.setOption(option);
      myChartMem.setOption(optionMeM);
    }
  });
  // initCpu();
  // initMem();
  window.addEventListener('resize', () => {
    myChart.resize();
    myChartMem.resize();
  });

  // 主岗位
  getPost(userStore.postId).then((res) => {
    postName.value = res.data.postName;
  });
  // 主部门
  getDept(userStore.deptId).then((res) => {
    deptName.value = res.data.deptName;
  });
  // 余额
  selectAccountBalanceByIds({ userIds: userStore.userId }).then((res) => {
    if (res.data) {
      accountBalance.value = res.data;
    }
  });

  // 消费列表
  listXfConsumedetail({ userId: userStore.userId, pageNum: 1, pageSize: 10 }).then((res) => {
    if (res.rows) {
      consumptionList.value = res.rows;
    }
  });
  // 充值列表
  listXfCreditaccount({ userId: userStore.userId, pageNum: 1, pageSize: 10 }).then((res) => {
    if (res.rows) {
      rechargeList.value = res.rows;
    }
  });
  // 已选择的菜单
  getSelectedMenus();
  /* getSelectedMenu().then((res) => {
    if (res.data) {
      selectedMenus.value = res.data;
    }
  }); */
});

const getSelectedMenus = () => {
  getSelectedMenu().then((res) => {
    if (res.data) {
      selectedMenus.value = res.data;
    }
  });
};

const clickDiv = (item: MenuVO) => {
  console.log('点击了菜单', item.routePath);
  router.push({ path: item.routePath });
};

onUnmounted(() => {
  // 销毁echarts实例
  if (window.document.getElementById('cpu')) {
    echarts.dispose(window.document.getElementById('cpu')!);
  }
  if (window.document.getElementById('mem')) {
    echarts.dispose(window.document.getElementById('mem')!);
  }
  window.removeEventListener('resize', () => {
    myChart.resize();
    myChartMem.resize();
  });
});

const refreshSetting = () => {
  // console.log('刷新设置');
  getSelectedMenus();
};

let option: EChartsOption;

let cpuUsed = ref(0);
let cpuUnUsed = ref(0);

option = {
  title: {
    text: 'CPU',
    subtext: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: 'CPU Data',
      type: 'pie',
      radius: '50%',
      data: [
        { value: cpuUsed.value, name: 'CPU空闲率' },
        { value: cpuUnUsed.value, name: 'CPU使用率' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ],
  color: ['#9fe080', '#ff7070', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
};

let optionMeM: EChartsOption;

let memUsed = ref(0);
let memUnUsed = ref(0);

optionMeM = {
  title: {
    text: '内存',
    subtext: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '内存',
      type: 'pie',
      radius: '50%',
      data: [
        { value: memUsed.value, name: '内存空闲率' },
        { value: memUnUsed.value, name: '内存使用率' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 5,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ],
  color: ['#5c7bd9', '#ffdc60', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
};

let myChart = null;
function initCpu() {
  let chartDom = null;
  chartDom = window.document.getElementById('cpu')!;
  myChart = echarts.init(chartDom);
  option && myChart.setOption(option);
}

let myChartMem = null;
function initMem() {
  let chartDomMem = window.document.getElementById('mem')!;
  myChartMem = echarts.init(chartDomMem);
  optionMeM && myChartMem.setOption(optionMeM);
}
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 20px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: 'open sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 15px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.el-table--large .cell {
  padding: 0 0.3125rem !important;
}

:deep(.el-table__header-wrapper > table.el-table__header tr th div.cell) {
  padding: 0 0.3125rem !important;
}

:deep(.el-table__header-wrapper > table.el-table__header tr th.el-table__cell) {
  padding: 0.3125rem 0 !important;
}

:deep(div.el-card > div.el-card__header) {
}

:deep(div.el-card > div.el-card__body) {
}

.menu-container img {
  width: 50px;
  height: 50px;
}

div.menu-container {
  padding-left: 20px;
  height: 200px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-start;
  gap: 15px;
  overflow: auto;
}

div.menu-container div {
  cursor: pointer;
  text-align: center;
}

div.menu-container div:hover {
  color: blue;
}
</style>
