<script setup lang="ts">
import { traduction, getErrorTranslate } from '@/utils/language';
import { computed, onUnmounted, onMounted, reactive, ref, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { UI_REST_FIRMWAREINVENTORY } from '@/api/api';
import { UploadFile } from 'element-plus/es/components/upload/src/upload';
import { ElNotification as elNotification } from 'element-plus';
import { IconHelpCircle, IconCaretDown } from '@computing/opendesign-icons';
import Dialog from '@/components/Dialog/Dialog.vue';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import ibmaServer from './ibma.server';
import { rangeVerification } from '@/validators/validation-functions';
import { showFailedMessage, showSuccessMessage } from '@/utils/composition';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';


const globalStoreService = new GlobalStoreService();
// 点击弹窗确认按钮回调逻辑
function logSetUpdate() {
  logSetDialogRef.value.show();
  checkFormStatus();
}

const smsName = useStore().state.loct.smsName;
const { getIbmaLogData, updateIbmaLogData } = ibmaServer(smsName);

// 表头信息
const columns = ref([
  {
    label: 'TABLE_TITLE_NUM',
    prop: 'Num',
  },
  {
    label: 'IBMA_LOG_NAME',
    prop: 'Name',
  },
  {
    label: 'IBMA_LOG_LEVEL',
    prop: 'Level',
  },
  {
    label: 'IBMA_LOG_NOTE',
    prop: 'Description',
  },
]);

// 表数据
const tableData: any = reactive({
  value: [],
});

// 日志说明列
const logDescriptions = [
  {
    logName: 'Common',
    logDescription: traduction('IBMA_LOG_DES_COMMON', { smsName }),
  },
  {
    logName: 'Http',
    logDescription: traduction('IBMA_LOG_DES_HTTP'),
  },
  {
    logName: 'Service',
    logDescription: traduction('IBMA_LOG_DES_SERVICE', { smsName }),
  },
  {
    logName: 'NicError',
    logDescription: traduction('IBMA_LOG_DES_NICERROR'),
  },
  {
    logName: 'Alert',
    logDescription: traduction('IBMA_LOG_DES_ALERT', { softwareName: useStore().state.loct.sn }),
  },
  {
    logName: 'AlertSys',
    logDescription: traduction('IBMA_LOG_DES_ALERTSYS', { softwareName: useStore().state.loct.sn }),
  },
  {
    logName: 'Kmsg',
    logDescription: traduction('IBMA_LOG_DES_KMSG'),
  },
  {
    logName: 'Bob',
    logDescription: traduction('IBMA_LOG_DES_BOB'),
  },
  {
    logName: 'Cdev',
    logDescription: traduction('IBMA_LOG_DES_CDEV'),
  },
  {
    logName: 'Tcp',
    logDescription: traduction('IBMA_LOG_DES_TCP', { smsName }),
  },
  {
    logName: 'Udp',
    logDescription: traduction('IBMA_LOG_DES_UDP', { smsName }),
  },
  {
    logName: 'Manager',
    logDescription: traduction('IBMA_LOG_DES_MANAGER'),
  },
  {
    logName: 'Oam',
    logDescription: traduction('IBMA_LOG_DES_OAM'),
  },
  {
    logName: 'MeshDetect',
    logDescription: traduction('IBMA_LOG_DES_MESHDETECT'),
  },
  {
    logName: 'Sff',
    logDescription: traduction('IBMA_LOG_DES_SFF'),
  },
  {
    logName: 'Hwbox',
    logDescription: traduction('IBMA_LOG_DES_HWBOX'),
  },
  {
    logName: 'Disk',
    logDescription: traduction('IBMA_LOG_DES_DISK'),
  },
  {
    logName: 'CdevDriver',
    logDescription: traduction('IBMA_LOG_DES_CDEVDRIVER'),
  },
  {
    logName: 'CdevVethDriver',
    logDescription: traduction('IBMA_LOG_DES_CDEVVETHDRIVER'),
  },
  {
    logName: 'EdmaDriver',
    logDescription: traduction('IBMA_LOG_DES_EDMADRIVER'),
  },
  {
    logName: 'VethDriver',
    logDescription: traduction('IBMA_LOG_DES_VETHDRIVER'),
  },
];

const logSetDialogRef = ref();

const logSetConfig = reactive({
  id: 'logSetDialog',
  type: 'warning',
  content: '',
  size: 'medium',
  title: traduction('IBMA_LOG_EXPORT_SET', { smsName }),
  okButton: { id: 'log_ok_btn'},
});

const store = useStore();
// 获取locked锁定值
let systemLockDownEnabled = computed(() => {
  return store.state.glob.systemLocked;
});
// 常规配置权限
const isBaseConfig = checkPrivil(UserPrivil.baseConfig);
let params: any = reactive({
  BMCRelevantAttributes: {},
});
watch(systemLockDownEnabled, () => {
  getLogData();
});

// 临时设置、永久设置radio
const logSetData: any = reactive({
  // 默认临时设置(temporarilySet：临时设置、永久设置：permanentSet)
  radio: 'temporarilySet',
  logName: '',
  logLowestLevel: 'DEBUG',
  timeLimit: '',
});

// 日志类型单选框发生修改
function raidoChange(value: string) {
  checkFormStatus();
  // 临时日志日志类别置空
  temporarilyLogInfo.radio = [];
  // 永久日志日志类别置空
  permanentLogInfo.radio = [];
  // 日志级别初始化DEBUG
  logSetData.logLowestLevel = 'DEBUG';
  // 生效时间
  activeTimeInMins.timeInMins = 0;
}
// 日志设置弹窗配置
const logSettingConfig = reactive({
  title: traduction('COMMON_INFORMATION'),
  content: '',
  closeIcon: false,
  cancelButton: {
    hide: true,
  },
});

// 点击弹窗确认按钮回调逻辑
function logSetHandle(reason: boolean) {
  logSetDialogRef.value.hide();
  if (reason) {
    let p = {};
    if (logSetData.radio === 'temporarilySet') {
      // 临时配置（传日志类别、日志级别、生效时间；）
      let logLevel = {};
      temporarilyLogInfo.radio.forEach((element: any) => {
        logLevel[element] = logSetData.logLowestLevel;
      });
      p = {
        PermanentEnable: false,
        ActiveTimeInMins: Number(activeTimeInMins.timeInMins),
        LogLevel: logLevel,
      };
    } else {
      // 永久配置（传日志类别、日志级别、不传生效时间；）
      let logLevel = {};
      permanentLogInfo.radio.forEach((element: any) => {
        logLevel[element] = logSetData.logLowestLevel;
      });
      p = {
        PermanentEnable: true,
        LogLevel: logLevel,
      };
    }
    updateIbmaLogTempData(p);
    resetLogData();
  } else {
    resetLogData();
  }
}

// 重置初始化页面数据
function resetLogData() {
  // 默认临时设置
  logSetData.radio = 'temporarilySet';
  // 临时日志日志类别置空
  temporarilyLogInfo.radio = [];
  // 永久日志日志类别置空
  permanentLogInfo.radio = [];
  // 日志级别初始化DEBUG
  logSetData.logLowestLevel = 'DEBUG';
  // 生效时间
  activeTimeInMins.timeInMins = 0;
}

let temporarilyLogOptions = [
  {
    value: 'Common',
    label: 'Common',
  },
  {
    value: 'Http',
    label: 'Http',
  },
  {
    value: 'Service',
    label: 'Service',
  },
  {
    value: 'NicError',
    label: 'NicError',
  },
  {
    value: 'Alert',
    label: 'Alert',
  },
  {
    value: 'AlertSys',
    label: 'AlertSys',
  },
  {
    value: 'Kmsg',
    label: 'Kmsg',
  },
  {
    value: 'Bob',
    label: 'Bob',
  },
  {
    value: 'Cdev',
    label: 'Cdev',
  },
  {
    value: 'Tcp',
    label: 'Tcp',
  },
  {
    value: 'Udp',
    label: 'Udp',
  },
  {
    value: 'Manager',
    label: 'Manager',
  },
  {
    value: 'Oam',
    label: 'Oam',
  },
  {
    value: 'MeshDetect',
    label: 'MeshDetect',
  },
  {
    value: 'Sff',
    label: 'Sff',
  },
  {
    value: 'Hwbox',
    label: 'Hwbox',
  },
  {
    value: 'Disk',
    label: 'Disk',
  },
  {
    value: 'CdevDriver',
    label: 'CdevDriver',
  },
  {
    value: 'CdevVethDriver',
    label: 'CdevVethDriver',
  },
  {
    value: 'EdmaDriver',
    label: 'EdmaDriver',
  },
  {
    value: 'VethDriver',
    label: 'VethDriver',
  },
];

let permanentLogOptions = [
  {
    value: 'Common',
    label: 'Common',
  },
  {
    value: 'Http',
    label: 'Http',
  },
  {
    value: 'Service',
    label: 'Service',
  },
  {
    value: 'NicError',
    label: 'NicError',
  },
  {
    value: 'Alert',
    label: 'Alert',
  },
  {
    value: 'AlertSys',
    label: 'AlertSys',
  },
  {
    value: 'Kmsg',
    label: 'Kmsg',
  },
  {
    value: 'Bob',
    label: 'Bob',
  },
];

let etag = '';

const temporarilyLogInfo = reactive({
  radio: [],
});

const permanentLogInfo = reactive({
  radio: [],
});

const activeTimeInMins = reactive({
  timeInMins: 0,
});

// 弹窗中表单校验规则
const rules = reactive({
  runTimes: {
    type: 'number',
    required: true,
    isInteger: true,
    min: 1,
    max: 60,
    message: traduction('VALID_VALUE_RANGE_TIP', [1, 60]),
    validator: rangeVerification,
    trigger: 'blur',
  },
});

const validateResult = reactive({
  timeInMins: false,
});

// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validate(key: string, state: boolean, message: any) {
  validateResult[key] = state;
  nextTick(()=>{
    checkFormStatus();
  });
}

