<script lang="ts" setup>
import { ref, reactive, onUnmounted, computed, nextTick, watch, onMounted } from 'vue';
import { getStoreData } from '@/utils/composition';
import {
  clearInletHistoryTemperature,
  getThermals,
  intelligentUpdate,
} from '../Info/service/system.service';
import { IAirInletTemperature, IFanInfo, IIntelSpeedAdjust, IPumpInfo } from './model/fan.datatype';
import { IconDelete, IconRefresh } from '@computing/opendesign-icons';
import {
  getAirInletTemperature,
  getFanInfo,
  getPumpInfo,
  getFanOption,
  getIntelSpeedAdjustInfo,
  initializingIntelSpeedAdjustInfo,
} from './utils/fan.utils';
import FanInfoCard from './component/FanInfoCard.vue';
import PumpInfoCard from './component/PumpInfoCard.vue';
import useStore from '@/stores';
import { setStoreData } from '@/utils/composition';
import FanHeatDissipation from './component/FanHeatDissipation.vue';
import { getGenericInfo } from '@/services/header/header.service';
import { getErrorTranslate, traduction } from '@/utils/language';
import * as echarts from 'echarts/core';
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
} from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { loading, showFailedMessage, showSuccessMessage } from '@/utils/composition';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { rangeVerification } from '@/validators/validation-functions';
import { ENERGY_PAGE_ENABLED } from '@/model/configure';

const $router = useRouter();
const route = useRoute();
const OPERATE_LOG = traduction('OPERATE_LOG');
const RUNNING_LOG = traduction('RUNNING_LOG');
const SERCURITY_LOG = traduction('SERCURITY_LOG');
// 安全配置权限
const securityConfig = checkPrivil(UserPrivil.securityConfig);

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
]);

let checkTabIndex = '1';
const all = [
  {
    index: '1',
    label: 'OPERATE_LOG',
    router: '/navigate/system/fans/fans-info',
    id: 'operationLog',
  },
  {
    index: '2',
    label: 'RUNNING_LOG',
    router: '/navigate/system/fans/fans-sensor',
    id: 'runLog',
  },
  {
    index: '3',
    label: 'SERCURITY_LOG',
    router: '/navigate/maintenance/bmc-logs/security',
    id: 'securityLog',
  },
];
let tabList = all;
let currentRoute = $router.currentRoute.value.fullPath;
const currentTabItem = tabList.find(item => {
  return item.router === currentRoute;
});
if (currentTabItem) {
  checkTabIndex = currentTabItem.index;
}

const handleSelect = (key: any) => {
  let res = tabList.find(item => {
    return item.index === key;
  });
  if (res) {
    $router.push(res.router);
  }
};

onMounted(() => {
  let path = route.fullPath.split('?');
  if(path[0] === tabList[0].router && !path[1]) {
    $router.push(tabList[0].router);
  }
});

loading(true);
const store = useStore();
const dialogRef = ref();
let airInletTemperature: IAirInletTemperature = {} as any;
const isShow = ref(false);
let timer: any;
let timerCount: number = 0;
let timerPump: any;
let timerCountPump: number = 0;
let timeout = null as any;
const refreshStatus = ref(false);
const refreshPumpStatus = ref(false);
const refreshDate = ref('');
const refreshPumpDate = ref('');
const viewPump = ref<1 | 2 | 3>(1); // 1为风扇信息，2为LAAC泵信息，3为风扇设置
const tempRefreshState = ref(false);
const fanInfoList = ref([] as IFanInfo[]);
const pumpInfoList = ref([] as IPumpInfo[]);
const dialogConfig = reactive({
  id: '',
  content: '',
  title: '',
});

const currentVal = ref();
// 获取locked锁定值
let systemLockDownEnabled = computed(() => {
  return store.state.glob.systemLocked;
});

const gridLeftAndLegendSetting = [
  {
    // 语种
    label: 'English',
    // 图表左边距
    left: '26px',
  },
  {
    label: '简体中文',
    left: '2px',
  },
  {
    label: '日本語',
    left: '2px',
  },
  {
    label: 'Français',
    left: '26px',
  },
  {
    label: 'Русский',
    left: '27px',
  },
];

