<script setup lang="ts">
import { useRoute } from 'vue-router';
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from '@ant-design-vue/pro-layout';
import { Form, Modal, message } from 'ant-design-vue/lib';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import {
  getForwardSet,
  getAlarmSet,
  updateAlarmSet,
  updateForwardSet,
} from '@/api/faultManage/faultSetting';
import useI18n from '@/hooks/useI18n';
const { t } = useI18n();
const route = useRoute();

/**路由标题 */
let title = ref<string>((route.meta.title as string) ?? '标题');

/**对象信息状态类型 */
type ModalStateType = {
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**表单数据 loading */
  fromLoading: boolean;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**告警设置信息状态 */
let alarmState: ModalStateType = reactive({
  title: '告警设置',
  from: {
    historyDuration: '',
    unit: 'day',
    syncTaskPeriod: '',
    alarmStart: '',
    alarmEnd: '',
  },
  fromLoading: true,
  confirmLoading: true,
});

/**告警设置信息内表单属性和校验规则 */
const alarmStateFrom = Form.useForm(
  alarmState.from,
  reactive({
    historyDuration: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入日志保存时间,最少15天',
      },
    ],
    syncTaskPeriod: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入告警同步周期',
      },
    ],
    alarmStart: [
      {
        required: true,
        trigger: 'blur',
        message: '请选择告警同步开始时间',
      },
    ],
    alarmEnd: [
      {
        required: true,
        trigger: 'blur',
        message: '请选择告警同步结束时间',
      },
    ],
  })
);

/**告警设置保存 */
function fnFormLogSetFinish() {
  alarmStateFrom.validate().then(() => {
    alarmState.confirmLoading = true;
    const from = toRaw(alarmState.from);
    updateAlarmSet(from)
      .then(res => {
        if (res.code === RESULT_CODE_SUCCESS && res.data > 0) {
          message.success(`告警设置保存成功`, 3);
        } else {
          message.warning(`告警设置无变更`, 3);
        }
      })
      .finally(() => {
        alarmState.confirmLoading = false;
      });
  });
}

/**告警前转接口对象信息状态 */
let forwardState: ModalStateType = reactive({
  title: '告警前转接口设置',
  from: {
    interface: 'email',
    forObject: '',
  },
  fromLoading: true,
  confirmLoading: true,
});

/**告警前转接口对象信息内表单属性和校验规则 */
const forwardStateFrom = Form.useForm(
  forwardState.from,
  reactive({
    forObject: [
      {
        required: true,
        message: '请输入前转对象',
      },
    ],
  })
);

/**告警前转接口对象保存 */
function fnFormForwardFinish() {
  forwardStateFrom.validate().then(() => {
    forwardState.confirmLoading = true;
    const from = toRaw(forwardState.from);
    updateForwardSet(from)
      .then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(`告警前转接口设置保存成功`, 3);
        } else {
          message.warning(`告警前转接口设置无变更`, 3);
        }
      })
      .finally(() => {
        forwardState.confirmLoading = false;
      });
  });
}

onMounted(() => {
  Promise.allSettled([getAlarmSet(), getForwardSet()]).then(resArr => {
    // 查询告警设置
    if (resArr[0].status === 'fulfilled') {
      const result = resArr[0].value;
      if (result.code === RESULT_CODE_SUCCESS) {
        alarmState.from = Object.assign(alarmState.from, result.data);
        alarmState.fromLoading = false;
        alarmState.confirmLoading = false;
      }
    }
    // 查询告警前转接口设置
    if (resArr[1].status === 'fulfilled') {
      const result = resArr[1].value;
      if (result.code === RESULT_CODE_SUCCESS) {
        forwardState.from = Object.assign(forwardState.from, result.data);
        forwardState.fromLoading = false;
        forwardState.confirmLoading = false;
      }
    }
  });
});
</script>

<template>
  <PageContainer :title="title">
    <a-row :gutter="16">
      <a-col :span="8">
        <!-- 日志设置 -->
        <a-card :title="alarmState.title" :loading="alarmState.fromLoading">
          <template #extra>
            <a-space :size="8" align="center">
              <a-button
                type="primary"
                :loading="alarmState.confirmLoading"
                @click.prevent="fnFormLogSetFinish"
              >
                <template #icon><SaveOutlined /></template>
                保存设置
              </a-button>
            </a-space>
          </template>
          <a-form
            name="alarmState.from"
            layout="horizontal"
            autocomplete="off"
            :label-col="{ span: 8 }"
          >
            <a-form-item
              label="历史告警保存时间(天)"
              name="historyDuration"
              v-bind="alarmStateFrom.validateInfos.historyDuration"
            >
              <a-input-number
                v-model:value="alarmState.from.historyDuration"
                placeholder="15"
                :min="15"
              />
            </a-form-item>
            <a-form-item
              label="告警同步周期单位"
              name="unit"
              v-bind="alarmStateFrom.validateInfos.unit"
            >
              <a-select v-model:value="alarmState.from.unit">
                <a-select-option key="hour" value="hour">小时</a-select-option>
                <a-select-option key="day" value="day">天</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="告警同步周期"
              name="syncTaskPeriod"
              v-bind="alarmStateFrom.validateInfos.syncTaskPeriod"
            >
              <a-input-number
                v-model:value="alarmState.from.syncTaskPeriod"
                placeholder="10"
                :min="10"
              />
            </a-form-item>
            <a-form-item
              label="告警同步开始时间"
              name="alarmStart"
              v-bind="alarmStateFrom.validateInfos.alarmStart"
            >
              <a-date-picker
                show-time
                placeholder="Select Time"
                v-model:value="alarmState.from.alarmStart"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
            <a-form-item
              label="告警同步结束时间"
              name="alarmEnd"
              v-bind="alarmStateFrom.validateInfos.alarmEnd"
            >
              <a-date-picker
                show-time
                placeholder="Select Time"
                v-model:value="alarmState.from.alarmEnd"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 告警前转接口设置-->
        <a-card :title="forwardState.title" :loading="forwardState.fromLoading">
          <template #extra>
            <a-space :size="8" align="center">
              <a-button
                type="primary"
                :loading="forwardState.confirmLoading"
                @click.prevent="fnFormForwardFinish"
              >
                <template #icon><SaveOutlined /></template>
                保存设置
              </a-button>
            </a-space>
          </template>
          <a-form
            name="forwardState"
            layout="horizontal"
            autocomplete="off"
            :label-col="{ span: 8 }"
          >
            <a-form-item label="告警前转接口类型" name="interface">
              <a-select v-model:value="forwardState.from.interface">
                <a-select-option key="sms" value="sms">SMS</a-select-option>
                <a-select-option key="email" value="email"
                  >Email</a-select-option
                >
              </a-select>
            </a-form-item>
            <a-form-item
              label="告警前转对象"
              name="forObject"
              v-bind="forwardStateFrom.validateInfos.forObject"
            >
              <a-input
                v-model:value="forwardState.from.forObject"
                allow-clear
                placeholder="请输入告警前转对象"
              ></a-input>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </PageContainer>
</template>

<style lang="less" scoped>
.backFile-download {
  margin-left: 12px;
  color: #eb2f96;
  text-decoration: underline;
}
</style>
