<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
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 { getGroupModuleDevStatus, updateGroupModuleDevData } from '@/api';

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

import StartStopTip from './StartStopTip.vue';

import type { SegmentedBaseOption } from 'ant-design-vue/es/segmented/src/segmented';
import type { GroupBatchDeviceItem, IconObject } from '@/types';

interface Props {
  groupId: number;
}

const props = defineProps<Props>();

const { visible, showView, hideView } = useViewVisible();
const { isLoading, handleRequest } = useRequest();
const devicesStatus = ref<Record<number, GroupBatchDeviceItem[] | undefined>>({});
let devicesStatusTimer: number | undefined;

watch(visible, () => {
  if (visible.value) {
    getAllDeviceStatus();
  } else {
    devicesStatus.value = {};
    clearTimeout(devicesStatusTimer);
  }
});

onUnmounted(() => {
  devicesStatus.value = {};
  clearTimeout(devicesStatusTimer);
});

const getAllDeviceStatus = () => {
  clearTimeout(devicesStatusTimer);

  handleRequest(async () => {
    const data = await getGroupModuleDevStatus(props.groupId);

    data.forEach((item) => {
      devicesStatus.value[item.deviceType] = item.deviceDataList;
    });
  });

  devicesStatusTimer = window.setTimeout(getAllDeviceStatus, 3000);
};

const activeKey = ref('manualStartStop');
const activeType = ref([DeviceType.冷水主机, DeviceType.冷却塔, DeviceType.冷冻泵, DeviceType.冷却泵]);

const isStartStop = computed(() => {
  return activeKey.value === 'manualStartStop';
});

interface DeviceTypeGroupItem {
  name: string;
  icon: IconObject;
  type: DeviceType.冷水主机 | DeviceType.冷却塔 | DeviceType.冷冻泵 | DeviceType.冷却泵;
  list: GroupBatchDeviceItem[];
}

const deviceTypeGroups = computed<DeviceTypeGroupItem[]>(() => {
  return [
    {
      name: t('common.chilledWaterUnit'),
      icon: {
        name: 'chiller-unit',
        size: 21,
      },
      type: DeviceType.冷水主机,
      list: devicesStatus.value[DeviceType.冷水主机] || [],
    },
    {
      name: t('common.coolingTower'),
      icon: {
        name: 'cooling-tower',
        size: 23,
      },
      type: DeviceType.冷却塔,
      list: devicesStatus.value[DeviceType.冷却塔] || [],
    },
    {
      name: t('common.chilledWaterPump'),
      icon: {
        name: 'cooling-pump',
        size: 20,
      },
      type: DeviceType.冷冻泵,
      list: devicesStatus.value[DeviceType.冷冻泵] || [],
    },
    {
      name: t('common.coolingPump'),
      icon: {
        name: 'cooling-pump',
        size: 20,
      },
      type: DeviceType.冷却泵,
      list: devicesStatus.value[DeviceType.冷却泵] || [],
    },
  ];
});

interface ManualAutoTypeItem extends SegmentedBaseOption {
  value: GroupBatchDeviceItem['manualAutoStatus'];
  payload: {
    title: string;
    confirmTip: string;
  };
}

const manualAutoTypes = computed<ManualAutoTypeItem[]>(() => {
  return [
    {
      value: 1,
      payload: {
        title: t('common.automatic'),
        confirmTip: t('realTimeMonitor.confirmSwitchToAutoTip'),
      },
    },
    {
      value: 0,
      payload: {
        title: t('common.manual'),
        confirmTip: t('realTimeMonitor.confirmSwitchToManualTip'),
      },
    },
  ];
});

const handleManualAutoClick = (option: ManualAutoTypeItem, device: GroupBatchDeviceItem) => {
  if (option.disabled || option.value === device.manualAutoStatus) {
    return;
  }

  Modal.confirm({
    title: t('realTimeMonitor.confirmSwitchStartStop', {
      name: device.deviceName,
      status: option.payload.title,
    }),
    content: option.payload.confirmTip,
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData(device.deviceId, 'manualAutoStatus', option.value);
    },
  });
};

const handleDisableEnableSwitch = (device: GroupBatchDeviceItem) => {
  const content = device.disableEnableStatus
    ? t('realTimeMonitor.confirmDeviceDisable')
    : t('realTimeMonitor.confirmDeviceEnable');
  const value = device.disableEnableStatus ? 0 : 1;

  Modal.confirm({
    title: t('realTimeMonitor.deviceStartStop'),
    content,
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData(device.deviceId, 'disableEnableStatus', value);
    },
  });
};

const handleStartStopSwitch = (device: GroupBatchDeviceItem) => {
  const content = device.startStopOrder ? t('common.confirmClose') : t('common.confirmOpen');
  const value = device.startStopOrder ? 0 : 1;

  Modal.confirm({
    title: t('realTimeMonitor.manualStartStop'),
    content: content + device.deviceName,
    closable: true,
    centered: true,
    onOk() {
      updateDeviceData(device.deviceId, 'startStopOrder', value);
    },
  });
};

