<script setup lang="ts">
import { onMounted, toRefs, ref, PropType, Ref, onUnmounted, watch } from 'vue';
import { IconRefresh } from '@computing/opendesign-icons';
import { computed } from 'vue';
import useStore from '@/stores';
import { IMonitorInfo, IEChartOption } from '../../home.datatype';
import { getGenericInfo, getOverView, getThermalOverView } from '../../services/home.service';
import { OChart, OChartLayout } from '@computing/opendesign2';
import { PieChart, GaugeChart } from 'echarts/charts';
import { GridComponent, TooltipComponent } from 'echarts/components';
import { factoryMonitorInfo, getChartData } from '../../utils/monitor.util';
import { useRouter } from 'vue-router';
import { Resolution, useHome, WebStyleType } from '../../hooks/useHome';
import { getStoreData } from '@/utils/composition';

const { getResolution, getWebStyle } = useHome();
const processorSupported = computed(() => getStoreData('loct', 'processorspt'));
const memorySupported = computed(() => getStoreData('loct', 'memoriespt'));
const storageSupported = computed(() => getStoreData('loct', 'storagespt'));
const fanSupported = computed(() => getStoreData('loct', 'fanspt'));
const resolution = getResolution;
const webStyle = getWebStyle();
interface ChartElement extends Element {
  resize: () => void;
  update: (opt: any, notMerge?: boolean) => void;
}

const props = defineProps({
  data: {
    type: Object as PropType<IMonitorInfo>,
    required: true,
    default: () => {
      return {};
    },
  },
});
const { data } = toRefs(props);
const monitorData: any = data?.value;
const store = useStore();
const refreshing = ref(false);
// 获取locked锁定值
let systemLockDownEnabled = computed(() => {
  return store.state.glob.systemLocked;
});
let refreshTime = ref('');
const router = useRouter();
const chartOptions = ref(getChartData(monitorData, true, webStyle) as IEChartOption[]);
// 主题模式
const themeMode = computed(() => {
  return store.state.loct.systemTheme;
});

watch(themeMode, () => {
  chartOptions.value = getChartData(monitorData, true, webStyle) as IEChartOption[];
  drawChart();
});
watch(resolution, () => {
  chartOptions.value = getChartData(monitorData, true, webStyle) as IEChartOption[];
  drawChart();
});

let loadingData = ref(true);

const components = [PieChart, GaugeChart, GridComponent, TooltipComponent];

const diskEl: Ref<ChartElement | null> = ref(null);
const cpuEl: Ref<ChartElement | null> = ref(null);
const ramEl: Ref<ChartElement | null> = ref(null);
const tempEl: Ref<ChartElement | null> = ref(null);
const powerEl: Ref<ChartElement | null> = ref(null);
let option = ref();

const updateChart = () => {
  loadingData.value = false;

  if (diskEl.value) {
    diskEl.value?.update(chartOptions.value[0].option);
  }
  if (cpuEl.value) {
    cpuEl.value?.update(chartOptions.value[1].option);
  }
  if (ramEl.value) {
    ramEl.value?.update(chartOptions.value[2].option);
  }
  if (tempEl.value) {
    tempEl.value?.update(chartOptions.value[3].option);
  }
  if (powerEl.value) {
    powerEl.value?.update(chartOptions.value[4].option);
  }
};

function refresh() {
  if (systemLockDownEnabled.value) {
    return;
  }
  refreshing.value = true;
  loadingData.value = true;

  getOverView().then((res: any) => {
    const overviewData = res.data;
    getThermalOverView().then((rsp: any) => {
      overviewData.Summary = { ...overviewData.Summary, ...rsp.data };

      let monitorInfo: IMonitorInfo = {};
      monitorInfo.powerConsumedWatts = 500;
      monitorInfo = factoryMonitorInfo(overviewData);
      chartOptions.value = getChartData(monitorInfo, true, webStyle);
      drawChart();
    });
  });

  refreshing.value = false;
}

function drawChart() {
  updateChart();
  // 刷新时间
  getGenericInfo().then((res: any) => {
    const refreshTimeData = res.CurrentTime;
    refreshTime.value = refreshTimeData.substring(0, 19);
  });
}
function gotoPage(index: number) {
  router.push({
    path:
      chartOptions.value[index].navigatorUrl +
      (chartOptions.value[index]['routerParam'] !== undefined
        ? '/' + chartOptions.value[index]['routerParam']
        : ''),
  });
}
onMounted(() => {
  drawChart();
});
</script>

