<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, shallowRef, useTemplateRef } from 'vue';
import { Modal } from 'ant-design-vue';

import { DeviceType } from '@/views/device-work-status/device-card';
import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { useViewVisible } from '@/hooks/view-visible';
import { t } from '@/i18n';
import { getAIOptimizeDevData, updateAIStartStopOptimize } from '@/api';
import { isNotEmptyVal } from '@/utils';

import ChillerUnitOptimize from '../device-optimize/ChillerUnitOptimize.vue';
import CoolingTowerOptimize from '../device-optimize/CoolingTowerOptimize.vue';

import type { Component } from 'vue';
import type { ColumnType } from 'ant-design-vue/es/table';
import type { AIOptimizeDevData, AIOptimizeSetItemInstance, GroupModuleInfo } from '@/types';

interface Props {
  info: GroupModuleInfo;
}

const props = defineProps<Props>();

interface OptimizeAlgorithmItem {
  algorithm: string;
  setValue?: number;
  isEnabled?: boolean;
  valuePropName: string;
  enablePropName: string;
  unit?: string;
  deviceType: DeviceType;
  modalWidth?: number;
  modalComponent?: Component;
}

const { isLoading, handleRequest } = useRequest();
const optimizeDevData = ref<AIOptimizeDevData>();
let optimizeTimer: number | undefined;

onMounted(() => {
  getOptimizeDevData();
});

onUnmounted(() => {
  optimizeDevData.value = undefined;
  clearTimeout(optimizeTimer);
});

const getOptimizeDevData = () => {
  clearTimeout(optimizeTimer);

  handleRequest(async () => {
    const groupId = props.info.groupId;
    const data = await getAIOptimizeDevData(groupId);
    optimizeDevData.value = data;
    enableChillerUnit.value = data.enableHostWaterSet;
    enableCoolingTower.value = data.enableTowerWaterSet;
    chillerUnitWaterTemp.value = data.moduleInfoAi.aiSeekHostWaterTempValue;
    coolingTowerWaterTemp.value = data.moduleInfoAi.aiSeekTowerWaterTempValue;
  });

  optimizeTimer = window.setTimeout(getOptimizeDevData, 3000);
};

const chillerUnitWaterTemp = ref<number>();
const coolingTowerWaterTemp = ref<number>();
const enableChillerUnit = ref(false);
const enableCoolingTower = ref(false);

const dataSource = computed<OptimizeAlgorithmItem[]>(() => {
  const list: OptimizeAlgorithmItem[] = [];
  const moduleInfoAi = optimizeDevData.value?.moduleInfoAi;

  if (enableChillerUnit.value) {
    list.push({
      algorithm: '冷机水温寻优',
      setValue: moduleInfoAi?.aiSeekHostWaterTempValue,
      isEnabled: moduleInfoAi?.aiSeekHostWaterTempButton,
      valuePropName: 'aiSeekHostWaterTempValue',
      enablePropName: 'aiSeekHostWaterTempButton',
      unit: '°C',
      deviceType: DeviceType.冷水主机,
      modalComponent: shallowRef(ChillerUnitOptimize),
    });
  }

  if (enableCoolingTower.value) {
    list.push({
      algorithm: '塔出水温度寻优',
      setValue: moduleInfoAi?.aiSeekTowerWaterTempValue,
      isEnabled: moduleInfoAi?.aiSeekTowerWaterTempButton,
      valuePropName: 'aiSeekTowerWaterTempValue',
      enablePropName: 'aiSeekTowerWaterTempButton',
      unit: '°C',
      deviceType: DeviceType.冷却塔,
      modalWidth: 460,
      modalComponent: shallowRef(CoolingTowerOptimize),
    });
  }

  // {
  //   algorithm: '冷冻泵寻优',
  //   setValue: 10,
  //   isEnabled: true,
  // },
  // {
  //   algorithm: '冷却泵寻优',
  //   setValue: 10,
  //   isEnabled: true,
  // },

  return list;
});

const columns = computed<ColumnType<OptimizeAlgorithmItem>[]>(() => [
  {
    title: t('realTimeMonitor.optimizationAlgorithm'),
    dataIndex: 'algorithm',
    key: 'algorithm',
  },
  {
    title: t('realTimeMonitor.setValue'),
    dataIndex: 'setValue',
    key: 'setValue',
  },
  {
    title: t('realTimeMonitor.isEnabled'),
    dataIndex: 'isEnabled',
    key: 'isEnabled',
  },
  {
    title: t('common.operation'),
    dataIndex: 'operation',
    key: 'operation',
  },
]);

const handleTempChange = (record: OptimizeAlgorithmItem, value: string | number | null) => {
  handleRequest(async () => {
    const id = optimizeDevData.value?.moduleInfoAi.id;
    const groupId = props.info.groupId;

    if (id && isNotEmptyVal(value)) {
      await updateAIStartStopOptimize({
        id,
        groupId,
        [record.valuePropName]: value,
      });
    }
  });
};

