<script lang="ts" setup>
import useStore from '@/stores';
import { traduction } from '@/utils/language';
import { getStoreData } from '@/utils/composition';
import { IconSuccess, IconError } from '@computing/opendesign-icons';
import { showElMessage, getBrowserType } from '@/utils/utils';
import { reactive, ref, onMounted, nextTick, computed, onUnmounted } from 'vue';
import ibmaServer from './ibma.server';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import IbmaTabs from './IbmaTabs.vue';
import IbmaBasicSetting from './IbmaBasicSetting.vue';
import IbmaLog from './IbmaLog.vue';
import IbmaTimer from './IbmaTimer.vue';
import GlobalStoreService from '@/services/gloabal-store-service';

// 型号：IBMC或者其他
const store = useStore();
const smsName = store.state.loct.smsName;

const {
  getIbmaData,
  usbStickControl,
  generateStartupFile,
  refreshActivationState,
  getBasicData,
} = ibmaServer(smsName);

const globalStoreService = new GlobalStoreService();
const successMsg = traduction('COMMON_SUCCESS');
const errorMsg = traduction('COMMON_FAILED');
// 控制 安装IBMC 可点击状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
// 控制是否展示 安装IBMC 按钮
const isPrivileges = checkPrivil([UserPrivil.remoteControl, UserPrivil.vmm]);

let dialogVisible = ref(false);

const resourceId = getStoreData('loct', 'rn');

const tableData = reactive([
  {
    system: 'Linux',
    path: 'Linux/install.sh',
  },
]);

let timer: any = null;

const formData: any = reactive({ value: {} });

const modal = reactive({
  des1: traduction('IBMA_INSTALL_DES1'),
  des2: traduction('IBMA_INSTALL_DES2'),
  des3: traduction('IBMA_INSTALL_DES3'),
  system: traduction('IBMA_INSTALL_TABLETH1'),
  path: traduction('IBMA_INSTALL_TABLETH2'),
  helpInformation: traduction('IBMA_INSTALL_DES4'),
  start: traduction('IBMA_START_KVM'),
});

interface IIbmaInfo {
  label: string;
  value: string;
}

interface IIbma {
  iBMAInstallableShow: boolean;
  iBMAInfos: IIbmaInfo[];
  iBMAInserted: boolean;
  iBMAInsertedStr: string;
  iBMAVersion: string;
  iBMARunStatus: string;
  iBMADirverVersion: string;
}

let iBMA: IIbma = reactive({
  iBMAInstallableShow: false,
  iBMAInfos: [],
  iBMAInserted: false,
  iBMAInsertedStr: '',
  iBMAVersion: '',
  iBMARunStatus: '',
  iBMADirverVersion: '',
});

// 加工ibma数据
function getIBMAInfo(data: any) {
  const availiableInstallationPackages = data.AvailiableInstallationPackages;
  const installables = [];
  if (availiableInstallationPackages) {
    for (const availiable of availiableInstallationPackages) {
      installables.push({
        label: availiable.OSType,
        value: availiable.Version,
      });
    }
  }
  const installedPackage = data.InstalledPackage;
  const targetData = {
    installableVersionShow: data.iBMAPacketStatus === 'iBMAPacketIsAvailable',
    ibmaInfos: installables,
    inserted: data.Inserted,
    insertedStr: data.Inserted ? traduction('IBMA_READY') : traduction('IBMA_NOTREADY'),
    version: installedPackage.Version,
    driverVersion: installedPackage.DriverVersion,
    runningStatus: installedPackage.RunningStatus,
  };
  return targetData;
}

// 获取数据
function getData() {
  getIbmaData()
    .then((data: any) => {
      const ibmaData = getIBMAInfo(data);
      iBMA.iBMAInstallableShow = ibmaData.installableVersionShow;
      iBMA.iBMAInfos = ibmaData.ibmaInfos;

      iBMA.iBMAInserted = ibmaData.inserted;
      iBMA.iBMAInsertedStr = ibmaData.insertedStr;
      iBMA.iBMAVersion = ibmaData.version;
      iBMA.iBMADirverVersion = ibmaData.driverVersion;
      iBMA.iBMARunStatus = ibmaData.runningStatus;
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
      if (timer) {
        clearInterval(timer);
      }
    });
}