// 获取数据
function getLogData() {
  getIbmaLogData()
    .then((res: any) => {
      globalStoreService.setValue('isLoading', false);
      tableData.value = handleLogLevelData(res.data.LogLevel);
      etag = res.headers.etag;
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
    });
}

// 处理日志级别
function handleLogLevelData(levelData: object) {
  let levelDataArr = [];
  for (let key in levelData) {
    if ({}.hasOwnProperty.call(levelData, key)) {
      levelDataArr.push({
        Name: key,
        Level: levelData[key],
        Description: logDescriptions.find(
          (item: any) => {
            return item.logName === key;
          },
        )?.logDescription,
      });
    }
  }
  return levelDataArr;
}

// 提交日志弹窗配置数据
function updateIbmaLogTempData(p: any) {
  globalStoreService.setValue('isLoading', true);
  updateIbmaLogData(p, etag)
    .then((res: any) => {
      globalStoreService.setValue('isLoading', false);
      showSuccessMessage();
      getLogData();
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
      showFailedMessage();
    });
}

// 弹窗表格数据校验
function checkFormStatus() {
  if (logSetData.radio === 'temporarilySet') {
    if (
      temporarilyLogInfo.radio.length === 0 ||
      activeTimeInMins.timeInMins === 0 ||
      !activeTimeInMins.timeInMins || 
      !validateResult['timeInMins']
    ) {
      logSetDialogRef.value.disable();
    } else {
      logSetDialogRef.value.enable();
    }
  } else {
    if (permanentLogInfo.radio.length === 0) {
      logSetDialogRef.value.disable();
    } else {
      logSetDialogRef.value.enable();
    }
  }
}

