<template>
  <div id="syslog">
    <div class="syslog-info">
      <h3 class="top-title">{{ $t('ALARM_REPORT_SYSLOG_FUNC') }}</h3>
      <el-form :model="formSyslog" label-width="auto" label-position="left">
        <!-- 告警级别 -->
        <el-form-item id="syslogAlarmLevelItem" :label="$t('ALARM_EVENT_ALARM_LEVEL')">
          <el-select
            v-model="formSyslog.alarmLevel.value"
            v-addId.select="'syslogAlarmLevel'"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="alarmLevelChange"
          >
            <el-option
              v-for="item in formSyslog.alarmLevel.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- syslog消息格式 -->
        <el-form-item
          id="syslogMessageFormatItem"
          :label="$t('ALARM_REPORT_SYSLOG_MESSAGE_FORMAT')"
        >
          <el-select
            v-model="formSyslog.messageFormat.value"
            v-addId.select="'syslogMessageFormat'"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="messageFormatChange"
          >
            <el-option
              v-for="item in formSyslog.messageFormat.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- syslog主机标识 -->
        <el-form-item id="syslogFlagItem" :label="$t('ALARM_REPORT_SYSLOG_FLAG')">
          <el-select
            v-model="formSyslog.syslogFlag.value"
            v-addId.select="'syslogFlag'"
            :disabled="
              formSyslog.messageFormat.value === 'RFC3164' ||
              isSystemLock ||
              !hasSecurityConfigPrivil
            "
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="syslogFlagChange"
          >
            <el-option
              v-for="item in formSyslog.syslogFlag.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="syslog-btns" :label="' '">
          <el-button
            id="syslogSaveBtn"
            :disabled="syslogBtn || isSystemLock"
            type="primary"
            @click="saveBtn(0)"
          >
            {{ $t('COMMON_SAVE') }}
          </el-button>
          <el-button v-show="!syslogBtn" id="syslogCancelBtn" @click="syslogCancelFun">
            {{ $t('COMMON_CANCEL') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="syslogTableBox" class="syslog-syntax">
      <h3 id="syslogTableTitle" class="table-title">{{ $t('ALARM_REPORT_SYSLOG_TITLE') }}</h3>
      <SyslogTable
        :data="srcData.data"
        :is-system-lock="isSystemLock"
        :has-permission="hasSecurityConfigPrivil"
        @operate-change="tableChange"
      ></SyslogTable>
    </div>
  </div>
  <Dialog ref="commonDialogRef" :config="commonDialogConfig" @close="commonDialogClose" />
</template>

<script lang="ts" setup>
import { traduction } from '@/utils/language';
import { computed, onMounted, reactive, ref } from 'vue';
import {
  getSyslogDBInfo,
  sysLogDBSave,
  sysLogDBSendTest
} from '../report.service';
import SyslogTable from './SyslogTableDB.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import useStore from '@/stores';
import { loading, showFailedMessage, showSuccessMessage } from '@/utils/composition';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import { useRouter } from 'vue-router';
import { deepClone } from '../../../../utils/utils';

const store = useStore();
let isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const hasSecurityConfigPrivil = checkPrivil(UserPrivil.securityConfig);
const globalStoreService = new GlobalStoreService();
const commonDialogRef = ref();

const commonDialogConfig = reactive({
  id: 'syslogTestModel',
  content: traduction('ALARM_REPORT_SYSLOG_TEST'),
  title: traduction('COMMON_CONFIRM'),
  cancelButton: {
    hide: true
  }
});
const formSyslog = reactive({
  state: false,
  alarmLevel: {
    value: 'Normal',
    options: [
      {
        id: 'None',
        key: '[NULL]'
      },
      {
        id: 'Critical',
        key: traduction('ALARM_EVENT_CRITICAL')
      },
      {
        id: 'Major',
        key: traduction('ALARM_EVENT_MAJOR')
      },
      {
        id: 'Minor',
        key: traduction('ALARM_EVENT_MINOR')
      },
      {
        id: 'Normal',
        key: traduction('ALARM_EVENT_NORMAL')
      }
    ]
  },
  messageFormat: {
    value: 'Custom',
    options: [
      {
        id: 'Custom',
        key: traduction('SERVICE_WBS_CRE_CUSTOM')
      },
      {
        id: 'RFC3164',
        key: 'RFC3164'
      }
    ]
  },
  syslogFlag: {
    value: 'BoardSN',
    options: [
      {
        id: 'BoardSN',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_1')
      },
      {
        id: 'ProductAssetTag',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_2')
      },
      {
        id: 'HostName',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_3')
      }
    ]
  }
});
let response: syslogType;
function stateChange(val: boolean) {
  changeBtnStatus();
}
// 告警级别change事件
function alarmLevelChange(val: string) {
  changeBtnStatus();
}
// syslog消息格式change事件
function messageFormatChange(val: string) {
  changeBtnStatus();
}
// syslog主机标识change事件
function syslogFlagChange(val: string) {
  changeBtnStatus();
}
// 传输协议change事件
function protocolChange(val: string) {
  changeBtnStatus();
}
// 认证方式change事件
function authModeChange(val: string) {
  changeBtnStatus();
}
function changeBtnStatus() {
  const isEqual =
    formSyslog.alarmLevel.value === defaultData.AlarmSeverity &&
    formSyslog.syslogFlag.value === defaultData.ServerIdentity &&
    formSyslog.messageFormat.value === defaultData.MessageFormat;
  if (isEqual) {
    syslogBtn.value = true;
  } else {
    syslogBtn.value = false;
  }
}
// 保存上面的数据
function saveBtn(redirectType: number) {
  const saveParam = {};
  if (formSyslog.alarmLevel.value !== defaultData.AlarmSeverity) {
    saveParam['AlarmSeverity'] = formSyslog.alarmLevel.value;
  }
  if (
    formSyslog.syslogFlag.value !== defaultData.ServerIdentity &&
    formSyslog.messageFormat.value !== 'RFC3164'
  ) {
    saveParam['ServerIdentity'] = formSyslog.syslogFlag.value;
  }
  if (formSyslog.messageFormat.value !== defaultData.MessageFormat) {
    saveParam['MessageFormat'] = formSyslog.messageFormat.value;
  }
  // 不为空
  if (JSON.stringify(saveParam) === '{}') {
    getInfo();
    return;
  }
  sysLogDBSave(saveParam).then(
    res => {
      showSuccessMessage();
      getInfo();
      syslogBtn.value = true;
    },
    error => {
      showFailedMessage();
      syslogBtn.value = false;
    }
  );
}

let defaultData: any;

const syslogCancel = ref(false);
const syslogBtn = ref(true);
const srcData = reactive({
  data: <any[]>[]
});
interface syslogServerList {
  MemberId: string;
  Address: string;
  LogItem: any[];
}
function _setLogTypeSelect(arr: []) {
  if (arr.length === 0) {
    return;
  }
  let result = '';
  arr.forEach(item => {
    result += _filterLogType(item) + ' + ';
  });
  return result.slice(0, -2);
}
function _filterLogType(type: string) {
  let zh = '';
  switch (type) {
    case 'OperationLog':
      zh = traduction('OPERATE_LOG');
      break;
    case 'SecurityLog':
      zh = traduction('SERCURITY_LOG');
      break;
    case 'EventLog':
      zh = traduction('EVENT_LOG');
      break;
    default:
      zh = traduction('OPERATE_LOG');
      break;
  }
  return zh;
}
interface syslogType {
  AlarmSeverity: string;
  MessageFormat: string;
  ServerIdentity: string;
  SyslogServers: any[];
}

function setTableData(response: syslogType) {
  const data: any[] = [];
  response.SyslogServers.forEach((item: any, idx: any) => {
    const obj = {};
    obj['num'] = Number(item.MemberId) + 1;
    obj['serviceAddr'] = item.Address;
    obj['logItem'] = [];

    if (item?.LogItem && item.LogItem.length > 0) {
      item.LogItem.forEach((i: any, idx: any) => {
        const itemObj = {};
        itemObj['LogType'] = i.LogType;
        itemObj['Enabled'] = i.Enabled;
        itemObj['port'] = i.Port === 0 ? null : i.Port;
        itemObj['TransmissionProtocol'] = i.TransmissionProtocol;
        itemObj['validationPort'] = {
          tip: traduction('VALIDTOR_RANGE'),
          tipPosition: 'right',
          errorMessage: {
            number: traduction('ALARM_REPORT_RANGESIZE'),
            digits: traduction('ALARM_REPORT_RANGESIZE'),
            rangeValue: traduction('ALARM_REPORT_RANGESIZE')
          }
        };
        itemObj['isEdit'] = false;
        itemObj['num'] = Number(item.MemberId) + 1;
        obj['logItem'].push(itemObj);
      });
    }
    obj['isEdit'] = false;
    obj['validationAddr'] = {
      tip: traduction('COMMON_IPV4_IPV6_DOMIN'),
      tipPosition: 'right',
      errorMessage: {
        pattern: traduction('COMMON_FORMAT_ERROR')
      }
    };

    obj['disabled'] = false;
    data.push(obj);
  });
  srcData.data = data;
}

function getInfo() {
  globalStoreService.setValue('isLoading', true);
  getSyslogDBInfo()
    .then(res => {
      defaultData = res['data'];
      response = res['data'] as syslogType;
      init(response);

      // 有表格数据
      if (response.SyslogServers && response.SyslogServers.length > 0 && !syslogCancel.value) {
        setTableData(response);
      }
      syslogCancel.value = false;
      syslogBtn.value = true;
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}
function init(response: syslogType) {
  formSyslog.alarmLevel.value = response.AlarmSeverity;
  formSyslog.messageFormat.value = response.MessageFormat;
  formSyslog.syslogFlag.value = response.ServerIdentity;
}
function syslogCancelFun() {
  init(response);
  syslogBtn.value = true;
}

const tempTableData: any[] = [];
// 表格操作
function tableChange(event: any) {
  loading(true);
  switch (event.key) {
    case 'save':
      if (event.value?.logItem && event.value.logItem.length > 0) {
        event.value.logItem.forEach((item: any) => {
          item.isEdit = false;
        });
      }
      event.value.isEdit = false;
      save(event.value);
      break;
    case 'cancel':
      if (event.value?.logItem && event.value.logItem.length > 0) {
        event.value.logItem.forEach((item: any) => {
          item.isEdit = false;
        });
      }
      cancel(event.value);
      event.value.isEdit = false;
      break;
    case 'edit':
      tempTableData[event.value.num - 1] = deepClone({
        num: event.value.num,
        serviceAddr: event.value.serviceAddr,
        logItem: event.value.logItem
      });
      if (event.value?.logItem && event.value.logItem.length > 0) {
        event.value.logItem.forEach((item: any) => {
          item.isEdit = true;
        });
      }
      event.value.isEdit = true;
      loading(false);
      break;
    case 'test':
      // 若参数未保存，弹框提示。
      if (!syslogBtn.value) {
        loading(false);
        commonDialogRef.value.show();
      } else {
        test(event.value);
      }
      break;
    default:
      return;
  }
}
interface saveType {
  num: number;
  logItem: any[];
  serviceAddr: any;
}

// 保存
function save(data: saveType) {
  let LogItem = [] as any[];
  data.logItem.forEach((item: any) => {
    LogItem.push({
      Enabled: item.Enabled,
      LogType: item.LogType,
      TransmissionProtocol: item.TransmissionProtocol,
      Port: parseInt(item.port as string, 10)
    });
  });
  const params = {
    SyslogServers: [
      {
        MemberId: data.num - 1,
        Address: data.serviceAddr,
        LogItem
      }
    ]
  };
  sysLogDBSave(params)
    .then(res => {
      const response = res['data'] as any;
      let SyslogServers = response?.SyslogServers;
      if (response.error) {
        showFailedMessage();
        SyslogServers = response['data']?.SyslogServers;
      } else {
        showSuccessMessage();
      }
      const memberId = data.num - 1;
      if (SyslogServers && SyslogServers.length > 0) {
        SyslogServers.forEach((item: { MemberId: any; Address: any; LogItem: any[] }) => {
          if (Number(item.MemberId) === Number(memberId)) {
            data.serviceAddr = item.Address;
            data.logItem = [];
            if (item?.LogItem && item.LogItem.length > 0) {
              item.LogItem.forEach((i: any, idx: any) => {
                const itemObj = {};
                itemObj['LogType'] = i.LogType;
                itemObj['Enabled'] = i.Enabled;
                itemObj['port'] = i.Port === 0 ? null : i.Port;
                itemObj['TransmissionProtocol'] = i.TransmissionProtocol;
                itemObj['validationPort'] = {
                  tip: traduction('VALIDTOR_RANGE'),
                  tipPosition: 'right',
                  errorMessage: {
                    number: traduction('ALARM_REPORT_RANGESIZE'),
                    digits: traduction('ALARM_REPORT_RANGESIZE'),
                    rangeValue: traduction('ALARM_REPORT_RANGESIZE')
                  }
                };
                itemObj['isEdit'] = false;
                itemObj['num'] = Number(item.MemberId) + 1;
                data.logItem.push(itemObj);
              });
            }
          }
        });
      }
      loading(false);
    })
    .catch(error => {
      loading(false);
      showFailedMessage();
    });
}
// 取消
function cancel(data: any) {
  data.logItem = tempTableData[data.num - 1].logItem;
  data.serviceAddr = tempTableData[data.num - 1].serviceAddr;
  tempTableData[data.num - 1] = null;
  loading(false);
}
// 测试
function test(data: { num: number; LogType: string }) {
  const params = {
    ID: Number(data.num - 1),
    LogType: data.LogType
  };
  sysLogDBSendTest(params)
    .then(res => {
      loading(false);
      showSuccessMessage(traduction('ALARM_REPORT_TEST_MESSAGE'));
    })
    .catch(error => {
      loading(false);
      const code = error?.data?.error[0]?.code;
      if (code) {
        let errorMessage = '';
        if (code === 'SyslogTestFailed') {
          errorMessage = 'TEST_SYSLOG_ERROR';
        } else {
          errorMessage = code + '.errorMessage';
        }
        showFailedMessage(traduction(errorMessage));
        return;
      }
      showFailedMessage();
    });
}

function commonDialogClose(reason: boolean) {
  commonDialogRef.value.hide();
}

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

<style lang="scss" scoped>
#syslog {
  margin-right: 24px;
  height: calc(100% - 104px);
}
#syslogCerItem {
  height: 16px;
  :deep(.el-form-item__label-wrap) {
    .el-form-item__label {
      padding-top: 0px;
    }
  }
}
#localCer {
  height: 16px;
  :deep(.el-form-item__label-wrap) {
    .el-form-item__label {
      padding-top: 0px;
    }
  }
}
.top-title {
  font-size: 16px;
  color: var(--o-text-color-primary);
  line-height: 24px;
  margin-bottom: 16px;
}
.syslog-info {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
  .el-select {
    width: 320px;
  }
}
.syslog-syntax {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
}
#syslogAlert {
  font-size: 12px;
  color: var(--o-color-major);
  letter-spacing: 0;
  line-height: 16px;
  margin-left: 8px;
}
.table-title {
  font-size: 16px;
  color: var(--o-text-color-primary);
  line-height: 24px;
  margin-bottom: 16px;
}
.syslog-btns {
  margin-bottom: 0;
}
:deep(.small-item) {
  height: 16px;
  .el-form-item__label {
    padding-top: 0;
    padding-bottom: 0;
  }
  .el-form-item__content {
    line-height: 16px;
  }
  .el-radio {
    height: 16px;
  }
  .el-radio__label {
    color: var(--o-text-color-secondary);
  }
}
</style>
