<template>
  <div id="raidInfo" class="raid-info">
    <div v-if="startCollectingLogs" class="alertDiv">
      <div class="alertIcon">
        <el-icon size="16">
          <IconAlarm />
        </el-icon>
      </div>
      <div class="alertContent">
        {{ $t('STORE_TIP_COLLECTLOG_STARTED') }}
      </div>
    </div>
    <div class="raid-content">
      <div class="raid-info-lfet">
        <div class="system-icon controller-img"></div>
        <p class="info-title">{{ $t('STORE_RAID_INFO') }}</p>
        <el-button
          v-if="isShowSetting && hasBaseConfigPrivil"
          :id="'settingBtn'"
          :disabled="systemLocked || startCollectingLogs || onTask"
          class="setting-btn"
          size="small"
          @click="show()"
        >
          {{ $t('HOME_FDM_ALARM_SETTING') }}
        </el-button>
        <el-tooltip :content="$t(collectLogTxt) + (percentValue || percentValue === 0 ? `${percentValue}%` : '')" trigger-keys>
          <el-button
            v-if="isShowSetting && isShowCollectBtn && hasBaseConfigPrivil"
            :id="'collectBtn'"
            :disabled="systemLocked || startCollectingLogs"
            class="setting-btn"
            size="small"
            @click="showCollectMsg"
          >
            {{ $t(collectLogTxt) + (percentValue || percentValue === 0 ? `${percentValue}%` : '') }}
          </el-button>
        </el-tooltip>
        <div v-if="dialogVisible" v-reqKeepAlive.dialog>
          <el-dialog
            v-model="dialogVisible"
            width="432px"
            :close-on-click-modal="false"
            :append-to-body="false"
          >
            <template #title>{{ $t('HOME_FDM_ALARM_SETTING') }}</template>
            <RaidEditComponent
              v-if="dialogVisible"
              :data="raidEdit.data"
              :raidNode="raidNode"
              @edit-change="editChange"
            ></RaidEditComponent>
            <template #footer>
              <span class="dialog-footer">
                <el-button
                  id="raidEditOkBtn"
                  size="small"
                  type="primary"
                  :disabled="editStatus"
                  @click="secondDialogRef.show()"
                >
                  {{ $t('COMMON_OK') }}
                </el-button>
                <el-button id="raidEditCancelBtn" size="small" @click="dialogVisible = false">
                  {{ $t('COMMON_CANCEL') }}
                </el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        <Dialog ref="secondDialogRef" :config="secondDialogConfig" @close="closeModal" />
        <Dialog ref="collectDialogRef" :config="colletDialogConfig" @close="closeCollectModal" />
      </div>
      <div id="raidContent">
        <div>
          <template v-for="item in raid.data" :key="item">
            <div v-if="item[0] && item[1] !== null" class="row">
              <p class="row-left">{{ $t(item[0]) }}</p>
              <p class="row-right">{{ getI18n(item[1]) }}</p>
            </div>
          </template>
          <template v-if="raid.bbu.length > 0">
            <div class="bbu-title">BBU</div>
            <template v-for="item in raid.bbu" :key="item">
              <div v-if="item[0]" class="row">
                <p class="row-left">{{ $t(item[0]) }}</p>
                <p class="row-right">{{ getI18n(item[1]) }}</p>
              </div>
            </template>
          </template>
          <div class="clearBoth"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, defineExpose, computed, onBeforeUnmount, watch } from 'vue';
import { factory } from './raid.service';
import RaidEditComponent from './raid-edit/RaidEdit.vue';
import Dialog from '@/components/Dialog/Dialog.vue';

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 { traduction, getErrorTranslate } from '@/utils/language';
import { RaidEditService } from './raid-edit/raid-edit.service';
import { StorageTree, Raid, RaidNode, RaidEditModel, VolumeNode, RaidType } from '../../models';
import { collectProgress, getDownLoadRaidFileContent } from '@/pages/Home/services/home.service';
import { getLocationSearch, getMessageId, getSsoErrorMsg, showElMessage } from '@/utils/utils';
import { alertMessage } from '../../../../Maintance/Report/report.service';
import { IconAlarm } from '@computing/opendesign-icons';
import { downloadFileWithResponse } from '@/utils/common-service';
const store = useStore();
let systemLocked = computed(() => {
  return store.state.glob.systemLocked;
});

const hasBaseConfigPrivil = checkPrivil(UserPrivil.baseConfig);

