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

import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import {
  addBatchMonitorPointAlarm,
  getMonitorPointAlarm,
  getMonitorPointInfo,
  updateBatchMonitorPointAlarm,
  updateLimits,
} from '@/api';

import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import type { LimitForm, MonitoringPointData, WarningItem } from '@/types';

const emit = defineEmits(['setClick']);

interface Props {
  monitoringId?: number;
  monitoringData: MonitoringPointData[];
}

const { handleRequest } = useRequest();
const props = defineProps<Props>();
const limitOpen = ref<boolean>(false);
const warningOpen = ref<boolean>(false);
const warningShow = ref<boolean>(false);
const formRef = ref<FormInstance>();
const limitForm = ref<LimitForm>({
  id: undefined,
  regionId: undefined,
  tempUpper: 0,
  tempLower: 0,
  tempPreset: 0,
  humidityUpper: 0,
  humidityLower: 0,
  humidityPreset: 0,
  batch: false,
});
const warningList = ref<WarningItem[]>([
  {
    pointId: props.monitoringId,
    enabled: false,
    type: 1,
    val: 0,
    duration: 0,
  },
  {
    pointId: props.monitoringId,
    enabled: false,
    type: 2,
    val: 0,
    duration: 0,
  },
]);

const rules: Record<string, Rule[]> = {
  id: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempUpper: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempLower: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempPreset: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityUpper: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityLower: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityPreset: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
};

const addLimit = () => {
  limitOpen.value = true;
  limitForm.value.batch = false;
};

const addWarning = () => {
  getMonitorPointList();
  warningOpen.value = true;
};

const getMonitorPointList = () => {
  handleRequest(async () => {
    if (props.monitoringId) {
      const data = await getMonitorPointAlarm(props.monitoringId);
      if (data.length) {
        warningShow.value = true;
        data.forEach((item, i) => {
          const { id, pointId, enabled, type, val, duration } = item;
          Object.assign(warningList.value[i], {
            id,
            pointId,
            enabled,
            type,
            val,
            duration,
          });
        });
      } else {
        warningShow.value = false;
        warningList.value = [
          {
            pointId: props.monitoringId,
            enabled: false,
            type: 1,
            val: 0,
            duration: 0,
          },
          {
            pointId: props.monitoringId,
            enabled: false,
            type: 2,
            val: 0,
            duration: 0,
          },
        ];
      }
    }
  });
};

const getLimit = () => {
  formRef.value
    ?.validate()
    .then(() => {
      handleRequest(async () => {
        await updateLimits(limitForm.value);
        getMonitorPoint();
        limitOpen.value = false;
        emit('setClick');
      });
    })
    .catch(() => {});
};

const getMonitorPoint = () => {
  handleRequest(async () => {
    if (props.monitoringId) {
      const { humidityLower, humidityPreset, humidityUpper, tempLower, tempPreset, tempUpper, id, regionId } =
        await getMonitorPointInfo(props.monitoringId);

      Object.assign(limitForm.value, {
        humidityLower,
        humidityPreset,
        humidityUpper,
        tempLower,
        tempPreset,
        tempUpper,
        id,
        regionId,
      });
    }
  });
};

const getWarning = () => {
  handleRequest(async () => {
    if (warningShow.value) {
      await updateBatchMonitorPointAlarm(warningList.value);
    } else {
      await addBatchMonitorPointAlarm(warningList.value);
    }
  });

  warningOpen.value = false;
};

watch(
  () => props.monitoringId,
  (count) => {
    if (count) {
      getMonitorPoint();
      getMonitorPointList();
    }
  },
);

onMounted(() => {
  getMonitorPoint();
});
</script>

