<template>
  <div class="tables">
    <el-upload
      id="rootCertUploadId"
      :disabled="systemLock"
      :name="uploadConfig.data.name"
      :action="rootUpload.data.action"
      :method="rootUpload.data.method"
      :headers="rootUpload.data.headers"
      :accept="rootUpload.data.accept"
      :auto-upload="rootUpload.data.isAutoUpload"
      :show-file-list="rootUpload.data.showList"
      :on-success="rootUpload.data.onSuccess"
      :on-error="rootUpload.data.onError"
      :before-upload="rootUpload.data.onAddItem"
    >
      <el-button id="rootCertUploadBtn" :disabled="systemLock">
        {{ $t('COMMON_CER_UPLOAD') }}
      </el-button>
    </el-upload>

    <el-table
      v-addId.table="'rootTableId'"
      :data="tableData"
      style="width: 100%"
      border
      resizable
      :class="{ 'empty-table': tableData.length === 0 }"
      :row-class-name="setRowClass"
    >
      <el-table-column type="expand">
        <template #default="scope">
          <p class="table-details-title">{{ $t('FDM_INFO') }}</p>
          <div :id="`certDetailForm${scope.row.certId}`" class="table-details">
            <div class="certDetail">
              <el-form label-position="left" label-width="auto">
                <el-form-item
                  :id="`issueByItem${scope.row.certId}`"
                  :label="$t('TWO_FACTORS_ISSUEDBY')"
                >
                  <span>{{ scope.row.issueBy }}</span>
                </el-form-item>
                <el-form-item
                  :id="`validItem${scope.row.certId}`"
                  :label="$t('TWO_FACTORS_EFFICTIVE_DATE')"
                >
                  <span>{{ scope.row.valid }}</span>
                </el-form-item>
                <el-form-item
                  v-if="scope.row.isImportCrl"
                  :id="`crlValidItem${scope.row.certId}`"
                  :label="$t('TWO_FACTORS_REVOCATION_LIST')"
                >
                  <span>{{ scope.row.crlValid }}</span>
                </el-form-item>
                <el-form-item
                  v-if="scope.row.isImportCrl"
                  :id="`isImportCrlItem${scope.row.certId}`"
                >
                  <template #label>
                    <span>{{ $t('TWO_FACTORS_REVOCATION_LIST') }}</span>
                    <HelpIcon
                      :id="'controlMethod'"
                      :tips="traduction('TWO_FACTORS_REVOCATION_LIST_TIP')"
                    ></HelpIcon>
                  </template>
                  <span>{{ scope.row.crlValid }}</span>
                </el-form-item>
              </el-form>
            </div>
            <div class="certDetail">
              <el-form label-position="left">
                <el-form-item
                  :id="`issueToItem${scope.row.certId}`"
                  :label="$t('TWO_FACTORS_ISSUEDTO')"
                >
                  <span>{{ scope.row.issueTo }}</span>
                </el-form-item>
                <el-form-item
                  :id="`serialNumberItem${scope.row.certId}`"
                  :label="$t('COMMON_SERIALNUMBER')"
                >
                  <span>{{ scope.row.serialNumber }}</span>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TWO_FACTORS_CERTIFICATES_ID')">
        <template #default="scope">
          <span class="twofactor-root-id">{{ scope.row.certId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TWO_FACTORS_ISSUEDBY')">
        <template #default="scope">
          <span class="twofactor-root-issue-by">{{ scope.row.issueByCN }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TWO_FACTORS_ISSUEDTO')">
        <template #default="scope">
          <span class="twofactor-root-issue-to">{{ scope.row.issueToCN }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TWO_FACTORS_DEADLING')">
        <template #default="scope">
          <span class="twofactor-root-valid">{{ scope.row.validTo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TWO_FACTORS_CRL')" class-name="twofactor-root-crl">
        <template #default="scope">
          <span v-if="scope.row.isImportCrl === true" class="crlState configured">
            <span v-t="'COMMON_CONFIGURED'"></span>
          </span>
          <span v-if="scope.row.isImportCrl === false" class="crlState unconfigured">
            <span v-t="'COMMON_UNCONFIGURED'"></span>
          </span>
          <span v-if="scope.row.revokedState === null" class="crlState">--</span>
          <div :id="`crlUploadId${scope.row.certId}`" v-privil.userConfig class="crlUploadBox">
            <el-upload
              v-if="!systemLock"
              class="crlUpload"
              :data="uploadConfig.data.data"
              :name="uploadConfig.data.name"
              :action="uploadConfig.data.action"
              :method="uploadConfig.data.method"
              :headers="uploadConfig.data.headers"
              :accept="uploadConfig.data.accept"
              :show-file-list="uploadConfig.data.showList"
              :on-success="uploadConfig.data.onSuccess"
              :on-error="uploadConfig.data.onError"
              :before-upload="uploadConfig.data.onAddItem"
            >
              <span
                :id="`crlUploadId${scope.row.certId}`"
                class="crlUpload"
                @click="clickUpload(scope.row.certId)"
              >
                {{ $t('COMMON_UPLOAD') }}
              </span>
              <template #tip></template>
            </el-upload>
            <span
              v-if="systemLock"
              :id="`crlUploadId${scope.row.certId}`"
              class="crlUpload disabled-btn"
            >
              {{ $t('COMMON_UPLOAD') }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('COMMON_OPERATE')" class-name="twofactor-root-operate">
        <template #default="scope">
          <span
            :id="`rootCertDelId${scope.row.certId}`"
            v-t="'COMMON_DELETE'"
            class="rootCertDel"
            :class="{ disabled: canNotDeleted || systemLock }"
            @click="delRootCertClick(scope.row.certId)"
          ></span>
        </template>
      </el-table-column>
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
    <el-pagination
      v-if="tableData.length > 0"
      v-model:currentPage="currentPage"
      v-addId.pagination="'rootPagination'"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
  <Dialog ref="dialog" :config="diaginfo" @close="dialogClose"></Dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { traduction } from '@/utils/language';
import { delRootCert, getTwoFactoryData, rootCertInfoAssemble } from '../twoFactor.service';
import { UploadFile } from 'element-plus/es/components/upload/src/upload';
import Dialog from '@/components/Dialog/Dialog.vue';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import useStore from '@/stores';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import {
  getStoreData,
  loading,
  setStoreData,
  showFailedMessage,
  showSuccessMessage,
} from '@/utils/composition';
import { escapeHeader } from '@/utils/utils';
const store = useStore();
let systemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const emit = defineEmits(['updata']);
const dialog = ref();
const tableDataRoot = reactive({
  data: [
    {
      certId: 1,
      issueBy: '',
      issueByCN: '',
      issueTo: '',
      issueToCN: '',
      validFrom: '',
      validTo: '',
      valid: '',
      crlValidFrom: '',
      crlValidTo: '',
      crlValid: '--',
      isImportCrl: false,
      serialNumber: '',
      isCRLUpload: false,
    },
  ],
});
const diaginfo = reactive({
  id: '',
  type: '',
  content: '',
  title: '',
});
const canNotDeleted = ref(false);
const defaultCurrentPage = 1;
const defaultPageSize = 10;
const currentPage = ref(defaultCurrentPage);
const pageSize = ref(defaultPageSize);
const pageSizes = ref([10, 20, 30, 50]);
const layout = ref('total, sizes, prev, pager, next, jumper');
const total = ref(0);
const dialogVisible = ref(false);
let delParam: any;
const tableData: any = ref([]);
function handleSizeChange(val: number) {
  pageSize.value = val;
  getData();
}
function handleCurrentChange() {
  getData();
}
function getData() {
  tableData.value = tableDataRoot.data.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value,
  );
}
function rootCertificateInit(resData: any) {
  canNotDeleted.value = resData.TwoFactorAuthenticationEnabled;
  tableDataRoot.data = rootCertInfoAssemble(resData);
  total.value = tableDataRoot.data.length;
  getData();
}
function delRootCertClick(certId: number) {
  if (systemLock.value || canNotDeleted.value) {
    return;
  }
  delParam = {
    CertificateType: 0,
    ID: certId,
  };
  diaginfo.id = 'delRoot';
  diaginfo.type = 'warning';
  diaginfo.title = traduction('COMMON_CONFIRM');
  diaginfo.content = traduction('TWO_FACTORS_DELETE_CERTIFICATE_TIP');
  dialog.value.show();
}
function dialogClose(val: boolean) {
  dialog.value.hide();
  if (val) {
    loading(true);
    delRootCert(delParam)
      .then(() => {
        loading(false);
        showSuccessMessage();
        init();
      })
      .catch(() => {
        loading(false);
        showFailedMessage();
      });
  }
}

const uploadConfig = reactive({
  data: {
    action: '/UI/Rest/AccessMgnt/TwoFactorAuthentication/ImportCrlCertificate',
    headers: {
      From: 'WebUI',
      'X-CSRF-Token': escapeHeader(getStoreData('loct', 'to')),
    },
    method: 'POST',
    name: 'Content',
    data: { CertID: '' } as any,
    isAutoUpload: true,
    accept: '.crl',
    showList: false,
    onAddItem: (file: UploadFile) => {
      let type = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (type !== 'crl') {
        showFailedMessage(traduction('COMMON_FILE_SUFFIX_CRL'));
        return false;
      } else if ((file.size as any) > 102400) {
        showFailedMessage(traduction('COMMON_UPLOAD_FILE_MORN_100KB_ERROR4'));
        return false;
      }
      return true;
    },
    onError: (error: any, file: UploadFile): void => {
      const errorCode = JSON.parse(error.message).error[0].code;
      if (errorCode === 'NoValidSession') {
        setStoreData(
          'event',
          'error401',
          `${traduction('SessionTimeout.errorMessage')}${Date.now()}`,
        );
      } else {
        showFailedMessage(traduction(errorCode + '.errorMessage'));
      }
    },
    onSuccess: (response: any, file: UploadFile): void => {
      showSuccessMessage();
      emit('updata');
      init();
    },
  },
});

const rootUpload = reactive({
  data: {
    action: '/UI/Rest/AccessMgnt/TwoFactorAuthentication/ImportRootCertificate',
    headers: {
      From: 'WebUI',
      'X-CSRF-Token': escapeHeader(getStoreData('loct', 'to')),
    },
    method: 'POST',
    name: 'Content',
    isAutoUpload: true,
    accept: '.cer,.pem,.crt',
    showList: false,
    onAddItem: (file: UploadFile) => {
      let type = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!['cer', 'pem', 'crt'].includes(type)) {
        showFailedMessage(traduction('COMMON_FILE_SUFFIX_CER_PEM_CRT'));
        return false;
      } else if ((file.size as any) > 1024 * 1024) {
        showFailedMessage(traduction('COMMON_UPLOAD_FILE_MORN_1M_ERROR'));
        return false;
      }
      loading(true);
      return true;
    },
    onError: (error: any): void => {
      loading(false);
      const errorCode = JSON.parse(error.message).error[0].code;
      if (errorCode === 'NoValidSession') {
        setStoreData(
          'event',
          'error401',
          `${traduction('SessionTimeout.errorMessage')}${Date.now()}`,
        );
      } else {
        showFailedMessage(traduction(errorCode + '.errorMessage'));
      }
    },
    onSuccess: (response: any, file: UploadFile): void => {
      loading(false);
      showSuccessMessage();
      emit('updata');
      init();
    },
  },
});
function clickUpload(certId: number) {
  if (systemLock.value) {
    return;
  }
  uploadConfig.data.data.CertID = certId;
}
function setRowClass(item: any) {
  const { row } = item;
  return `twofactor-root-row-${row.certId}`;
}
function init() {
  getTwoFactoryData().then((response: any) => {
    const resData = response['data'];
    rootCertificateInit(resData);
  });
}
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.tables {
  padding: 16px;
  background-color: var(--o-bg-color-base);
  position: relative;

  :deep(.el-pagination) {
    margin-top: 16px;
  }
}

.table-details {
  display: flex;
  padding: 8px 40px;
  justify-content: space-between;
  > div {
    width: calc(100% - 32px);
    .el-form-item {
      margin-bottom: 0;
    }
    :deep(.el-form-item__label) {
      max-width: 180px;
    }
  }
  :deep(.el-table__expanded-cell) {
    background-color: var(--o-bg-color-light);
  }
  :deep(.el-form-item__content) {
    color: var(--o-text-color-primary);
  }
}
.table-details-title {
  font-size: 12px;
  color: var(--o-text-color-primary);
  line-height: 16px;
  font-weight: bold;
  padding-left: 40px;
}
:deep(.el-table td.el-table__cell.el-table__expanded-cell) {
  border-bottom: none;
  background-color: var(--o-bg-color-light);
}
:deep(.el-table td.el-table__cell.el-table__expanded-cell:hover) {
  border-bottom: none;
  background-color: var(--o-bg-color-light);
}
.crlUpload {
  color: var(--o-color-primary);
  cursor: pointer;
  margin-right: 8px;
  :hover {
    color: var(--o-color-primary-secondary);
  }
}
.rootCertDel {
  color: var(--o-color-primary);
  cursor: pointer;
  &:hover {
    color: var(--o-color-primary-secondary);
  }
}
.rootCertDel.disabled {
  color: var(--o-text-color-primary);
  cursor: not-allowed;
  &:hover {
    color: var(--o-text-color-primary);
  }
}
.crlUploadBox {
  display: inline-block;
  vertical-align: middle;
}
#rootCertUploadId {
  margin-bottom: 16px;
}
.crlState {
  display: inline-block;
  min-width: 64px;
  padding: 0 4px;
  height: 16px;
  border-radius: var(--i-button-border-radius);
  background-color: var(--o-text-color-tertiary);
  color: #fff;
  line-height: 16px;
  text-align: center;
  font-size: 12px;
  vertical-align: middle;
  &.configured {
    background-color: var(--o-color-success);
  }
}
.layout-patination {
  margin-left: 0;
}
.crlUploadBox {
  margin-left: 8px;
}
:deep(.empty-table) {
  .el-table__body-wrapper {
    height: 450px !important;
  }
}
.el-table {
  min-height: 430px;
}
</style>