const handleSwitchClick = (record: OptimizeAlgorithmItem) => {
  const titlePrefix = record.isEnabled ? t('common.confirmClose') : t('common.confirmOpen');

  Modal.confirm({
    title: titlePrefix + record.algorithm,
    closable: true,
    centered: true,
    onOk() {
      handleRequest(async () => {
        const id = optimizeDevData.value?.moduleInfoAi.id;
        const groupId = props.info.groupId;

        if (id) {
          await updateAIStartStopOptimize({
            id,
            groupId,
            [record.enablePropName]: !record.isEnabled,
          });
        }
      });
    },
  });
};

const selectedAlgorithm = ref<OptimizeAlgorithmItem>();

const handleSettingClick = (record: OptimizeAlgorithmItem) => {
  selectedAlgorithm.value = record;
  showView();
};

const { visible, showView, hideView } = useViewVisible();
const { isLoading: isOptimizeSetLoading, handleRequest: handleOptimizeSetRequest } = useRequest();
const optimizeSetRef = useTemplateRef<AIOptimizeSetItemInstance>('optimizeSetItem');

const modalTitle = computed(() => {
  return selectedAlgorithm.value?.algorithm + t('common.settings');
});

const handleOk = () => {
  handleOptimizeSetRequest(async () => {
    await optimizeSetRef.value?.submit?.();
    hideView();
  });
};
</script>

<template>
  <div class="ai-optimize-container">
    <ATable class="ai-optimize-table" :columns="columns" :data-source="dataSource" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'algorithm'">
          <span>{{ record.algorithm }}</span>
          <span v-if="record.unit">({{ record.unit }})</span>
        </template>
        <template v-if="column.key === 'setValue'">
          <AInputNumber
            v-if="record.algorithm === '冷机水温寻优'"
            class="ai-optimize-input"
            v-model:value="chillerUnitWaterTemp"
            :disabled="record.isEnabled"
            :controls="false"
            @change="handleTempChange(record as OptimizeAlgorithmItem, $event)"
          />
          <AInputNumber
            v-else-if="record.algorithm === '塔出水温度寻优'"
            class="ai-optimize-input"
            v-model:value="coolingTowerWaterTemp"
            :disabled="record.isEnabled"
            :controls="false"
            @change="handleTempChange(record as OptimizeAlgorithmItem, $event)"
          />
        </template>
        <template v-if="column.key === 'isEnabled'">
          <ASwitch
            :checked="record.isEnabled"
            :checked-children="$t('common.on')"
            :un-checked-children="$t('common.off')"
            @click="handleSwitchClick(record as OptimizeAlgorithmItem)"
          />
        </template>
        <template v-else-if="column.key === 'operation'">
          <div class="ai-optimize-setting">
            <SvgIcon name="setting" @click="handleSettingClick(record as OptimizeAlgorithmItem)" />
          </div>
        </template>
      </template>
    </ATable>
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
    <AModal
      v-model:open="visible"
      wrap-class-name="hvac-modal ai-optimize-modal"
      :title="modalTitle"
      :width="selectedAlgorithm?.modalWidth || 920"
      centered
      destroy-on-close
      :confirm-loading="isOptimizeSetLoading"
      @ok="handleOk"
    >
      <component ref="optimizeSetItem" :is="selectedAlgorithm?.modalComponent" :group-id="info.groupId" />
    </AModal>
  </div>
</template>

<style lang="scss">
.ai-optimize-modal {
  .ant-modal-body {
    max-height: 638px;
    overflow-y: auto;
  }
}
</style>

<style lang="scss" scoped>
.ai-optimize-container {
  padding-inline: 24px;
}

:deep(.ai-optimize-table).ant-table-wrapper .ant-table {
  color: rgba(255 255 255 / 85%);
  background: transparent;

  .ant-table-thead > tr > th {
    padding: 12px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(255 255 255 / 85%);
    background: rgba(255 255 255 / 8%);
    border-bottom: none;
  }

  .ant-table-header {
    border-radius: 0;
  }

  table > thead > tr:first-child > {
    *:first-child {
      border-start-start-radius: 0;
    }

    *:last-child {
      border-start-end-radius: 0;
    }
  }

  .ant-table-thead
    > tr
    > th.ant-table-cell:not(:last-child, .ant-table-selection-column, .ant-table-row-expand-icon-cell, [colspan]) {
    &::before {
      background-color: transparent;
    }
  }

  .ant-table-tbody > tr {
    > td {
      padding-inline: 12px;
      border-top-color: rgba(255 255 255 / 8%);
    }

    &:last-child > td {
      border-bottom-color: rgba(255 255 255 / 8%);
    }

    &.ant-table-row:hover > td,
    > td.ant-table-cell-row-hover {
      background: rgba(255 255 255 / 8%);
    }
  }

  .ant-empty-normal {
    color: rgba(255 255 255 / 25%);
  }

  .ant-table-placeholder:hover > td {
    background: transparent;
  }
}

.ai-optimize-input {
  width: 96px;
  background: rgb(30 37 48 / 32%);
  border-color: rgb(255 255 255 / 24%);
  border-radius: 4px;

  :deep(.ant-input-number-input) {
    color: #fff;
  }

  &:hover,
  &:focus,
  &.ant-input-number-focused {
    border-color: var(--antd-color-primary-hover);
  }

  &.ant-input-number-disabled {
    border-color: rgb(255 255 255 / 24%);
    opacity: 0.4;
  }
}

.ai-optimize-setting {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: var(--antd-color-primary);
  cursor: pointer;
}
</style>