<template>
  <div>
    <div>
      <AButton type="text" class="icon-button icon-style" @click="addLimit">
        <SvgIcon name="setting" />
        设置温湿度限值
      </AButton>
      <AButton type="text" class="icon-button icon-style" @click="addWarning">
        <SvgIcon name="setting" />
        设置温湿度预警
      </AButton>
    </div>

    <AModal
      v-model:open="limitOpen"
      title="设置温湿度限值"
      :footer="null"
      width="704px"
      :mask-closable="false"
      :keyboard="false"
    >
      <AForm ref="formRef" :model="limitForm" layout="vertical" :rules="rules">
        <AFormItem label="请选择监控点名" name="id">
          <ASelect
            class="select-width"
            v-model:value="limitForm.id"
            :options="monitoringData"
            :field-names="{ label: 'name', value: 'id' }"
            placeholder="请选择"
          />
        </AFormItem>
        <AFlex justify="space-between">
          <AFormItem label="室内温度设定值" name="tempPreset">
            <AInputNumber class="select-width" v-model:value="limitForm.tempPreset" :min="0" :max="40" />
          </AFormItem>
          <AFormItem label="室内温度上限值" name="tempUpper">
            <AInputNumber class="select-width" v-model:value="limitForm.tempUpper" :min="0" :max="40" />
          </AFormItem>
          <AFormItem label="室内温度下限值" name="tempLower">
            <AInputNumber class="select-width" v-model:value="limitForm.tempLower" :min="0" :max="40" />
          </AFormItem>
        </AFlex>
        <AFlex justify="space-between">
          <AFormItem label="室内湿度设定值" name="humidityPreset">
            <AInputNumber class="select-width" v-model:value="limitForm.humidityPreset" :min="0" :max="100" />
          </AFormItem>
          <AFormItem label="室内湿度上限值" name="humidityUpper">
            <AInputNumber class="select-width" v-model:value="limitForm.humidityUpper" :min="0" :max="100" />
          </AFormItem>
          <AFormItem label="室内湿度下限值" name="humidityLower">
            <AInputNumber class="select-width" v-model:value="limitForm.humidityLower" :min="0" :max="100" />
          </AFormItem>
        </AFlex>
        <ACheckbox v-model:checked="limitForm.batch">批量设置</ACheckbox>
      </AForm>
      <AFlex justify="flex-end" class="limit-top">
        <AButton class="limit-button default-button" @click="limitOpen = false">{{ $t('common.cancel') }}</AButton>
        <AButton type="primary" @click="getLimit">{{ $t('common.confirm') }}</AButton>
      </AFlex>
    </AModal>

    <AModal v-model:open="warningOpen" :footer="null" width="704px" :mask-closable="false" :keyboard="false">
      <template #title>
        <div class="warning-title">设置温湿度预警</div>
      </template>

      <div v-for="item in warningList" :key="item.id" class="warning-div warning-color">
        <ACheckbox v-model:checked="item.enabled" class="warning-color">{{
          item.type === 1 ? '启用温度预警' : '启用湿度预警'
        }}</ACheckbox>
        <AFlex align="center" class="warning-flex">
          <div>{{ item.type === 1 ? '室内温度大于' : '室内湿度大于' }}</div>

          <AInputNumber class="input-width" v-model:value="item.val" :min="1" :max="9999" />
          <div>{{ item.type === 1 ? '℃' : '%' }}</div>
          <div>，且持续时间大于</div>
          <AInputNumber class="input-width" v-model:value="item.duration" :min="1" :max="9999" />
          <div>min时，触发</div>
        </AFlex>
      </div>

      <AFlex justify="flex-end" class="limit-top">
        <AButton class="default-button limit-button" @click="warningOpen = false">{{ $t('common.cancel') }}</AButton>
        <AButton type="primary" @click="getWarning">{{ $t('common.confirm') }}</AButton>
      </AFlex>
    </AModal>
  </div>
</template>

<style lang="scss" scoped>
.input-width {
  width: 120px;
  margin: 0 12px;
}

.warning-flex {
  margin: 16px 0 32px;
}

.warning-color {
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: rgb(0 0 0 / 65%);
  text-align: left;
}

.warning-div {
  padding-top: 8px;
}

.warning-title {
  margin-bottom: 16px;
}

.limit-button {
  margin: 0 16px;
}

.limit-top {
  margin-top: 24px;
}

.icon-style {
  color: var(--antd-color-primary);
}

.select-width {
  width: 192px;
}
</style>
