<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useFullscreen } from '@vueuse/core';
import { Modal } from 'ant-design-vue';

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { useViewVisible } from '@/hooks/view-visible';
import { t } from '@/i18n';
import { getGroupModuleDevData, updateGroupModuleDevData } from '@/api';
import { isNotEmptyVal } from '@/utils';
import { DevParamChillerUnit, DevParamCoolingPump, DevParamCoolingTower } from '@/constants/device-params';

import { DeviceType } from '../device-work-status/device-card';

import type { EquipmentDetailsItem } from '@/types';

interface Props {
  info?: EquipmentDetailsItem;
}

const props = defineProps<Props>();

defineEmits<{
  openDevBatchExe: [];
}>();

const { visible, showView, hideView } = useViewVisible();
const { isLoading, handleRequest } = useRequest();
const deviceRealTimeData = ref<Record<string, number | string | undefined>>({});
let deviceRTDTimer: number | undefined;

const deviceType = computed(() => {
  return props.info?.deviceQueryVo.deviceType;
});

const disableStartStopCtrl = computed(() => {
  const { isLocale, isAuto, isDisable } = getDeviceStatus();
  return isLocale || isAuto || isDisable;
});

const startStopTip = computed(() => {
  const { isLocale, isAuto, isDisable } = getDeviceStatus();
  const tips: string[] = [];

  if (isLocale) {
    tips.push(t('realTimeMonitor.startStopControlTipLocal'));
  }

  if (isAuto) {
    tips.push(t('realTimeMonitor.startStopControlTipAuto'));
  }

  if (isDisable) {
    tips.push(t('realTimeMonitor.startStopControlTipDisable'));
  }

  let tipText = '';

  tips.forEach((item, index) => {
    tipText += `${index + 1}. ${item};\n`;
  });

  return tipText;
});

const getDeviceStatus = () => {
  const { localRemoteStatus, manualAutoStatus, disableEnableStatus } = deviceRealTimeData.value;

  return {
    isLocale: localRemoteStatus === '本地',
    isAuto: manualAutoStatus === 1,
    isDisable: disableEnableStatus === 0,
  };
};

watch(visible, () => {
  if (visible.value) {
    getDeviceData();
  } else {
    deviceRealTimeData.value = {};
    clearTimeout(deviceRTDTimer);
  }
});

onUnmounted(() => {
  deviceRealTimeData.value = {};
  clearTimeout(deviceRTDTimer);
});

const getDeviceData = () => {
  clearTimeout(deviceRTDTimer);

  handleRequest(async () => {
    if (!props.info?.deviceQueryVo) {
      return;
    }

    const { id, deviceType } = props.info.deviceQueryVo;
    const data = await getGroupModuleDevData(id, deviceType);

    data.dataList.forEach((item) => {
      deviceRealTimeData.value[item.dataCode] = item.value;
    });
  });

  deviceRTDTimer = window.setTimeout(getDeviceData, 3000);
};

const updateDeviceData = (paramCode: string, value?: string | number | null) => {
  handleRequest(async () => {
    if (!props.info?.deviceQueryVo) {
      return;
    }

    const { id } = props.info.deviceQueryVo;

    if (isNotEmptyVal(value)) {
      await updateGroupModuleDevData(id, paramCode, value);
    }
  });
};

const handleDisableEnableSwitch = () => {
  const { disableEnableStatus } = deviceRealTimeData.value;
  const title = disableEnableStatus ? t('common.disable') : t('common.enable');
  const value = disableEnableStatus ? 0 : 1;

  Modal.confirm({
    title: t('realTimeMonitor.confirmSwitchToMode', { mode: title }),
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData('disableEnableStatus', value);
    },
  });
};

const handleAutoManualSwitch = () => {
  const { manualAutoStatus } = deviceRealTimeData.value;
  const title = manualAutoStatus ? t('common.manual') : t('common.automatic');
  const content = manualAutoStatus
    ? t('realTimeMonitor.confirmSwitchToManualTip')
    : t('realTimeMonitor.confirmSwitchToAutoTip');
  const value = manualAutoStatus ? 0 : 1;

  Modal.confirm({
    title: t('realTimeMonitor.confirmSwitchToMode', { mode: title }),
    content,
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData('manualAutoStatus', value);
    },
  });
};

const handleStartStopSwitch = () => {
  const { startStopOrder } = deviceRealTimeData.value;
  const title = startStopOrder ? t('common.confirmClose') : t('common.confirmOpen');
  const value = startStopOrder ? 0 : 1;

  Modal.confirm({
    title: title + props.info?.deviceQueryVo.deviceName,
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData('startStopOrder', value);
    },
  });
};

const router = useRouter();
const { exit } = useFullscreen();

const goDevWorkStatus = () => {
  if (!props.info?.deviceQueryVo) {
    return;
  }

  const { id, groupId, deviceType } = props.info.deviceQueryVo;
  exit();

  router.push({
    path: `/ai-smart-ctrl/device-group/${groupId}`,
    query: {
      tab: 'deviceWorkStatus',
      deviceId: id,
      deviceType,
      r: Date.now(),
    },
  });
};

defineExpose({
  showView,
  hideView,
});
</script>