const updateDeviceData = (deviceId: number, paramCode: string, value: number) => {
  handleRequest(async () => {
    await updateGroupModuleDevData(deviceId, paramCode, value);
  });
};

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

<template>
  <AModal
    v-model:open="visible"
    wrap-class-name="hvac-modal device-batch-modal"
    :centered="true"
    :width="920"
    @ok="hideView"
  >
    <template #title>
      <ATabs class="button-tabs-compact device-batch-tabs" v-model:active-key="activeKey" type="card">
        <ATabPane key="manualStartStop" :tab="$t('realTimeMonitor.manualStartStop')" />
        <ATabPane key="enableDisable" :tab="$t('realTimeMonitor.enableDisable')" />
      </ATabs>
    </template>
    <ACollapse
      class="device-batch-collapse"
      v-model:active-key="activeType"
      expand-icon-position="end"
      :bordered="false"
      ghost
    >
      <ACollapsePanel v-for="item in deviceTypeGroups" :key="item.type" :show-arrow="false">
        <template #header>
          <span class="device-batch-item-header">
            <SvgIcon v-bind="item.icon" />
            <span>{{ item.name }}</span>
          </span>
        </template>
        <div class="device-batch-list-item" v-for="device in item.list" :key="device.deviceId">
          <span
            v-show="isStartStop"
            :class="[
              'status-dot',
              'device-batch-list-status',
              {
                'status-dot-green': device.runningStatus === 1,
              },
            ]"
          ></span>
          <div :class="['device-batch-list-name', { 'flex-1': !isStartStop || device.manualAutoStatus }]">
            {{ device.deviceName }}
          </div>
          <div v-show="isStartStop && !device.manualAutoStatus" class="device-batch-start-stop flex-1">
            <StartStopTip :device-data="device" @click="handleStartStopSwitch(device)" />
          </div>
          <ASwitch
            v-show="!isStartStop"
            :checked="device.disableEnableStatus"
            :checked-value="1"
            :un-checked-value="0"
            @click="handleDisableEnableSwitch(device)"
          />
          <ASegmented v-show="isStartStop" :value="device.manualAutoStatus" :options="manualAutoTypes">
            <template #label="option">
              <span @click="handleManualAutoClick(option as ManualAutoTypeItem, device)">
                {{ option.payload.title }}
              </span>
            </template>
          </ASegmented>
        </div>
      </ACollapsePanel>
    </ACollapse>
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
  </AModal>
</template>

<style lang="scss">
.device-batch-modal {
  .ant-modal-body {
    max-height: 650px;
    overflow-y: auto;
  }
}

.device-batch-tabs {
  .ant-tabs-nav {
    margin-bottom: 0;
  }
}

.device-batch-collapse.ant-collapse {
  > .ant-collapse-item > {
    .ant-collapse-header {
      padding: 16px 24px;
      background-color: #f5f6f7;
    }

    .ant-collapse-content > .ant-collapse-content-box {
      padding: 0;
    }
  }

  .ant-collapse-item + .ant-collapse-item {
    margin-top: 24px;
  }
}
</style>

<style lang="scss" scoped>
.device-batch-item-header {
  display: flex;
  align-items: center;

  i {
    width: 21px;
    height: 20px;
    margin-right: 16px;
    color: var(--antd-color-primary);
  }

  span {
    font-size: 14px;
    font-weight: 600;
    line-height: 24px;
    color: #000;
  }
}

.device-batch-list-item {
  display: flex;
  align-items: center;
  height: 56px;
  padding-inline: 24px;
  border-bottom: 1px solid #e4e7ed;

  .ant-switch {
    background: #f56c6c;

    &:hover:not(.ant-switch-disabled) {
      background: #ff9797;
    }

    &.ant-switch-checked {
      background: var(--antd-color-primary);

      &:hover:not(.ant-switch-disabled) {
        background: var(--antd-color-primary-hover);
      }
    }
  }

  :deep(.ant-segmented) {
    padding: 4px;
    color: var(--antd-color-primary);
    background-color: var(--antd-color-primary-opacity-15);
    border-radius: 8px;

    .ant-segmented-group > div {
      background-color: var(--antd-color-primary);
    }

    .ant-segmented-item-label {
      display: flex;
      align-items: center;
      padding-inline: 0;

      span {
        padding: 5px 16px;
        font-size: 14px;
        font-weight: 500;
        line-height: 22px;
      }
    }

    .ant-segmented-item-selected {
      color: #fff;
      background-color: var(--antd-color-primary);
      box-shadow: none;
    }

    .ant-segmented-item {
      + .ant-segmented-item {
        margin-left: 4px;
      }

      &:hover:not(.ant-segmented-item-selected, .ant-segmented-item-disabled) {
        color: var(--antd-color-primary);

        &::after {
          background-color: var(--antd-color-primary-opacity-15);
        }
      }
    }
  }
}

.device-batch-list-status {
  margin-right: 12px;
}

.device-batch-list-name {
  line-height: 24px;
  color: var(--antd-color-text-secondary);
}

.device-batch-start-stop {
  display: flex;
  justify-content: space-between;
  margin-right: 24px;
  margin-left: 16px;
}
</style>