const i18n = useI18n();
const langOptions = computed(() => {
  return store.state.glob.langOptions;
});
const curLang = langOptions.value.filter((lang: any) => lang.id === i18n.locale.value)[0].label;
const gridLeftSettingItem = gridLeftAndLegendSetting.find(item => item.label === curLang);

const systemTheme = computed(() => {
  return store.state.loct.systemTheme;
});
const fanInfo = computed(() => {return getStoreData('loct', 'fanInfo')}) as any;

watch(systemTheme, () => {
  initChart(airInletTemperature);
});

watch(
  fanInfo,
  () => {
    init();
  },
  { deep: true }
);
function init() {
  let path = route.fullPath.split('?');
  if (path?.[1]?.split('=')?.[1] === 'FAN_SET_TAB') {
    viewPump.value = 3;
  }
  const res = fanInfo.value;
  const airInletInfo = getAirInletTemperature(res.data);
  airInletTemperature = {
    inletTemperature: airInletInfo.inletTemperature,
    time: airInletInfo.time,
    inletTempCelsius: airInletInfo.inletTempCelsius,
  };
  fanInfoList.value = getFanInfo(res.data);
  pumpInfoList.value = getPumpInfo(res.data);
  initChart(airInletTemperature);
  tempRefreshState.value = true;
  loading(false);
};

// 绘制进风口温度图表
function initChart(airInletTemp: IAirInletTemperature) {
  const language: string = getStoreData('loct', 'locale');
  const option = getFanOption(airInletTemp.inletTemperature);
  currentVal.value = airInletTemp.inletTemperature;
  option.xAxis.data = airInletTemp.time;
  option.series[0].showSymbol = airInletTemp.time.length === 1;
  option.series[0].data = airInletTemp.inletTempCelsius;
  option.grid.left = gridLeftSettingItem?.left || '16px';
  if (language === 'ru') {
    option.yAxis.nameTextStyle.padding = [8, 0, 8, -1];
  }
  if (language === 'fr') {
    option.yAxis.nameTextStyle.padding = [8, 0, 8, -3];
  }
  isShow.value = true;
  nextTick(() => {
    const elem: HTMLElement = document.getElementById('fanChartsId') as HTMLElement;
    const myChart = echarts.init(elem);
    myChart.setOption(option);
  });
}

// 进风口温度刷新
function refresh() {
  if (tempRefreshState.value === true) {
    tempRefreshState.value = false;
    getThermals().then(
      (res: any) => {
        const airInletInfo = getAirInletTemperature(res.data);
        airInletTemperature = {
          inletTemperature: airInletInfo.inletTemperature,
          time: airInletInfo.time,
          inletTempCelsius: airInletInfo.inletTempCelsius,
        };
        initChart(airInletTemperature);
        tempRefreshState.value = true;
      },
      error => {
        tempRefreshState.value = true;
      }
    );
  }
}

// 清空进风口温度
function tempClear() {
  if (systemLockDownEnabled.value) {
    return;
  }
  dialogConfig.id = 'oneKeyConfirm';
  dialogConfig.title = traduction('COMMON_CONFIRM');
  dialogConfig.content = traduction('COMMON_ASK_OK');
  dialogRef.value.show();
}

// 清空进风口温度确认弹窗关闭
function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    clearInletHistoryTemperature().then(
      res => {
        store.state.event.setEventState({
          type: 'alertMessage',
          value: { type: 'success', message: traduction('COMMON_SUCCESS') },
        });
        timeout = setTimeout(() => {
          refresh();
        }, 2000);
      },
      error => {
        tempRefreshState.value = false;
      }
    );
  }
}

// 风扇实时刷新开关变化
function refreshStatusChange(val: boolean) {
  if (val) {
    interval();
  } else {
    clearTimer();
  }
}

// 关闭实时刷新风扇信息功能
function clearTimer(): void {
  if (timer) {
    clearInterval(timer);
  }
  timerCount = 0;
}

// 实时刷新风扇信息
function interval(): void {
  const timerCountMax = 7;
  timer = setInterval(() => {
    if (timerCount < timerCountMax) {
      timerCount++;
      getThermals().then((res: any) => {
        refreshDate.value = `${new Date().getTime()}`;
        fanInfoList.value = getFanInfo(res.data);
        timerCount--;
      });
    }
  }, 1000);
}