// 点击安装IBMA
function installNotes() {
  if (isSystemLock.value) {
    return;
  }
  if (iBMA.iBMAInserted) {
    showElMessage('warning', traduction('IBMA_ALERT1'));
  } else {
    globalStoreService.setValue('isLoading', true);
    const param = {
      Type: 'Connect',
    };
    usbStickControl(param)
      .then(() => {
        getData();
        globalStoreService.setValue('isLoading', false);
        dialogVisible.value = true;
      })
      .catch(() => {
        showElMessage('error', traduction('IBMA_ALERT2'));
        globalStoreService.setValue('isLoading', false);
      });
  }
}

function downloadFileWithResponse(res: any, fileName: string) {
  const browserType = getBrowserType();
  if (
    (browserType.browser === 'ie' || browserType.browser === 'edge') &&
    window.navigator['msSaveBlob'] &&
    window.navigator['msSaveBlob'] instanceof Function
  ) {
    window.navigator['msSaveBlob'](res, fileName);
  } else {
    const downloadUrl = window.URL.createObjectURL(res);
    const anchor = document.createElement('a');
    const body = document.getElementsByTagName('body')[0];
    body.appendChild(anchor);
    anchor.setAttribute('style', 'display:none');
    anchor.href = downloadUrl;
    anchor.download = fileName;
    anchor.click();
    window.URL.revokeObjectURL(downloadUrl);
  }
}

