<template>
  <div class="dashboard-editor-container">
    <!-- <github-corner class="github-corner" /> -->

    <!--  <panel-group @handleSetLineChartData="handleSetLineChartData" />-->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfixs">
            <span>memory</span>
          </div>
          <instruChart style="height: 350px" :percentage="currentPercentage" />
        </el-card>
      </el-col>
      <el-col style="margin-bottom: 20px" :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfixs">
            <span>GPU使用率</span>
          </div>
          <LineChart :data="chartData" style="height: 350px"></LineChart>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfixs header_sel">
            <span>知识库构成</span>
            <div>
              <el-select
                v-model="kenValue"
                @change="kenChange"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in kenList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <!-- <LineChart :data="chartData" style="height: 350px"></LineChart> -->
          <BarChart :kenValue="kenVal" style="height: 350px"></BarChart>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfixs">
            <span>文件种类占比</span>
          </div>
          <pie-chart style="height: 366px" />
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfixs">
            <span>知识库热门标签</span>
          </div>
          <TagCloud :tags="tags" />
        </el-card>
      </el-col> -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfixs">
            <span>最近访问的文件</span>
          </div>
          <RecentFile style="height: 350px" />
        </el-card>
      </el-col>
    </el-row>

    <!--   <transaction-table /> -->
  </div>
</template>

<script>
import GithubCorner from "@/components/GithubCorner";
import PanelGroup from "./components/PanelGroup";
import LineChart from "./components/LineChart";
import RaddarChart from "./components/RaddarChart";
import PieChart from "./components/PieChart";
import BarChart from "./components/BarChart";
import TransactionTable from "./components/TransactionTable";
import TodoList from "./components/TodoList";
import BoxCard from "./components/BoxCard";
import TagCloud from "./components/tagCloud.vue";
import RecentFile from "./components/recentFile.vue";
import instruChart from "./components/instruChart.vue";
import {
  listBuckets,
  structure_count,
  GET_Rbq,
  gpu_info,
} from "@/api/knowledge";
import { mapState } from "vuex";

const lineChartData = {
  newVisitis: {
    expectedData: [100, 120, 161, 134, 105, 160, 165],
    actualData: [120, 82, 91, 154, 162, 140, 145],
  },
  messages: {
    expectedData: [200, 192, 120, 144, 160, 130, 140],
    actualData: [180, 160, 151, 106, 145, 150, 130],
  },
  purchases: {
    expectedData: [80, 100, 121, 104, 105, 90, 100],
    actualData: [120, 90, 100, 138, 142, 130, 130],
  },
  shoppings: {
    expectedData: [130, 140, 141, 142, 145, 150, 160],
    actualData: [120, 82, 91, 154, 162, 140, 130],
  },
};

export default {
  name: "DashboardAdmin",
  components: {
    GithubCorner,
    PanelGroup,
    LineChart,
    RaddarChart,
    PieChart,
    BarChart,
    TransactionTable,
    TodoList,
    BoxCard,
    TagCloud,
    RecentFile,
    instruChart,
  },
  data() {
    return {
      lineChartData: lineChartData.newVisitis,
      tags: [
        "Figma",
        "Adobe XD",
        "PSD Editor",
        "Employer",
        "Online Jobs",
        "Remote Work",
        "Salary",
        "Tips",
        "Income",
        "Develop",
        "App",
        "Digital",
        "Marketing",
        "CEO",
      ],
      kenList: [],
      kenValue: null,
      kenVal: {},
      currentPercentage: 11,
      refreshInterval: null,
      isOnDashboard: false,
      ws: null, // WebSocket 实例
      chartData: {},
    };
  },
  computed: {
    ...mapState({
      route: (state) => state.tagsView.visitedViews,
    }),
  },
  watch: {
    $route: {
      immediate: true,
      handler(newRoute) {
        this.isOnDashboard = newRoute.path === "/dashboard";
        this.handleRouteChange();
      },
    },
  },
  mounted() {
    this.init();
    /*  this.startRefreshInterval(); */
  },
  beforeDestroy() {
    this.stopRefreshInterval();
    this.closeWebSocket(); // 组件销毁前关闭 WebSocket
  },
  methods: {
    handleRouteChange() {
      if (this.isOnDashboard) {
        this.refreshData();
        this.initWebSocket();// 初始化 WebSocket
      } else {
        this.closeWebSocket();
      }
    },
    /* 选择知识库 */
    kenChange(val) {
      this.kenVal = this.kenList.find((el) => el.id === val);
    },
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type];
    },
    startRefreshInterval() {
      this.refreshInterval = setInterval(() => {
        this.refreshData();
      }, 30000); // 30 seconds
    },

    stopRefreshInterval() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
      }
    },

    refreshData() {
      structure_count().then((res) => {
        if (res.status !== 200) return;
        this.kenList = res.data;
        if (this.kenList.length > 0) {
          this.kenValue = this.kenList[0].id;
          this.kenVal = this.kenList[0];
        }
      });
      /* GET_Rbq().then((res) => {
        console.log(res);
      }); */
      /* gpu_info().then((res) => {
        const total = res.data.data.cpu.memory.total;
        const used = res.data.data.cpu.memory.used;
        this.currentPercentage = Number((used / total).toFixed(2));
      }); */
    },

    init() {
      this.refreshData();
    },
    initWebSocket() {
      // 获取基础 API 地址并替换 http/https 为 ws/wss
      const wsUrl = process.env.VUE_APP_BASE_API.replace(/^http/, "ws");
      // 创建 WebSocket 连接
      this.ws = new WebSocket(`${wsUrl}/ws/monitoring`);

      // 连接成功回调
      this.ws.onopen = () => {
        console.log("WebSocket连接成功");
      };

      // 接收消息回调
      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log(data);
          // 检查数据结构是否完整
          if (
            data &&
            data.data &&
            data.data.system &&
            data.data.system.cpu &&
            data.data.system.cpu.memory
          ) {
            // 更新图表数据
            this.chartData = data;
            const total = data.data.system.cpu.memory.total;
            const used = data.data.system.cpu.memory.used;
            this.currentPercentage = Number((used / total).toFixed(2)) * 100;
          } else {
            console.warn("Received incomplete data structure:", data);
          }
        } catch (error) {
          console.error("Error processing WebSocket message:", error);
        }
      };

      // 连接关闭回调
      this.ws.onclose = () => {
        console.log("WebSocket连接关闭");
      };

      // 连接错误回调
      this.ws.onerror = (error) => {
        console.error("WebSocket连接错误:", error);
      };
    },

    closeWebSocket() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  min-height: 100%;
  /*   background-color: rgb(240, 242, 245); */
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }
  .clearfixs {
    span {
      font-size: 16px;
      font-weight: 600;
    }
  }
  .header_sel {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
  ::v-deep .el-card__body {
    padding-top: 0;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