// LAAC泵实时刷新开关变化
function refreshPumpStatusChange(val: boolean) {
  if (val) {
    intervalPump();
  } else {
    clearPumpTimer();
  }
}

// 关闭实时刷新LAAC泵信息功能
function clearPumpTimer(): void {
  if (timerPump) {
    clearInterval(timerPump);
  }
  timerCountPump = 0;
}

// 实时刷新LAAC泵信息
function intervalPump(): void {
  const timerCountMax = 7;
  timerPump = setInterval(() => {
    if (timerCountPump < timerCountMax) {
      timerCountPump++;
      getThermals().then((res: any) => {
        refreshPumpDate.value = `${new Date().getTime()}`;
        pumpInfoList.value = getPumpInfo(res.data);
        timerCountPump--;
      });
    }
  }, 1000);
}
 
function handleUpdateFanInfo(res: any) {
  setStoreData('loct', 'fanInfo', res);
  fanInfoList.value = getFanInfo(res.data);
}
 
onUnmounted(() => {
  if (timeout !== null) {
    clearTimeout(timeout);
  }

  if (timer !== null) {
    clearTimeout(timer);
  }

  if (timerPump !== null) {
    clearTimeout(timer);
  }
});
</script>

<template>
  <div class="fanId">
    <div class="content-details" v-if="ENERGY_PAGE_ENABLED">
      <span v-t="'FAN_HEAT_TEMPERATURE_TITLE'" class="title" />
      <el-tooltip :content="$t('COMMON_REFRESH')" :teleported="false" placement="top" trigger-keys>
        <el-icon id="refresh" :size="16" class="icon icon-float icon-refresh" @click="refresh">
          <IconRefresh />
        </el-icon>
      </el-tooltip>
      <el-tooltip :content="$t('COMMON_CLEAR')" :teleported="false" placement="top" trigger-keys>
        <el-icon
          id="clear"
          v-privil.baseConfig
          :size="16"
          class="icon icon-float clear"
          :class="{ 'disabled-icon': systemLockDownEnabled }"
          @click="tempClear"
        >
          <IconDelete />
        </el-icon>
      </el-tooltip>
      <div id="currentValue">{{ currentVal }}</div>
      <div v-if="isShow" id="fanChartsId" />
    </div>
    <div class="tab">
      <span
        v-t="'FAN_INFO'"
        :class="[viewPump === 1 ? 'tabActive' : 'changeTab', ENERGY_PAGE_ENABLED ? '' : 'tabMargin']"
        @click="viewPump = 1"
      />
      <span
        v-if="pumpInfoList.length"
        v-t="'PUMP_INFO'"
        :class="[viewPump === 2 ? 'tabActive' : 'changeTab', ENERGY_PAGE_ENABLED ? '' : 'tabMargin']"
        @click="viewPump = 2"
      />
      <span
        :class="[viewPump === 3 ? 'tabActive' : 'changeTab', ENERGY_PAGE_ENABLED ? '' : 'tabMargin']"
        @click="viewPump = 3"
      >{{ $t('FAN_SET_TAB') }}</span>
    </div>
    <div class="fan-info" v-if="viewPump === 1">
      <span v-t="'FAN_INFO'" class="title" />
      <el-switch
        id="refreshSwitch"
        v-model="refreshStatus"
        class="icon-float"
        @change="refreshStatusChange"
      />
      <span v-t="'FAN_REDFRESH'" class="icon-float refresh icon-float-title"></span>
      <div class="fan-body">
        <FanInfoCard
          v-for="(fan, index) in fanInfoList"
          :id="'fan' + index"
          :key="`${fan.id}${refreshDate}`"
          :data="fan"
          :class="{ 'card-blank': (index + 1) % 4 !== 0 }"
        />
      </div>
    </div>
    <div class="fan-info" v-else-if="viewPump === 2">
      <span v-t="'PUMP_INFO'" class="title" />
      <el-switch
        id="refreshPumpSwitch"
        v-model="refreshPumpStatus"
        class="icon-float"
        @change="refreshPumpStatusChange"
        v-show="viewPump"
      />
      <span v-t="'FAN_REDFRESH'" class="icon-float refresh icon-float-title"></span>
      <div class="pump-card">
        <PumpInfoCard
          v-if="pumpInfoList.length"
          v-for="(pump, index) in pumpInfoList"
          :id="'pump' + index"
          :key="`${pump.id}${refreshPumpDate}`"
          :data="pump"
          :class="{ 'card-blank': (index + 1) % 4 !== 0 }"
        />
      </div>
    </div>
    <div class="fan-info" v-else>
      <span class="title">{{ $t('FAN_SET_TITLE') }}</span>
      <FanHeatDissipation @updateFanInfo="handleUpdateFanInfo" :fanInfoList="fanInfoList" />
    </div>
  </div>
  <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose" />