<template>
  <AModal
    v-model:open="visible"
    wrap-class-name="hvac-modal"
    :closable="false"
    :centered="true"
    :width="460"
    :footer="null"
  >
    <template #title>
      <div class="dev-ctrl-modal-header">
        <span>{{ info?.deviceQueryVo.deviceName }}</span>
        <span class="dev-ctrl-modal-operate" @click="goDevWorkStatus">
          {{ $t('common.viewMore') }}
          <SvgIcon name="right" />
        </span>
      </div>
    </template>
    <template v-if="deviceType === DeviceType.冷水主机">
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.chilledWaterOutletTemperature') }}</span>
        <span>{{ deviceRealTimeData[DevParamChillerUnit.冷冻水出水温度] ?? '-' }}℃</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.loadRate') }}</span>
        <span>{{ deviceRealTimeData[DevParamChillerUnit.负载率] ?? '-' }}%</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.activePower') }}</span>
        <span>{{ deviceRealTimeData[DevParamChillerUnit.有功功率] ?? '-' }}kW</span>
      </div>
    </template>
    <template v-if="deviceType === DeviceType.冷却塔">
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.localRemoteStatus') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingTower.本地远程状态] ?? '-' }}</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.activePower') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingTower.有功功率] ?? '-' }}kW</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.runningTime') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingTower.运行时间] ?? '-' }}{{ $t('common.hour') }}</span>
      </div>
    </template>
    <template v-if="deviceType === DeviceType.冷冻泵 || deviceType === DeviceType.冷却泵">
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.localRemoteStatus') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingPump.本地远程状态] ?? '-' }}</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.activePower') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingPump.有功功率] ?? '-' }}kW</span>
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.runningTime') }}</span>
        <span>{{ deviceRealTimeData[DevParamCoolingPump.运行时间] ?? '-' }}{{ $t('common.hour') }}</span>
      </div>
    </template>
    <div class="dev-ctrl-modal-separator"></div>
    <div class="dev-ctrl-modal-item">
      <span></span>
      <span class="dev-ctrl-modal-operate" @click="$emit('openDevBatchExe')">
        {{ $t('common.batchExecution') }}
        <SvgIcon name="right" />
      </span>
    </div>
    <div class="dev-ctrl-modal-item">
      <span>{{ $t('realTimeMonitor.enableDisable') }}</span>
      <ASwitch
        :checked="deviceRealTimeData.disableEnableStatus"
        :checked-value="1"
        :un-checked-value="0"
        @click="handleDisableEnableSwitch"
      />
    </div>
    <div class="dev-ctrl-modal-item">
      <span>{{ $t('realTimeMonitor.autoManual') }}</span>
      <ASwitch
        :checked="deviceRealTimeData.manualAutoStatus"
        :checked-value="1"
        :un-checked-value="0"
        @click="handleAutoManualSwitch"
      />
    </div>
    <div class="dev-ctrl-modal-item">
      <span>{{ $t('realTimeMonitor.startStopControl') }}</span>
      <span class="dev-ctrl-modal-start-stop-right">
        <ATooltip overlay-class-name="hvac-tooltip">
          <template #title>{{ startStopTip }}</template>
          <SvgIcon v-show="disableStartStopCtrl" name="info-cirlce-o" />
        </ATooltip>
        <ASwitch
          :checked="deviceRealTimeData.startStopOrder"
          :checked-value="1"
          :un-checked-value="0"
          :disabled="disableStartStopCtrl"
          @click="handleStartStopSwitch"
        />
      </span>
    </div>
    <template v-if="deviceType === DeviceType.冷水主机">
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.chilledWaterOutletSetValue') }}</span>
        <AInputNumber
          class="dev-ctrl-chiller-input"
          v-model:value="deviceRealTimeData[DevParamChillerUnit.冷冻水出水温度设定值]"
          :controls="false"
          @change="updateDeviceData(DevParamChillerUnit.冷冻水出水温度设定值, $event)"
        />
      </div>
      <div class="dev-ctrl-modal-item">
        <span>{{ $t('realTimeMonitor.loadRateLimitSetValue') }}</span>
        <AInputNumber
          class="dev-ctrl-chiller-input"
          v-model:value="deviceRealTimeData[DevParamChillerUnit.负载率限制设定值]"
          :controls="false"
          @change="updateDeviceData(DevParamChillerUnit.负载率限制设定值, $event)"
        />
      </div>
    </template>
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
  </AModal>
</template>

<style lang="scss" scoped>
.dev-ctrl-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dev-ctrl-modal-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 24px;

  > span {
    &:first-child {
      color: var(--antd-color-text-secondary);
    }

    &:last-child {
      color: var(--antd-color-text);
    }
  }

  > span.dev-ctrl-modal-operate {
    color: var(--antd-color-primary);
  }

  & + & {
    margin-top: 16px;
  }
}

.dev-ctrl-modal-separator {
  margin-block: 16px;
  border: 1px solid #e4e7ed;
}

.dev-ctrl-modal-operate {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: var(--antd-color-primary);
  cursor: pointer;

  i {
    margin-left: 8px;
    font-size: 12px;
  }
}

.dev-ctrl-modal-start-stop-right {
  display: flex;
  align-items: center;

  i {
    margin-right: 8px;
    font-size: 12px;
    color: #999;
  }
}

.dev-ctrl-chiller-input {
  width: 120px;
}
</style>