const emit = defineEmits(['changeCollectList']);
let raid = reactive({ data: <any[]>[], bbu: <any[]>[] });
const raidEdit = reactive({ data: {} });
const editStatus = ref(true);
const raidEditService = new RaidEditService();
let nodeUrl: string;
const isShowCollectBtn = ref(false);
let timers: any[] = [];
// 是否处于一键收集状态
const startCollectingLogs = ref(false);
// 收集按钮显示查看进度还是收集日志
const collectLogTxt = ref('STORE_COLLECTING_LOGS');
const percentValue = ref();
let raidNode = reactive({} as RaidNode);
interface RaidData {
  bandManag: string[];
  bbu: Object;
  cachePinned: string[];
  childData: Object;
  configVersion: string[];
  copyback: string[];
  deviceInter: string[];
  driveArr: Object[];
  driverName: string[];
  driverVersion: string[];
  faultMemory: string[];
  firmwareVersion: string[];
  foreignConfigStatus: boolean;
  health: string[];
  jbodModel: [];
  memorySize: string[];
  mode: [];
  name: string[];
  sn: string[];
  raidLevels: [];
  sasAddress: string[];
  smartErrors: [];
  stripSizeRange: string[];
  supportedModes: Object;
  type: string[];
  [propName: string]: any;
}

let isShowSetting = ref(true);
let dialogVisible = ref(false);
const secondDialogConfig = reactive({
  id: 'secondDialog',
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
});
const colletDialogConfig = reactive({
  id: 'oneKeyCollect',
  title: traduction('COMMON_CONFIRM'),
  content: traduction('STORE_COLLECTING_CONFIRM'),
  okButton: { id: 'oneKeyCollect_ok_btn' },
  cancelButton: { id: 'oneKeyCollect_cancel_btn' },
});
const secondDialogRef = ref();
const collectDialogRef = ref();

const props = defineProps({
  data: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  collectList: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  onTask: {
    type: Boolean,
    default: false,
  },
});
watch(props.collectList, newVal => {
  startCollectingLogs.value = props.collectList[raidNode.labelId] || false;
});
const data = reactive(props.data);
const collectList = reactive(props.collectList);
const getRaid = data?.data[0];

function factoryFun(node?: any) {
  nodeUrl = node ? node.url : data.url;
  factory(node || data, nodeUrl).then(node => {
    raidEdit.data = node as RaidData;
    data.setRaid = node;
    raidNode.setRaid = node;
    formatRaidData(node);
    getConllectBtn();
    isShowSetting.value = settingShow();
    loading(false);
  });
}
function formatRaidData(node: any) {
  raid.data = [];
  let res = node as RaidData;
  for (const i in res) {
    if (Object.prototype.toString.call(res[i]) === '[object Array]') {
      if (Object.prototype.toString.call(res[i][0]) === '[object String]') {
        raid.data.push(res[i]);
      }
    }
    if (i === 'bbu' && res['bbu'] && Object.keys(res['bbu']).length > 0) {
      raid.bbu.splice(0);
      Object.keys(res['bbu']).forEach(key => {
        raid.bbu.push(res[i][key]);
      });
    }
  }
}
function show() {
  editStatus.value = true;
  dialogVisible.value = true;
}
function getI18n(str?: any) {
  if (!str) {
    return '--';
  }
  if (Object.prototype.toString.call(str) === '[object Object]') {
    if (str.label) {
      return traduction(str.label) ? traduction(str.label) : str.label;
    } else {
      return '--';
    }
  } else {
    str = traduction(str) ? traduction(str) : str;
  }
  return str;
}

onMounted(() => {
  checkNode();
});
onBeforeUnmount(() => {
  timers.forEach(item => {
    clearTimeout(item);
  });
});
defineExpose({
  factoryFun, checkNode
});

function checkNode(node?: any) {
  nodeUrl = node ? node.url : data.url;
  raidNode = StorageTree.getInstance().getCheckedNode as RaidNode;
  isShowCollectBtn.value = false;
  showIsCollecting();
  if (raidNode.getRaid) {
    raidEdit.data = raidNode.getRaid;
    data.setRaid = raidNode.getRaid;
    formatRaidData(raidNode.getRaid);
    getConllectBtn();
    isShowSetting.value = settingShow();
  } else {
    factoryFun(raidNode);
  }
}

