<script setup lang="ts">
import { reactive, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { Form, 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();

/**对象信息状态类型 */
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: t('views.faultManage.faultSetting.forwardSet'),
  from: {
    interface: 'email',
    emailObj: [],
    smsObj: [],
  },
  fromLoading: true,
  confirmLoading: true,
});

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

/**告警前转接口对象保存 */
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(
            t('common.msgSuccess', {
              msg: t('views.faultManage.faultSetting.save'),
            }),
            3
          );
        } else {
          message.warning(t('views.faultManage.faultSetting.noChange'), 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) {
        let finalData: any = {
          emailObj: result.data[0]['to_user'],
          smsObj: result.data[1]['to_user'],
        };
        forwardState.from = Object.assign(forwardState.from, finalData);
        forwardState.fromLoading = false;
        forwardState.confirmLoading = false;
      }
    }
  });
});
</script>

<template>
  <PageContainer>
    <a-row :gutter="16">
      <a-col :span="8" v-if="false">
        <!-- 日志设置 -->
        <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>
                {{ t('views.faultManage.faultSetting.save') }}
              </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>
                {{ t('views.faultManage.faultSetting.save') }}
              </a-button>
            </a-space>
          </template>
          <a-form name="forwardState" layout="horizontal" autocomplete="off">
            <a-form-item
              :label="t('views.faultManage.faultSetting.interfaceType')"
              name="interface"
            >
              <a-input value="Email" allow-clear disabled></a-input>
            </a-form-item>
            <a-form-item
              :label="t('views.faultManage.faultSetting.email')"
              name="emailObj"
            >
              <a-select
                v-model:value="forwardState.from.emailObj"
                mode="tags"
                style="width: 100%"
                :token-separators="[',']"
              ></a-select>
            </a-form-item>
            <a-form-item
              :label="t('views.faultManage.faultSetting.interfaceType')"
              name="interface"
            >
              <a-input value="SMS" allow-clear disabled></a-input>
            </a-form-item>
            <a-form-item
              :label="t('views.faultManage.faultSetting.sms')"
              name="smsObj"
            >
              <a-select
                v-model:value="forwardState.from.smsObj"
                mode="tags"
                style="width: 100%"
                :token-separators="[',']"
              ></a-select>
            </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>
