<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import dayjs from 'dayjs';

import { DeviceType } from '@/views/device-work-status/device-card';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { getAIOptimizeDetail, updateAIOptimizeSetting } from '@/api';
import { isEmptyVal } from '@/utils';

import type { ColumnType } from 'ant-design-vue/es/table';
import type { AIOptimizeDeviceItem, AIOptimizeSetItemExpose, TemperatureRange, TemperatureRangeItem } from '@/types';

interface Props {
  groupId: number;
}

const props = defineProps<Props>();

const devices = ref<AIOptimizeDeviceItem[]>([]);

const deviceColumns = computed<ColumnType<AIOptimizeDeviceItem>[]>(() => [
  {
    title: t('realTimeMonitor.deviceName'),
    dataIndex: 'deviceName',
    key: 'deviceName',
  },
  {
    title: t('realTimeMonitor.deviceStatus'),
    dataIndex: 'runningStatus',
    key: 'runningStatus',
    width: 128,
  },
  {
    title: t('realTimeMonitor.isInAlgorithm'),
    dataIndex: 'addingToAlg',
    key: 'addingToAlg',
    width: 128,
  },
]);

const temperatureRanges = ref<TemperatureRange[]>([]);

const isOneTempRange = computed(() => {
  return temperatureRanges.value.length <= 1;
});

const addTimeRange = () => {
  temperatureRanges.value.push({} as TemperatureRange);
};

const deleteTimeRange = (index: number) => {
  if (!isOneTempRange.value) {
    temperatureRanges.value.splice(index, 1);
  }
};

const { handleRequest } = useRequest();

onMounted(() => {
  handleRequest(async () => {
    const { deviceList, algorithmConfig } = await getAIOptimizeDetail(props.groupId, DeviceType.冷水主机);
    const tempRange = JSON.parse(algorithmConfig.chilledWaterOutletTempRange || '[]') as TemperatureRangeItem[];
    algorithmId = algorithmConfig.id;
    devices.value = deviceList;

    temperatureRanges.value = tempRange.map<TemperatureRange>((item) => ({
      time: [dayjs(item.startTime, 'HH:mm'), dayjs(item.endTime, 'HH:mm')],
      lower: item.lower,
      upper: item.upper,
    }));
  });
});

let algorithmId: number | undefined;

const submit = async () => {
  const invalidTempRange = temperatureRanges.value.find((item) => {
    return isEmptyVal(item.time?.[0]) || isEmptyVal(item.time?.[1]) || isEmptyVal(item.lower) || isEmptyVal(item.upper);
  });

  if (invalidTempRange) {
    throw new Error(t('realTimeMonitor.waterTempCtrlIntervalValEmpty'));
  }

  const tempRange = temperatureRanges.value.map<TemperatureRangeItem>((item) => ({
    startTime: item.time?.[0].format('HH:mm') as string,
    endTime: item.time?.[1].format('HH:mm') as string,
    lower: item.lower,
    upper: item.upper,
  }));

  await updateAIOptimizeSetting({
    deviceList: devices.value,
    algorithmConfig: {
      id: algorithmId,
      chilledWaterOutletTempRange: JSON.stringify(tempRange),
    },
  });
};

defineExpose<AIOptimizeSetItemExpose>({
  submit,
});
</script>