function exportKvmStartupFile() {
  return new Promise((resolve, reject) => {
    const locale = localStorage.getItem('locale');
    const param = {
      Mode: 'Shared',
      Language: locale ? locale.split('-')[0] : '',
    };
    const httpOptions = {};
    const headers = {
      'Content-Type': 'application/json;charset=utf-8',
      Accept: 'application/json',
    };
    httpOptions['headers'] = headers;
    httpOptions['responseType'] = 'blob';
    generateStartupFile(param, httpOptions)
      .then((res: any) => {
        const data = res.data;
        downloadFileWithResponse(data, 'kvm.jnlp');
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}

function openJavaShare() {
  exportKvmStartupFile()
    .then()
    .catch((res: any) => {
      showElMessage('success', traduction('COMMON_FAILED'));
    });
}

// 点击启动远程控制台
function sureSetting() {
  localStorage.setItem('H5ClientModel', 'Shared');
  const toURL = '#/kvm_h5';
  // 如果获取不到sessionId, 则不发送
  if (resourceId) {
    refreshActivationState()
      .then((res: any) => {
        dialogVisible.value = false;
        nextTick(() => {
          const win = window.open(toURL, '_blank');
          if (win) {
            win.opener = null;
          }
        });
      })
      .catch((err: any) => {
        dialogVisible.value = false;
        openJavaShare();
      });
  } else {
    openJavaShare();
  }
}

onMounted(() => {
  // 获取数据
  getData();
  getBasicData().then((res: any) => {
    formData.value = res.data;
  });
  timer = setInterval(() => {
    getData();
  }, 3000);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<template>
  <div id="ibmaContentId" class="ibma-box">
    <div v-if="iBMA.iBMAInstallableShow" id="ibmaVersion" class="part version">
      <div class="content">
        <div class="update-top">
          <div class="update">{{ $t('IBMA_UPDATE') }}</div>
          <div class="triangle"></div>
        </div>
        <div class="system-title">
          <div class="system-title-content">
            <div class="upload-system-icon upload-img" />
            <div class="left-text">{{ $t('IBMA_INSTALL_VERSION1') }}</div>
          </div>
          <el-button
            v-if="isPrivileges"
            id="install"
            class="btn"
            size="small"
            :disabled="isSystemLock"
            @click="installNotes"
          >
            {{ $t('IBMA_ADD_IBMA') }}
          </el-button>
        </div>
        <el-divider direction="vertical" class="vertical" />
        <div class="right-box-upload">
          <div class="fixedBox">
            <div class="left">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item key">
                {{ item.label }}
              </div>

              <div class="item key">
                {{ $t('IBMA_INSTALLER_STATUS') }}
              </div>
            </div>

            <div id="iBMAInfos" class="right">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item value">
                {{ item.value }}
              </div>

              <div class="item special-item value">
                <el-icon :class="!iBMA.iBMAInserted ? 'no-success-icon' : ''">
                  <IconSuccess />
                </el-icon>
                <span id="iBMAInsertedStr">
                  {{ iBMA.iBMAInsertedStr }}
                </span>
              </div>
            </div>
          </div>
          <div class="fixedBox">
            <div v-show="iBMA.iBMAInfos.length >= 3" class="left">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item key">
                {{ item.label }}
              </div>
              <div class="item key">
                {{ $t('IBMA_INSTALLER_STATUS') }}
              </div>
            </div>
            <div v-show="iBMA.iBMAInfos.length >= 3" id="iBMAInfos" class="right">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item value">
                {{ item.value }}
              </div>

              <div class="item special-item value">
                <el-icon :class="!iBMA.iBMAInserted ? 'no-success-icon' : ''">
                  <IconSuccess />
                </el-icon>
                <span id="iBMAInsertedStr">
                  {{ iBMA.iBMAInsertedStr }}
                </span>
              </div>
            </div>
          </div>
          <div class="fixedBox">
            <div v-show="iBMA.iBMAInfos.length >= 6" class="left">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item key">
                {{ item.label }}
              </div>

              <div class="item key">
                {{ $t('IBMA_INSTALLER_STATUS') }}
              </div>
            </div>
            <div v-show="iBMA.iBMAInfos.length >= 6" id="iBMAInfos" class="right">
              <div v-for="item in iBMA.iBMAInfos" :key="item.label" class="item value">
                {{ item.value }}
              </div>
              <div class="item special-item value">
                <el-icon :class="!iBMA.iBMAInserted ? 'no-success-icon' : ''">
                  <IconSuccess />
                </el-icon>
                <span id="iBMAInsertedStr">
                  {{ iBMA.iBMAInsertedStr }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 点击 安装IBMC的弹窗 -->
    <div v-if="dialogVisible && !isSystemLock" v-reqKeepAlive.dialog>
      <el-dialog
        id="ibmaModalId"
        v-model="dialogVisible"
        :title="$t('IBMA_INSTALL_NOTE')"
        :close-on-click-modal="false"
      >
        <div class="content">
          <div class="desBox">
            <div class="des">{{ modal.des1 }}</div>
            <div class="des">{{ modal.des2 }}</div>
            <div class="des">{{ modal.des3 }}</div>
          </div>

          <div class="table-bx">
            <el-table
              id="ibmaTable" :data="tableData" border resizable
              class="special-table"
            >
              <el-table-column prop="system" :label="modal.system" />
              <el-table-column prop="path" :label="modal.path" />
            </el-table>
          </div>

          <p class="help">{{ modal.helpInformation }}</p>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button id="sure" type="primary" size="small" @click="sureSetting">
              {{ modal.start }}
            </el-button>
            <el-button id="cancel" size="small" @click="dialogVisible = false">
              {{ $t('COMMON_CANCEL') }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
  <div id="ibmaContentId" class="ibma-status-box">
    <div id="ibmaStatus" class="part">
      <div class="content">
        <div class="system-title">
          <div class="system-title-content">
            <div class="system-icon restart-img" />
            <div class="left-text">{{ $t('IBMC_STATUS_MESSAGE', { smsName: smsName }) }}</div>
          </div>
        </div>
        <el-divider direction="vertical" class="vertical" />
        <div class="right-box">
          <div class="fixedBox">
            <div class="left">
              <div class="item key">{{ $t('IBMA_VERSION', { smsName: smsName }) }}</div>
              <div class="item key">{{ $t('IBMA_RUN_STATUS', { smsName: smsName }) }}</div>
              <div class="item key end-item">
                {{ $t('IBMA_DRIVER_VERSION', { smsName: smsName }) }}
              </div>
            </div>

            <div id="valueBox" class="right">
              <div id="iBMAVersion" class="item value">{{ iBMA.iBMAVersion || '--' }}</div>
              <div class="item value special-item">
                <el-icon
                  v-if="iBMA.iBMARunStatus"
                  :class="iBMA.iBMARunStatus !== 'Running' ? 'no-success-icon' : ''"
                >
                  <IconSuccess />
                </el-icon>
                <span id="iBMARunStatus">
                  {{ iBMA.iBMARunStatus || '--' }}
                </span>
              </div>
              <div id="iBMADirverVersion" class="item value end-item">
                {{ iBMA.iBMADirverVersion || '--' }}
              </div>
            </div>
          </div>
          <div class="fixedBox">
            <div class="left">
              <div class="item key">{{ $t('IBMC_SYSTEM_SUPPORTED', { smsName: smsName }) }}</div>
              <div class="item key">{{ $t('IBMC_NIC', { smsName: smsName }) }}</div>
              <div class="item key end-item">
                {{ $t('IBMC_PATH', { smsName: smsName }) }}
              </div>
            </div>

            <div id="valueBox" class="right">
              <div class="item value special-item">
                <el-icon
                  v-if="formData.value.Attributes?.SystemdSupported"
                  :class="formData.value.Attributes?.SystemdSupported ? '' : 'no-success-icon'"
                >
                  <IconSuccess />
                </el-icon>
                <el-icon v-else><IconError /></el-icon>
              </div>
              <div id="iBMAVersion" class="item value">{{ formData.value.Attributes?.Nic || '--' }}</div>

              <div id="iBMADirverVersion" class="item value end-item">
                {{ formData.value.Attributes?.Path || '--' }}
              </div>
            </div>
          </div>
          <div class="fixedBox">
            <div class="left">
              <div class="item key">{{ $t('IBMC_CHAR_DEVICE_PATH', { smsName: smsName }) }}</div>
              <div class="item key">{{ $t('IBMC_VERSION', { smsName: smsName }) }}</div>
              <div class="item key end-item">
                {{ $t('IBMC_RELEASE_DATE', { smsName: smsName }) }}
              </div>
            </div>

            <div id="valueBox" class="right">
              <div id="iBMAVersion" class="item value">
                {{ formData.value.Attributes?.CharDevicePath || '--' }}
              </div>
              <div id="iBMAVersion" class="item value">
                {{ formData.value.Attributes?.UsbDevicePath || '--' }}
              </div>
              <div id="iBMADirverVersion" class="item value end-item">
                {{ formData.value.Attributes?.ReleaseDate || '--' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <IbmaTabs>
    <template #BasicSetting><IbmaBasicSetting :form-data="formData.value" /></template>
    <template #Log><IbmaLog /></template>
    <template #Timer><IbmaTimer /></template>
  </IbmaTabs>
</template>

<style lang="scss" scoped>
.ibma-box {
  margin-right: 24px;
  border-radius: 4px;
  background-color: var(--o-bg-color-base);

  .part {
    .content {
      position: relative;
      display: flex;
      padding: 24px;
      border-radius: 4px;
      .update-top {
        position: absolute;
        top: -4px;
        left: 0px;
        display: flex;
      }
      .update {
        height: 32px;
        background: var(--o-color-state-primary);
        border-radius: 4px 0 4px 0;
        padding: 8px 12px;
        font-family: HarmonyOS_Sans_SC_Medium;
        font-size: 12px;
        color: #fffffe;
        letter-spacing: 0;
        line-height: 16px;
      }
      .triangle {
        width: 0;
        height: 0;
        border-right: 4px solid transparent;
        border-bottom: 4px solid #004db9;
      }
      .system-title {
        width: 200px;
        text-align: center;
        .left-text {
          margin-bottom: 8px;
          font-weight: 600;
        }
      }
      .left {
        margin-right: 24px;
      }

      .left,
      .right {
        .item {
          margin-bottom: 16px;
        }

        .item:nth-last-child(1) {
          margin-bottom: 0;
        }

        .key {
          color: var(--o-text-color-secondary);
        }

        .value {
          color: var(--o-text-color-primary);
        }

        .special-item {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
          }

          .no-success-icon {
            :deep(svg path:nth-child(1)) {
              fill: #c3cedf;
            }
          }
        }

        .end-item {
          margin-bottom: 0;
        }
      }
    }
  }

  :deep(.el-overlay) {
    .el-dialog {
      width: 656px;
    }

    .table-bx {
      padding: 8px 16px 16px;
      background-color: var(--o-bg-color-light);
      border-radius: 4px;

      .el-table--border {
        background-color: rgba(0, 0, 0, 0);

        tr,
        th {
          background-color: rgba(0, 0, 0, 0);
        }

        .el-table__body-wrapper {
          .el-table__body {
            td {
              padding-top: 9px;
              padding-bottom: 9px;
            }
          }
        }
      }
    }

    .des {
      line-height: 16px;
      margin-bottom: 8px;
    }

    .help {
      margin-top: 8px;
    }
  }
}
.upload-system-icon {
  width: 40px;
  height: 32px;
  background-size: contain;
  margin: 0 auto;
  margin-bottom: 16px;
}
.system-icon {
  width: 32px;
  height: 32px;
  background-size: contain;
  margin: 0 auto;
  margin-bottom: 16px;
}
.upload-img {
  background: url(@/assets/assets-bmc/default/ibma-upload.svg) no-repeat;
}
.restart-img {
  background: url(@/assets/assets-bmc/default/system_software.svg) no-repeat;
}
.vertical {
  height: auto;
}
.right-box-upload {
  width: 80%;
  display: flex;
  justify-content: space-around;
  .fixedBox {
    width: 20%;
    display: flex;
    align-items: center;
  }
}
.right-box {
  width: 80%;
  display: flex;
  justify-content: space-around;
  .fixedBox {
    width: 20%;
    display: flex;
    align-items: center;
  }
}
.ibma-status-box {
  margin-top: 8px;
  margin-right: 24px;
  border-radius: 4px;
  background-color: var(--o-bg-color-base);

  .part {
    .content {
      display: flex;
      padding: 24px;
      border-radius: 4px;
      .system-title {
        width: 200px;
        align-items: center;
        justify-content: center;
        display: flex;
        .left-text {
          text-align: center;
          font-weight: 600;
        }
      }
      .left {
        margin-right: 24px;
      }

      .left,
      .right {
        .item {
          margin-bottom: 16px;
        }

        .item:nth-last-child(1) {
          margin-bottom: 0;
        }

        .key {
          color: var(--o-text-color-secondary);
        }

        .value {
          color: var(--o-text-color-primary);
        }

        .special-item {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
          }

          .no-success-icon {
            :deep(svg path:nth-child(1)) {
              fill: #c3cedf;
            }
          }
        }

        .end-item {
          margin-bottom: 0;
        }
      }
    }
  }

  .version {
    margin-bottom: 24px;
  }

  :deep(.el-overlay) {
    .el-dialog {
      width: 656px;
    }

    .table-bx {
      padding: 8px 16px 16px;
      background-color: var(--o-bg-color-light);
      border-radius: 4px;

      .el-table--border {
        background-color: rgba(0, 0, 0, 0);

        tr,
        th {
          background-color: rgba(0, 0, 0, 0);
        }

        .el-table__body-wrapper {
          .el-table__body {
            td {
              padding-top: 9px;
              padding-bottom: 9px;
            }
          }
        }
      }
    }

    .des {
      line-height: 16px;
      margin-bottom: 8px;
    }

    .help {
      margin-top: 8px;
    }
  }
}
</style>