let paramsData: any;
function editChange(params: any) {
  paramsData = params;
  editStatus.value = JSON.stringify(params) === '{"ConsisCheckInfo":{}}';
}

// 关闭确认弹出框
function closeModal(reason: boolean) {
  if (reason) {
    loading(true);
    raidEditService
      .updateEditData(nodeUrl, paramsData)
      .then(res => {
        factoryFun(getRaid);
        showSuccessMessage();
      })
      .catch(err => {
        const errCode = err.data.error[0].code;
        if (errCode === 'RAIDControllerSetSuccessfully') {
          showSuccessMessage(traduction('SYSTEM_LOG_PCIE_TIP'));
        } else {
          showFailedMessage();
        }
      })
      .finally(() => {
        loading(false);
        dialogVisible.value = false;
      });
  }
  secondDialogRef.value.hide();
}

// 关闭确认弹出框
function closeCollectModal(reason: boolean) {
  if (reason) {
    oneKeyCollectFunc('click');
  }
  collectDialogRef.value.hide();
}

function getConllectBtn() {
  const conllectCard =
    data.setRaid?.getBandManag &&
    (raidNode.getRaidType === RaidType.ARIES || raidNode.getRaidType === RaidType.PMC);
  if (conllectCard) {
    isShowCollectBtn.value = true;
    const id = raidNode.labelId;
    startCollectingLogs.value = collectList[id] || false;
  }
}

function settingShow(): boolean {
  if (data.setRaid.getChidrenData) {
    const isBRCM = raidNode.getRaidType === RaidType.BRCM;
    const isARIES = raidNode.getRaidType === RaidType.ARIES;
    const isPMC = raidNode.getRaidType === RaidType.PMC;
    const isHBA = raidNode.getRaidType === RaidType.HBA;

    // 是否支持带外管理
    const oobSupport = data.setRaid.getChidrenData.oobSupport || false;
    // 逻辑盘列表
    const volumeNodeList =
      raidNode.children?.filter(item => item.componentName === 'VolumeNode') || [];
    if (isBRCM || isARIES || isHBA) {
      return oobSupport;
    }

    // 设置按钮显示:1.若PMC卡不支持工作模式的场景隐藏（PMC卡只支持工作模式）2.有逻辑盘且模式不能是HBA
    if (isPMC) {
      const mode = data.setRaid.getSupportedModes.options;
      return mode !== null && oobSupport;
    }
  }

  return false;
}
function oneKeyCollectFunc(data: string) {
  let fileName = raidNode.label.replace(/\s+/g, '_') + '.tar.gz';
  const collectUrl = raidNode.getUrl;
  if (!localStorage.getItem('raidFileName')) {
    localStorage.setItem('raidFileName', fileName);
  }
  if (data !== 'init') {
    raidEditService
      .oneKeyCollect(collectUrl)
      .then(res => {
        const { url } = res.data;
        const str = sessionStorage.getItem('raidCollectProgressURL');
        if (str) {
          const obj = JSON.parse(str);
          obj[raidNode.id] = url;
          const str2 = JSON.stringify(obj);
          sessionStorage.setItem('raidCollectProgressURL', str2);
        } else {
          const obj: any = {};
          obj[raidNode.id] = url;
          const str2 = JSON.stringify(obj);
          sessionStorage.setItem('raidCollectProgressURL', str2);
        }
        queryCollectProgress(fileName);
      })
      .catch(err => {
        const collectLogUrl = getCollectUrl();
        if (
          collectLogUrl &&
          getMessageId(err.error)[0]['errorId'].indexOf('DuplicateExportingErr') > -1
        ) {
          queryCollectProgress(fileName);
        }
      });
  } else {
    const collectLogUrl = getCollectUrl();
    if (collectLogUrl) {
      queryCollectProgress(fileName);
    }
  }
}
function queryCollectProgress(fileName: string) {
  const labelId = raidNode.labelId;
  const collectLogUrl = getCollectUrl();
  collectProgress(collectLogUrl)
    .then(res => {
      const prepareProgress = res.data.prepare_progress;
      if (prepareProgress || prepareProgress === 0) {
        percentValue.value = prepareProgress;
      }
      if (prepareProgress === 100) {
        const str = sessionStorage.getItem('raidCollectProgressURL');
        if (str) {
          const obj = JSON.parse(str);
          delete obj[raidNode.id];
          const str2 = JSON.stringify(obj);
          sessionStorage.setItem('raidCollectProgressURL', str2);
        }
        localStorage.removeItem('raidFileName');
        queryDownloadUrl(fileName, labelId);
      } else {
        emit('changeCollectList', labelId, true);
        collectLogTxt.value = 'STORE_COLLECTING_LOGS_VIEW';
        const progressTimer = setTimeout(() => {
          queryCollectProgress(fileName);
        }, 2000);
        timers.push(progressTimer);
      }
    })
    .catch(error => {
      emit('changeCollectList', labelId, false);
      collectLogTxt.value = 'STORE_COLLECTING_LOGS';
      const str = sessionStorage.getItem('raidCollectProgressURL');
      if (str) {
        const obj = JSON.parse(str);
        delete obj[raidNode.id];
        const str2 = JSON.stringify(obj);
        sessionStorage.setItem('raidCollectProgressURL', str2);
      }
      localStorage.removeItem('raidFileName');
      const errorId = getMessageId(error.error)[0]['errorId'];
      const errorMessage = getErrorTranslate(errorId) || 'COMMON_FAILED';
      alertMessage({ type: 'error', label: errorMessage });
    });
}