// 获取数据
getLogData();

</script>

<template>
  <!-- 输出设置 -->
  <el-button
    :id="'logSetBtn'"
    :type="'primary'"
    :disabled="systemLockDownEnabled || !isBaseConfig"
    @click="logSetUpdate"
  >
    {{ traduction('IBMA_EXPORT_SETTING') }}
  </el-button>
  <!-- 日志详情列表 -->
  <div class="root-container">
    <el-table id="logTable" :data="tableData.value" resizable border>
      <!-- 序号 -->
      <el-table-column :label="$t(columns[0].label)" type="index" />

      <el-table-column :prop="'Name'" :label="$t(columns[1].label)" :resizable="true">
        <template #default="scope">
          <span class="locale-name">{{ scope.row.Name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column :prop="'Level'" :label="$t(columns[2].label)" :resizable="true">
        <template #default="scope">
          <span class="locale-level">{{ scope.row.Level }}</span>
        </template>
      </el-table-column>

      <el-table-column :prop="'Description'" :label="$t(columns[3].label)">
        <template #default="scope">
          <span class="locale-description">{{ scope.row.Description }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 输出设置弹窗 -->
  <Dialog ref="logSetDialogRef" :config="logSetConfig" @close="logSetHandle">
    <template #other>
      <div style="display: block;">
        <div style="display: flex;">
          <div style="margin-top: 16px; margin-right: 20px;">
            <span style="margin-right: 4px;">{{ $t('IBMA_LOG_SET_TYPE') }}</span>
            <el-tooltip effect="light" :content="$t('IBMA_LOG_ICON_TIP_CONTENT')" placement="top" trigger-keys>
              <el-icon :size="16" class="tip"><IconHelpCircle /></el-icon>
            </el-tooltip>
          </div>
          <!-- 临时设置、永久设置radio -->
          <div class="radio-box">
            <el-radio
              v-model="logSetData.radio"
              v-addId.radio="'temporarilySetId'"
              label="temporarilySet"
              size="large"
              @change="raidoChange"
            >
              {{ $t('IBMA_LOG_TEMPORARILY_SET') }}
            </el-radio>
            <el-radio
              v-model="logSetData.radio"
              v-addId.radio="'permanentSetId'"
              label="permanentSet"
              size="large"
              @change="raidoChange"
            >
              {{ $t('IBMA_LOG_PERMANENTSET_SET') }}
            </el-radio>
          </div>
          <span class="warning-tip">{{ $t('IBMA_LOG_WARNING_TIP_CONTENT', { smsName }) }}</span>
        </div>
        <div>
          <el-form
            label-position="left"
            label-width="auto"
            :model="activeTimeInMins"
            :rules="rules"
            @validate="validate"
          >
            <!-- 临时设置联动表单字段 -->
            <el-form-item
              v-show="logSetData.radio === 'temporarilySet'"
              :label="$t('IBMA_LOG_NAME')"
              style="margin-top: 14px;"
              prop="logName"
            >
              <!-- 临时设置-日志名称 -->
              <el-select
                v-model="temporarilyLogInfo.radio"
                v-addId.select="'roleList'"
                multiple
                collapse-tags
                filterable
                :teleported="false"
                :suffix-icon="IconCaretDown"
                @change="checkFormStatus"
              >
                <el-option
                  v-for="item in temporarilyLogOptions"
                  :id="'role_' + item.value"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-show="logSetData.radio === 'temporarilySet'"
              :label="$t('IBMA_LOG_EXPORT_LOWEST_EXPORT_LEVEL')"
              style="margin-top: 14px;"
              prop="exportLevel"
            >
              <!-- 临时设置-输出最低级别radio -->
              <div class="log-level-box">
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'temporarilySetId'"
                  label="DEBUG"
                  size="large"
                >
                  Debug
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'temporarilySetId'"
                  label="INFO"
                  size="large"
                >
                  Info
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'temporarilySetId'"
                  label="WARNING"
                  size="large"
                >
                  Warning
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'temporarilySetId'"
                  label="ERROR"
                  size="large"
                >
                  Error
                </el-radio>
              </div>
            </el-form-item>
            <el-form-item
              v-show="logSetData.radio === 'temporarilySet'"
              :label="$t('IBMA_LOG_EXPORT_TIME_LIMIT')"
              prop="timeInMins"
              :rules="rules.runTimes"
            >
              <!-- 临时设置-输出时限 -->
              <el-input
                id="timeInMins"
                v-model="activeTimeInMins.timeInMins"
                v-clearable
                type="text"
                clearable
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
              <span class="log-time-unit">{{ $t('IBMA_LOG_EXPORT_TIME_UNIT') }}</span>
            </el-form-item>

            <!-- 永久设置联动表单字段 -->
            <el-form-item
              v-show="logSetData.radio === 'permanentSet'"
              :label="$t('IBMA_LOG_NAME')"
              style="margin-top: 14px;"
              prop="logName"
            >
              <!-- 日志名称 -->
              <el-select
                v-model="permanentLogInfo.radio"
                v-addId.select="'roleList'"
                multiple
                collapse-tags
                filterable
                :teleported="false"
                :suffix-icon="IconCaretDown"
                @change="checkFormStatus"
              >
                <el-option
                  v-for="item in permanentLogOptions"
                  :id="'role_' + item.value"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-show="logSetData.radio === 'permanentSet'"
              :label="$t('IBMA_LOG_EXPORT_LOWEST_EXPORT_LEVEL')"
              style="margin-top: 14px;"
              prop="lowestExportLevel"
            >
              <!-- 永久设置-输出最低级别radio -->
              <div class="log-level-box">
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'permanentSetId'"
                  label="DEBUG"
                  size="large"
                >
                  Debug
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'permanentSetId'"
                  label="INFO"
                  size="large"
                >
                  Info
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'permanentSetId'"
                  label="WARNING"
                  size="large"
                >
                  Warning
                </el-radio>
                <el-radio
                  v-model="logSetData.logLowestLevel"
                  v-addId.radio="'permanentSetId'"
                  label="ERROR"
                  size="large"
                >
                  Error
                </el-radio>
              </div>
            </el-form-item>
            <el-form-item
              v-show="logSetData.radio === 'permanentSet'"
              :label="$t('IBMA_LOG_EXPORT_TIME_LIMIT')"
              prop="timeLimit"
            >
              <!-- 永久设置-输出时限 -->
              <el-input
                id="timeInMins"
                v-model="activeTimeInMins.timeInMins"
                v-clearable
                disabled
                type="text"
                clearable
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
              <span class="log-time-unit">{{ $t('IBMA_LOG_EXPORT_TIME_UNIT') }}</span>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<style lang="scss" scoped>
  .root-container{
    margin-top: 16px;
  }
  .radio-box {
    margin-top: 5px;
    margin-bottom: 11px;
    margin-left: 6px;
  }
  .warning-tip {
    margin-top: 16px;
    margin-left: 8px;
    color: var(--o-text-color-tertiary);
  }
  :deep(.el-form-item__label) {
    margin-top: 2px;
  }
  :deep(.el-dialog) {
    width: 544px;
  }
  #roleList {
    width: 100%;
    :deep(.el-tag) {
      display: inline-flex;
      height: 24px;
      background-color: #DFE5EF !important;
      position: static;
      color: var(--o-text-color-primary);
    }
  }

  :deep(.el-input--suffix) {
    width: 56px;
  }

  .log-time-unit {
    margin-left: 8px;
  }
  :deep(.el-radio){
    .el-radio__label{
      font-size: 12px;
    }
  }
</style>