</template>

<style lang="scss" scoped>
#fanId {
  padding-right: 24px;
  .page-title {
    margin-top: 16px;
  }

  #fanChartsId {
    width: 100%;
    height: 264px;
  }

  .content-details {
    padding: 24px 24px 24px 24px;
    background: var(--o-bg-color-base);
    border-radius: 4px;
  }

  .tab {
    .changeTab {
      margin-top: 16px;
      display: inline-block;
      height: 36px;
      cursor: default;
      margin-right: 4px;
      padding: 9px 16px;
      border-radius: 1px 1px 0px 0px;
      background: var(--o-bg-color-base);
      opacity: 0.5;
    }
    .tabActive {
      position: relative;
      margin-top: 16px;
      display: inline-block;
      height: 36px;
      color: var(--o-color-primary);
      cursor: default;
      margin-right: 4px;
      padding: 9px 16px;
      border-radius: 1px 1px 0px 0px;
      background: var(--o-bg-color-base);
      &::before {
        position: absolute;
        left: 0px;
        bottom: -5px;
        content: '';
        width: 100%;
        height: 5px;
        background-color: var(--o-bg-color-base);
      }
    }
    .tabMargin {
      margin-top: 0px;
    }
  }

  .title {
    font-size: 16px;
    line-height: 24px;
    margin-top: 24px;
    font-weight: 600;
  }

  .icon-float {
    height: 16px;
    float: right;
  }

  .icon {
    color: var(--o-text-color-tertiary);
    &:hover {
      color: var(--o-color-primary-secondary);
    }
  }

  .icon-refresh {
    cursor: pointer;
  }

  .clear {
    margin-right: 8px;
    cursor: pointer;
  }

  .disabled-icon {
    cursor: not-allowed;
  }

  .fan-info {
    margin-top: 4px;
    background: var(--o-bg-color-base);
    border-radius: 4px;
    padding: 24px 24px 24px 24px;
  }

  .card-blank {
    margin-right: 16px;
    border-radius: 4px;
  }

  .icon-float-title {
    font-size: 12px;
    color: var(--o-text-color-secondary);
    line-height: 16px;
  }

  .refresh {
    margin-right: 24px;
  }

  .adjust-speed {
    display: inline-flex;
  }

  .speed-button {
    min-height: 24px;
    line-height: 1px;
  }

  .speed-mode {
    color: var(--o-text-color-primary) !important;
    text-align: center;
    font-weight: 500;
  }

  .speed-label {
    color: var(--o-text-color-tertiary);
  }

  .info {
    margin-top: 4px;
    line-height: 16px;
  }

  #currentValue {
    visibility: hidden;
  }
  #lock {
    margin-right: 0;
  }
}
#fanId {
  .tooltip-icon-float {
    height: 3px;
    width: 16px;
    background-color: #0062dc;
    display: inline-block;
    margin-bottom: 3px;
    margin-right: 8px;
  }

  .tooltip-value {
    font-size: 16px;
    color: var(--o-text-color-primary);
    text-align: right;
    line-height: 24px;
    float: right;
  }

  .tooltip-time {
    font-size: 12px;
    color: var(--o-text-color-tertiary);
    line-height: 16px;
  }

  .tooltip-icon {
    background-color: #0062dc;
    width: 16px;
    height: 3px;
    display: inline-flex;
    margin: 4px 8px 4px 0;
  }

  .tooltip-item {
    height: 24px;
  }

  .tooptip-temp {
    color: var(--o-text-color-secondary);
    font-size: 12px;
  }
}
</style>