function queryDownloadUrl(fileName: string, labelId: string) {
  getDownLoadRaidFileContent(fileName)
    .then(res => {
      downloadFileWithResponse(res.data, fileName);
      const pecentTimer = setTimeout(() => {
        collectLogTxt.value = 'STORE_COLLECTING_LOGS';
        percentValue.value = '';
        emit('changeCollectList', labelId, false);
      }, 1000);
      const showResultTimer = setTimeout(() => {
        showSuccessMessage();
      }, 3000);
      timers.push(pecentTimer, showResultTimer);
    })
    .catch(() => {
      emit('changeCollectList', labelId, false);
      percentValue.value = '';
      showFailedMessage();
    });
}
function showCollectMsg() {
  if (collectLogTxt.value === 'STORE_COLLECTING_LOGS') {
    collectDialogRef.value.show();
  } else {
    showIsCollecting();
  }
}
function getCollectUrl() {
  const collectProgressURL = sessionStorage.getItem('raidCollectProgressURL');
  if (collectProgressURL) {
    const obj = JSON.parse(collectProgressURL);
    const id = raidNode.id;
    return obj[id];
  }
  return null;
}
function showIsCollecting() {
  const collectLogUrl = getCollectUrl();
  if (collectLogUrl) {
    oneKeyCollectFunc('init');
  }
}
</script>

<style scoped lang="scss">
#raidInfo {
  background: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 16px 16px;
  margin-top: 8px;
  .alertDiv {
    display: flex;
    margin-bottom: 16px;
    background-color: var(--o-color-major-secondary);
    height: 32px;
    align-items: center;
    padding-left: 16px;
    border-radius: 4px;
    .alertIcon {
      height: 16px;
      line-height: 16px;
    }
    .alertContent {
      padding-left: 8px;
    }
  }
  .raid-content {
    display: flex;
  }
  .raid-info-lfet {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 72px;
    border-right: 1px solid var(--o-border-color-light);
    width: 183px;
    flex-shrink: 0;
    .info-title {
      font-size: 12px;
      color: var(--o-text-color-primary);
      line-height: 16px;
    }
    .setting-btn {
      font-size: 12px;
      margin-top: 8px;
      margin-left: 0px;
      width: 89px;
      :deep(span){
        max-width: 71px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .download-btn {
      width: 100px;
    }
    .controller-img {
      width: 30px;
      height: 30px;
      margin-bottom: 12px;
      background: url(@/assets/assets-bmc/default/storage_control.svg) 50% 50%;
    }
  }
  #raidContent {
    .bbu-title {
      width: 100%;
      float: left;
      padding: 8px 0;
    }
    .row {
      width: 50%;
      float: left;
      padding: 8px 0;
      .row-left {
        width: 35%;
        display: inline-block;
        font-size: 12px;
        color: var(--o-text-color-secondary);
        word-break: break-word;
      }
      .row-right {
        width: 65%;
        display: inline-block;
        font-size: 12px;
        color: var(--o-text-color-secondary);
        word-break: break-word;
      }
    }
  }
}
:deep(.el-button--text > span) {
  color: inherit;
}
</style>

<style lang="scss" scoped>
.raid-info {
  :deep(.el-overlay) {
    .el-dialog__header {
      color: var(--o-text-color-primary);
      font-size: 16px;
      font-weight: 900;
    }
  }
}
</style>
