<script lang="ts" setup>
import {useMainLayoutStore} from "~/strores/UseMainLayoutStore";
import VChart from "vue-echarts";
import dayjs from "dayjs";
import {useDataStore} from "~/strores/DataStore";

const mainLayoutStore = useMainLayoutStore()
type CpuInfo = {
  field: string,
  data: string
}
const lsCpu = ref<CpuInfo[]>([])
const dataStore = useDataStore()
const colorMode = useColorMode()
const getSystemInfo = () => {
  $fetch(`/Api/Server/GetServerCpuInfo`, {
    method: 'GET',
    responseType: "json",
    params: {
      serverId: mainLayoutStore.SelectServer.id
    },
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${useCookie('token').value}`
    },
    baseURL: useRuntimeConfig().public.baseUrl
  }).then((res) => {
    const data = res as any
    //转换json
    lsCpu.value = data['lscpu']
    console.log(data)
  })
}
onMounted(() => {
  getSystemInfo();
})
watch(() => mainLayoutStore.SelectServer, () => {
  getSystemInfo();
})
const values = ref<(number | null)[]>([...Array.from({length: 61}, (_, index) => null)])
const hoursValue = ref<(number | null)[]>([...Array.from({length: 61}, (_, index) => null)])
const dayValue = ref<(number | null)[]>([...Array.from({length: 13}, (_, index) => null)])
const option = computed(() => {
  return {
    animation: false,
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: values.value.length}, (_, index) => dayjs().add(-index, 's').toString()),
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    grid: {
      left: '0',
      right: '0',
      bottom: '0',
      top: '0',
      show: true,
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      splitNumber: 10,
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    series: [
      {
        data: values.value,
        color: ['#0167d7'],
        type: 'line',
        areaStyle: {}
      }
    ],
  }
})
const optionHours = computed(() => {
  return {
    animation: false,
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: hoursValue.value.length}, (_, index) => dayjs().add(-index, 'h').toString()),
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    grid: {
      left: '0',
      right: '0',
      bottom: '0',
      top: '0',
      show: true,
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      splitNumber: 10,
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    series: [
      {
        data: hoursValue.value,
        color: ['#0167d7'],
        type: 'line',
        areaStyle: {}
      }
    ],
  }
})
const optionDay = computed(() => {
  return {
    animation: false,
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: dayValue.value.length}, (_, index) => dayjs().add(-index, 'h').toString()),
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    grid: {
      left: '0',
      right: '0',
      bottom: '0',
      top: '0',
      show: true,
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      splitNumber: 10,
      splitLine: {
        show: true,
        lineStyle: {
          color: ['rgba(0,115,244,0.3)'],
          width: 2,
          type: 'solid'
        }
      }
    },
    series: [
      {
        data: dayValue.value,
        color: ['#0167d7'],
        type: 'line',
        areaStyle: {}
      }
    ],
  }
})
let Interval: NodeJS.Timeout
let IntervalHours: NodeJS.Timeout
let IntervalRefresh: NodeJS.Timeout
let minutesTemp: number[] = []
onMounted(() => {
  nextTick(() => {
    Interval = setInterval(() => {
      let data: number = Number(dataStore.data["CpuTotalUsage"])
      //随机抖动-5,+5
      const jitter = Math.random() * 2 - 1
      data = Number((data + jitter).toFixed(2))
      values.value.push(data)
      minutesTemp.push(data)
      values.value.shift()
    }, 1000)
    IntervalHours = setInterval(() => {
      //data为minutesTemp的均值
      let data: number = minutesTemp.reduce((a, b) => a + b, 0) / minutesTemp.length
      data = Number((data).toFixed(2))
      hoursValue.value.push(data)
      values.value.shift()
    }, 60000)
    IntervalRefresh = setInterval(() => {
      getHistoryData()
    }, 600000)
  })

})
watch(() => mainLayoutStore.SelectServer.id, () => {
  values.value = [...Array.from({length: 61}, (_, index) => null)]
  getHistoryData()
})
onBeforeUnmount(() => {
  clearInterval(Interval)
  clearInterval(IntervalHours)
})
const getHistoryData = () => {
  values.value = dataStore.dataHistory.data["CpuTotalUsage"].slice(-60).map(x => Number(x))
  setTimeout(() => {
    $fetch('/Api/Server/GetServerHistoryStep', {
      method: 'GET',
      params: {
        ServerId: mainLayoutStore.SelectServer.id,
        DataType: 'CpuTotalUsage',
        timeRange: '1h'
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${useCookie('token').value}`
      },
      baseURL: useRuntimeConfig().public.baseUrl
    }).then((res: any) => {
      hoursValue.value = res.data
    })
  }, 1000)
  setTimeout(() => {
    $fetch('/Api/Server/GetServerHistoryStep', {
      method: 'GET',
      params: {
        ServerId: mainLayoutStore.SelectServer.id,
        DataType: 'CpuTotalUsage',
        timeRange: '1d'
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${useCookie('token').value}`
      },
      baseURL: useRuntimeConfig().public.baseUrl
    }).then((res: any) => {
      dayValue.value = res.data
    })
  }, 2000)
}
onBeforeMount(() => {
  getHistoryData()
})

</script>

<template>
  <div class="cpu-layout">
    <div class="left-chart">
      <div class="cpu-title">
        <h1>CPU</h1>
        <h2>{{ lsCpu.find(x => x.field === 'Model name:')?.data }}</h2>
      </div>
      <div class="cpu-chart-top">
        <p>使用率</p>
        <p>100%</p>
      </div>
      <div class="cpu-chart">
        <v-chart
            :option="option"
            autoresize
            class="chart"/>
      </div>
      <div class="cpu-chat-bottom">
        <p>1分钟</p>
        <p>0</p>
      </div>
      <div class="cpu-chart-top">
        <p>使用率</p>
        <p>100%</p>
      </div>
      <div class="cpu-chart">
        <v-chart
            :option="optionHours"
            autoresize
            class="chart"/>
      </div>
      <div class="cpu-chat-bottom">
        <p>1小时</p>
        <p>0</p>
      </div>
      <div class="cpu-chart-top">
        <p>使用率</p>
        <p>100%</p>
      </div>
      <div class="cpu-chart">
        <v-chart
            :option="optionDay"
            autoresize
            class="chart"/>
      </div>
      <div class="cpu-chat-bottom">
        <p>1天</p>
        <p>0</p>
      </div>
    </div>
    <div class="right-info">
      <div class="info-title-box">
        <div class="info-title">
          <p>使用率</p>
          <h2>{{ Number(dataStore.data["CpuTotalUsage"]).toFixed(2) }}%</h2>
        </div>
        <div class="info-title">
          <p>速度</p>
          <h2>{{ (Number(dataStore.data["CpuTotalSpeed"]) / 1000).toFixed(2) }}GHZ</h2>
        </div>
        <div class="info-title">
          <p>进程</p>
          <h2>{{ Number(dataStore.data["ProcessTotalCount"]) }}</h2>
        </div>
        <div class="info-title">
          <p>线程</p>
          <h2>{{ Number(dataStore.data["ThreadsTotalCount"]) }}</h2>
        </div>
        <div class="info-title">
          <p>句柄</p>
          <h2>{{ Number(dataStore.data["PhrasePatternCount"]) }}</h2>
        </div>
      </div>
      <div class="other-info-box">
        <div v-for="info in lsCpu" class="other-info">
          <p>{{ info.field }}</p>
          <p>{{ info.data }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "base";

.cpu-layout {
  padding: $padding*1.5;
  display: grid;
  grid-template-columns: 1fr 300px;
  grid-template-rows: 1fr;
  gap: $gap*2;
}

.left-chart {
  display: flex;
  flex-direction: column;
  gap: $gap;

  .cpu-title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .dark-mode & {
      h1, h2 {
        color: $dark-text-color;
      }
    }

    h1, h2 {
      color: $light-text-color;
    }

    h1 {
      font-size: 32px;
    }
  }
}

.cpu-chart-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cpu-chart {
  flex: 1;
  border: 4px solid #0073f4;
  border-radius: $radius*2;
  height: min-content;
  max-height: 32rem;
  min-height: 24rem;
  overflow: hidden;
}

.cpu-chat-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-title-box {
  display: flex;
  flex-wrap: wrap;
  gap: $gap*2;

  .info-title {
    display: flex;
    flex-direction: column;
    gap: $gap*.5;
  }

  .info-title:nth-of-type(2) {
    width: 60%;
  }
}

.other-info-box {
  display: flex;
  flex-direction: column;
  gap: $gap*.5;

  .other-info {
    display: flex;
    gap: $gap;

    p:first-of-type {
      font-weight: 500;
    }

    p {
      flex: 1;
    }
  }
}

.right-info {
  display: flex;
  flex-direction: column;
  gap: $gap*2;
}
</style>