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

import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { getAIAdvancedSetting, updateGroupModuleDevData } from '@/api';
import { isNotEmptyVal } from '@/utils';
import { DevParamCtrlCabinet } from '@/constants/device-params';

import type { FormInstance } from 'ant-design-vue';
import type { SegmentedBaseOption } from 'ant-design-vue/es/segmented/src/segmented';
import type { AIAdvancedParamItem, GroupModuleInfo } from '@/types';

interface Props {
  info: GroupModuleInfo;
}

const props = defineProps<Props>();

type ParamTypeValue = 'addSubtractLoad' | 'other';

interface ParamTypeItem extends SegmentedBaseOption {
  value: ParamTypeValue;
  payload: {
    title: string;
  };
}

const paramTypes = computed<ParamTypeItem[]>(() => {
  return [
    {
      value: 'addSubtractLoad',
      payload: {
        title: t('realTimeMonitor.addSubtractLoadParameters'),
      },
    },
    {
      value: 'other',
      payload: {
        title: t('realTimeMonitor.otherParameters'),
      },
    },
  ];
});

const currentParamType = ref<ParamTypeValue>('addSubtractLoad');
const formRef = ref<FormInstance>();

watch(currentParamType, () => {
  const formEl = formRef.value?.$el as HTMLElement | undefined;

  formEl?.scrollTo({
    top: 0,
    behavior: 'smooth',
  });
});

const addSubLoadParamOrder: string[] = [
  DevParamCtrlCabinet.冷机出水温度,
  DevParamCtrlCabinet.加机温差,
  DevParamCtrlCabinet.减机温差,
  DevParamCtrlCabinet.加机负载率,
  DevParamCtrlCabinet.减机负载率,
  DevParamCtrlCabinet.加机延时1,
  DevParamCtrlCabinet.减机延时,
  DevParamCtrlCabinet.加机延时2,
  DevParamCtrlCabinet.塔出水温度,
  DevParamCtrlCabinet.加塔温差,
  DevParamCtrlCabinet.减塔温差,
  DevParamCtrlCabinet.加塔频率,
  DevParamCtrlCabinet.减塔频率,
  DevParamCtrlCabinet.加塔延时,
  DevParamCtrlCabinet.减塔延时,
];

const { isLoading, handleRequest } = useRequest();
const paramList = ref<AIAdvancedParamItem[]>([]);
let settingsTimer: number | undefined;

const typeParamsMap = computed<Record<ParamTypeValue, AIAdvancedParamItem[]>>(() => {
  const addSubLoadParams = paramList.value
    .filter((item) => addSubLoadParamOrder.includes(item.deviceParamCode))
    .sort((a, b) => {
      const indexA = addSubLoadParamOrder.indexOf(a.deviceParamCode);
      const indexB = addSubLoadParamOrder.indexOf(b.deviceParamCode);
      return indexA - indexB;
    });

  const otherParams = paramList.value.filter((item) => !addSubLoadParamOrder.includes(item.deviceParamCode));

  return {
    addSubtractLoad: addSubLoadParams,
    other: otherParams,
  };
});

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

onUnmounted(() => {
  paramList.value = [];
  clearTimeout(settingsTimer);
});

const getSettings = () => {
  clearTimeout(settingsTimer);

  handleRequest(async () => {
    const { groupId } = props.info;
    paramList.value = await getAIAdvancedSetting(groupId);
  });

  settingsTimer = window.setTimeout(getSettings, 5000);
};

const updateDeviceData = (deviceId: number, paramCode: string, value?: string | number | null) => {
  handleRequest(async () => {
    if (isNotEmptyVal(value)) {
      await updateGroupModuleDevData(deviceId, paramCode, value);
    }
  });
};
</script>

<template>
  <div class="ctrl-panel-scroll-container">
    <ASegmented v-model:value="currentParamType" :options="paramTypes">
      <template #label="{ payload }">
        <span>{{ payload.title }}</span>
      </template>
    </ASegmented>
    <AForm ref="formRef" class="ai-advanced-param-form ctrl-panel-scroll-content" layout="vertical">
      <ARow :gutter="32">
        <template v-for="(params, type) in typeParamsMap" :key="type">
          <ACol v-show="type === currentParamType" v-for="item in params" :key="item.paramId" :span="12">
            <AFormItem :label="item.deviceParamName">
              <ASelect
                v-if="item.pullWindow"
                v-model:value="item.value"
                popup-class-name="ai-advanced-select-popup"
                @change="updateDeviceData(item.deviceId, item.deviceParamCode, $event as string)"
              >
                <ASelectOption :value="item.zeroValue" />
                <ASelectOption :value="item.oneValue" />
              </ASelect>
              <AInputNumber
                v-else
                v-model:value="item.value"
                :controls="false"
                @change="updateDeviceData(item.deviceId, item.deviceParamCode, $event)"
              />
            </AFormItem>
          </ACol>
        </template>
      </ARow>
    </AForm>
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
  </div>
</template>

<style lang="scss">
.ai-advanced-select-popup {
  background-color: rgb(44 54 70);

  .ant-select-item {
    color: #fff;

    &:hover {
      background-color: rgb(255 255 255 / 20%);
    }
  }

  .ant-select-item-option-selected:not(.ant-select-item-option-disabled) {
    color: #fff;
    background-color: rgb(255 255 255 / 20%);
  }
}
</style>

<style lang="scss" scoped>
:deep(.ant-form) {
  h4 {
    margin-bottom: 12px;
    font-size: 14px;
    font-weight: 500;
    line-height: 22px;
    color: #fff;
  }

  .ant-form-item .ant-form-item-label > label {
    font-size: 14px;
    font-weight: 400;
    color: rgb(255 255 255 / 65%);
  }

  .ant-input-number {
    width: 100%;
    color: #fff;
    background: rgb(30 37 48 / 32%);
    border-color: rgb(255 255 255 / 24%);
    border-radius: 4px;

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

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

  .ant-select {
    .ant-select-selector {
      color: #fff;
      background-color: rgb(30 37 48 / 32%);
      border-color: rgb(255 255 255 / 24%);
    }

    .ant-select-arrow {
      color: #8c94a8;
    }

    &.ant-select-single.ant-select-open .ant-select-selection-item {
      color: rgb(255 255 255 / 25%);
    }
  }
}
</style>