<template>
  <div>
    <div class="chiller-optimize-device-title">{{ t('realTimeMonitor.settingParticipatingDevices') }}</div>
    <ATable
      class="chiller-optimize-table hvac-table"
      :columns="deviceColumns"
      :data-source="devices"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'runningStatus'">
          <span :class="['device-status-tag', { 'device-status-run': record.runningStatus === 1 }]">
            {{ record.runningStatus === 1 ? $t('common.run') : $t('common.shutDown') }}
          </span>
        </template>
        <template v-if="column.key === 'addingToAlg'">
          <ASwitch v-model:checked="record.addingToAlg" />
        </template>
      </template>
    </ATable>
    <div class="chiller-optimize-time-title">
      <span>{{ t('realTimeMonitor.waterTemperatureControlInterval') }}</span>
      <AButton class="icon-button" @click="addTimeRange">
        <SvgIcon name="plus" />
        {{ t('realTimeMonitor.addTimePeriod') }}
      </AButton>
    </div>
    <div class="chiller-optimize-time-temp-item" v-for="(item, index) in temperatureRanges" :key="index">
      <div>
        <span class="chiller-optimize-time-temp-label">{{ $t('realTimeMonitor.timeSegment') }}</span>
        <ATimeRangePicker v-model:value="item.time" format="HH:mm" :allow-clear="false" separator="-">
          <template #suffixIcon>
            <SvgIcon name="clock-circle-o" :size="16" color="var(--antd-color-text-secondary)" />
          </template>
        </ATimeRangePicker>
        <span class="chiller-optimize-time-temp-label">{{ $t('realTimeMonitor.outletTemperature') }}</span>
        <AInputNumber
          class="chiller-optimize-temp-min"
          v-model:value="item.lower"
          :min="0"
          :max="item.upper"
          :precision="1"
          :controls="false"
        />
        <span class="chiller-optimize-temp-separator">-</span>
        <AInputNumber
          class="chiller-optimize-temp-max hvac-input-number"
          v-model:value="item.upper"
          :min="item.lower"
          :max="999"
          :precision="1"
          :controls="false"
          addon-after="℃"
        />
      </div>
      <SvgIcon :class="{ 'delete-icon-disable': isOneTempRange }" name="delete" @click="deleteTimeRange(index)" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chiller-optimize-device-title {
  margin-bottom: 16px;
  font-size: 14px;
  font-weight: 500;
  line-height: 22px;
}

:deep(.chiller-optimize-table).ant-table-wrapper .ant-table-container {
  .ant-table-thead > tr > th:first-child {
    padding-left: 40px;
  }

  .ant-table-tbody > tr > td,
  tfoot > tr > th,
  tfoot > tr > td {
    &:first-child {
      padding-left: 40px;
    }
  }
}

.device-status-tag {
  padding: 2px 8px;
  font-size: 12px;
  line-height: 20px;
  color: #666;
  background: #f8f8f8;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
}

.device-status-run {
  color: #52c41a;
  background: #f6ffed;
  border-color: #b7eb8f;
}

.chiller-optimize-time-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 24px;
  margin-bottom: 16px;

  > span {
    font-size: 14px;
    font-weight: 500;
    line-height: 22px;
  }

  button {
    color: var(--antd-color-primary);
    background: rgb(255 255 255 / 0%);
    border: 1px solid var(--antd-color-primary);
    border-radius: 4px;

    i {
      font-weight: 900;
    }
  }
}

.chiller-optimize-time-temp-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: #f5f7fa;

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

  > div {
    display: flex;
    align-items: center;
  }

  .ant-picker {
    width: 256px;
    margin-right: 40px;
  }

  > i {
    font-size: 21px;
    color: var(--antd-color-primary);
    cursor: pointer;

    &.delete-icon-disable {
      cursor: not-allowed;
      opacity: 0.6;
    }
  }

  :deep(input) {
    text-align: center;
  }
}

.chiller-optimize-time-temp-label {
  margin-right: 16px;
}

.chiller-optimize-temp-min,
:deep(.chiller-optimize-temp-max) .ant-input-number {
  width: 102px;

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

.chiller-optimize-temp-min {
  border-right-color: transparent;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

:deep(.chiller-optimize-temp-max) {
  .ant-input-number {
    border-left-color: transparent;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}

.chiller-optimize-temp-separator {
  display: block;
  width: 12.5px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background-color: #fff;
  border-top: 1px solid var(--antd-color-border);
  border-bottom: 1px solid var(--antd-color-border);
}
</style>