<template>
  <div class="monitor-card">
    <div class="monitor-header">
      <span v-t="'HOME_SYSTEM_MONITORING'" class="title"></span>
      <el-tooltip placement="top" :content="$t('COMMON_REFRESH')" trigger-keys>
        <span
          class="refresh-icon last-refresh-time"
          :class="{ 'icon-disabled': refreshing || systemLockDownEnabled }"
          @click="refresh"
        >
          <el-icon :size="16">
            <IconRefresh></IconRefresh>
          </el-icon>
        </span>
      </el-tooltip>
      <span id="refreshTime" class="refresh-text last-refresh-time">{{ refreshTime }}</span>
      <span
        id="getRefreshTimeBtn"
        v-t="'HOME_SYSMONITOR_LASTTIME'"
        class="refresh-text last-refresh-time"
      ></span>
    </div>
    
    <div v-if="!refreshing" class="monitor-container">
      <!-- 磁盘占用率 -->
      <div
        v-if="chartOptions[0].show && storageSupported"
        :id="chartOptions[0].id"
        class="monitor-chart"
        @click="gotoPage(0)"
      >
        <o-chart-layout v-loading="loadingData" class="chart-card">
          <o-chart
            ref="diskEl"
            class="demo-chart"
            :option="option"
            :theme="themeMode"
            :components="components"
          ></o-chart>
        </o-chart-layout>
        <div class="chart-title-box">
          <span v-t="chartOptions[0].title" class="chart-title"></span>
        </div>
      </div>
      <!-- CPU占用率 -->
      <div
        v-if="chartOptions[1].show && processorSupported.CPU"
        :id="chartOptions[1].id"
        class="monitor-chart"
        @click="gotoPage(1)"
      >
        <o-chart-layout v-loading="loadingData" class="chart-card">
          <o-chart
            ref="cpuEl"
            class="demo-chart"
            :option="option"
            :theme="themeMode"
            :components="components"
          ></o-chart>
        </o-chart-layout>
        <div class="chart-title-box">
          <span v-t="chartOptions[1].title" class="chart-title"></span>
        </div>
      </div>
      <!-- 内存占用率 -->
      <div
        v-if="chartOptions[2].show && memorySupported"
        :id="chartOptions[2].id"
        class="monitor-chart"
        @click="gotoPage(2)"
      >
        <o-chart-layout v-loading="loadingData" class="chart-card">
          <o-chart
            ref="ramEl"
            class="demo-chart"
            :option="option"
            :theme="themeMode"
            :components="components"
          ></o-chart>
        </o-chart-layout>
        <div class="chart-title-box">
          <span v-t="chartOptions[2].title" class="chart-title"></span>
        </div>
      </div>
      <!-- 进风口温度 -->
      <div
        v-if="chartOptions[3].show && fanSupported"
        :id="chartOptions[3].id"
        class="monitor-chart"
        @click="gotoPage(3)"
      >
        <o-chart-layout v-loading="loadingData" class="chart-card">
          <o-chart
            ref="tempEl"
            class="demo-chart"
            :option="option"
            :theme="themeMode"
            :components="components"
          ></o-chart>
        </o-chart-layout>
        <div class="chart-title-box">
          <span v-t="chartOptions[3].title" class="chart-title"></span>
        </div>
      </div>
      <!-- 功率-->
      <div
        v-if="chartOptions[4].show"
        :id="chartOptions[4].id"
        class="monitor-chart"
        @click="gotoPage(4)"
      >
        <o-chart-layout v-loading="loadingData" class="chart-card">
          <o-chart
            ref="powerEl"
            class="demo-chart"
            :option="option"
            :theme="themeMode"
            :components="components"
          ></o-chart>
        </o-chart-layout>
        <div class="chart-title-box">
          <span v-t="chartOptions[4].title" class="chart-title"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.monitor-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .monitor-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .title {
      font-size: 16px;
      font-weight: bold;
      color: var(--o-text-color-primary);
    }
    
    .last-refresh-time {
      font-size: 12px;
      text-align: right;
      color: var(--o-text-color-secondary);
      display: flex;
      align-items: center;
      gap: 4px;
    }
    
    .refresh-icon {
      display: flex;
      border: 1px solid var(--o-border-color-lighter);
      border-radius: 2px;
      width: fit-content;
      cursor: pointer;
      &:hover {
        border: 1px solid var(--o-color-primary-secondary);
        .el-icon {
          color: var(--o-color-primary-secondary);
        }
      }
      .el-icon {
        color: var(--o-text-color-tertiary);
        margin: 4px;
      }
    }
    
    .refresh-text {
      margin-top: 4px;
    }
    
    .icon-disabled,
    .icon-disabled:hover {
      cursor: not-allowed;
      .el-icon {
        color: var(--o-color-placeholder) !important;
      }
      border-color: var(--o-color-placeholder) !important;
    }
  }
  
  .monitor-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    flex: 1;
    overflow-y: auto;
    padding-right: 4px;
  }
  
  .monitor-chart {
    flex: 1 1 calc(50% - 10px); // 每行两个图表
    min-width: 120px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: #f8f9fa;
    border-radius: 6px;
    padding: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }

    :deep(canvas),
    .chart-title {
      cursor: pointer;
    }
  }
}

.chart-card {
  width: 100%;
  margin: auto;
  max-width: 100%;
  padding: 12px 4px 0px 4px !important;
}
.demo-chart {
  width: 100%;
  height: 150px;
}

.chart-title {
  top: -12px;
  position: relative;
  font-size: 14px;
  color: var(--o-text-color-primary);
  line-height: 20px;
  width: 100%;
}

.chart-title-box {
  width: 100%;
  position: relative;
  .chart-title-temp {
    top: -32px;
    left: 0px;
    position: absolute;
    font-size: 13px;
    color: #4e5865;
    text-align: center;
    line-height: 20px;
    width: 100%;
  }
  .chart-title {
    top: -12px;
    position: relative;
    font-size: 14px;
    color: var(--o-text-color-primary);
    line-height: 20px;
    width: 100%;
  }
}
</style>
