<script setup lang="ts">
import { reactive, ref } from 'vue';
import { getErrorTranslate, traduction } from '@/utils/language';
import { VALID_BASELINE } from '@/utils/regular';
import { updateService } from '@/pages/User/Tpcm/tpcm.service';
import { getMessageId, showElMessage } from '@/utils/utils';
import { getStoreData, showFailedMessage } from '@/utils/composition';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';

const props = defineProps<{
  srcData: any;
  isPrivileges: any;
  isSystemLock: boolean;
  tsbEnableStatus: number;
  tpcmConfigData: {
    initMeasureState: boolean;
    initControlState: boolean;
    initAlertMeasureState: boolean;
    initAlertControlState: boolean;
  };
}>();

const emit = defineEmits(['updateDetail']);

const privil = getStoreData('loct', 'privil');
const hasConfigUsers = privil.includes('UserConfigEnabled');
const updateBasicRef = ref();
const updateBoxVisible = ref(false);
const updateBoxBasicVisible = ref(false);
let updateTip: string = '';
const updateSave = ref(true);
const baselinePreValue = ref('');
const passwordDialog = ref();
let param = reactive<any>({});
const noPwd = getStoreData('loct', 'nopwd');

const basicForm = reactive({
  baselinePreValue: '',
});

let updateItem = reactive({
  MeasuredObject: '',
  ActualDigest: '',
});

const updateBox = reactive({
  title: 'TPCM_UPDATE',
  content: '',
  id: 'updateBox',
});

const basicRules = reactive({
  baselinePreValue: [
    { validator: baseValid, message: traduction('COMMON_FORMAT_ERROR'), trigger: 'blur' },
  ],
});

function baseValid(rule: any, value: any, callback: any) {
  if (value === '') {
    return null;
  }
  const result = VALID_BASELINE.test(value);
  return result;
}

function showUpdateBox(item: any) {
  if (!item.ActualDigest) {
    updateSave.value = false;
  }

  if (props.isSystemLock || !hasConfigUsers) {
    return;
  }
  if (item.MeasuredObject === 'Bios') {
    updateTip = 'TPCM_UPDATE_BIOS_TIP';
  } else {
    updateTip = 'TPCM_UPDATE_OTHER_TIP';
  }
  updateItem = item;
  basicForm.baselinePreValue = item.ActualDigest;
  updateBoxVisible.value = true;
  updateBoxBasicVisible.value = true;
}

function generateBaselineData(): void {
  if (
    !baseValid([], basicForm.baselinePreValue, '') ||
    !basicForm.baselinePreValue ||
    !updateItem.ActualDigest
  ) {
    updateSave.value = false;
  } else {
    updateSave.value = true;
  }
}

function saveTpcmUpdate(params: { [key: string]: any }) {
  param = {};
  if (!noPwd) {
    param.ReauthKey = window.btoa(params.password);
  }

  const successText =
    params.measuredObject === 'Bios' ? 'TPCM_UPDATE_BIOS_SUCCESS' : 'TPCM_UPDATE_OTHER_SUCCESS';
  getFirmwareParameter(params.measuredObject);

  updateService(param)
    .then((res: any) => {
      showElMessage('success', traduction(successText));
      emit('updateDetail', true);
    })
    .catch((error: any) => {
      const errors = getMessageId(error.data);
      if (error && errors?.length > 0) {
        const errorId = errors[0].code;
        const errorMsg = getErrorTranslate(errorId as string);
        showFailedMessage(errorMsg);
      }
    });
  passwordDialog.value.hide();
}


function pswSave(res: { reason: boolean; password: string }) {
  if (res.reason) {
    saveTpcmUpdate({ measuredObject: updateItem.MeasuredObject, password: res.password });
  } else {
    passwordDialog.value.hide();
  }
}


function updateClose(type: string) {
  if (noPwd) {
    saveTpcmUpdate({ measuredObject: updateItem.MeasuredObject });
  } else if (type === 'save') {
    passwordDialog.value.show();
  } else {
    baselinePreValue.value = updateItem.ActualDigest;
    updateSave.value = true;
  }
  updateBoxBasicVisible.value = false;
}

function getFirmwareParameter(item: string) {
  const resultArr = [
    {
      name: 'Bios',
      paramKey: 'BiosStandardDigest',
    },
    {
      name: 'Shim',
      paramKey: 'ShimStandardDigest',
    },
    {
      name: 'Grub',
      paramKey: 'GrubStandardDigest',
    },
    {
      name: 'Grub.Cfg',
      paramKey: 'GrubCfgStandardDigest',
    },
    {
      name: 'Kernel',
      paramKey: 'KernelStandardDigest',
    },
    {
      name: 'Initrd',
      paramKey: 'InitrdStandardDigest',
    },
  ];
  resultArr.forEach((ele, i) => {
    if (ele.name === item) {
      param[ele.paramKey] = basicForm.baselinePreValue;
    }
  });
}
</script>

<template>
  <el-alert
    v-if="
      tsbEnableStatus !== 0 &&
        srcData.data &&
        srcData.data.length &&
        tpcmConfigData.initMeasureState
    "
    :title="$t('TPCM_BASELINE_TIP')"
    type="info"
    show-icon
    :closable="false"
  />
  <div id="sensorTableComponent">
    <el-table
      v-if="tsbEnableStatus !== 0 && tpcmConfigData.initMeasureState"
      v-addId.table="'tableComponent'"
      :data="srcData.data"
      border
      resizable
    >
      <el-table-column min-width="75" :label="$t('TPCM_MEASURED_TARGET')">
        <template #default="scope">
          <span class="id">
            {{ scope.row.MeasuredObject === '' ? '- -' : scope.row.MeasuredObject }}
          </span>
        </template>
      </el-table-column>
      <el-table-column min-width="75" show-overflow-tooltip :label="$t('TPCM_VERSION')">
        <template #default="scope">
          <span class="id">{{ scope.row.Version === '' ? '- -' : scope.row.Version }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="75" :label="$t('TPCM_PLATFORM_STATUS_REGISTER')">
        <template #default="scope">
          <span>{{ scope.row.PCR === '' ? '- -' : scope.row.PCR }}</span>
        </template>
      </el-table-column>
      <el-table-column
        min-width="75"
        :label="$t('TPCM_ACTUAL_MEASUREMENT_VALUE')"
      >
        <template #default="scope">
          <span v-addTooltip.td class="overFlow">
            {{ scope.row.ActualDigest === '' ? '- -' : scope.row.ActualDigest }}
          </span>
        </template>
      </el-table-column>
      <el-table-column min-width="75" :label="$t('TPCM_BASE_VALUE')">
        <template #default="scope">
          <span v-addTooltip.td class="overFlow">
            {{ scope.row.StandardDigest === '' ? '- -' : scope.row.StandardDigest }}
          </span>
        </template>
      </el-table-column>
      <el-table-column min-width="50" :label="$t('TPCM_CONSISTENCY')">
        <template #default="scope">
          <el-tag :type="scope.row.IsMatch ? 'success' : 'danger'">
            <span
              class="match-text"
              :class="{ 'item-pass': scope.row.IsMatch, 'item-no-pass': !scope.row.IsMatch }"
            >
              {{ scope.row.IsMatch ? $t('TPCM_TRUST_YES') : $t('TPCM_TRUST_NO') }}
            </span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column min-width="75" :label="$t('TPCM_BASE_VALUE_UPDATE')">
        <template #default="scope">
          <span
            v-if="
              ['TPCM_FW', 'UBoot', 'Rootfs', 'Coprocessor']
                .every(item => !scope.row.MeasuredObject.includes(item))
            "
            :id="'update' + scope.row.id"
            class="update"
            :class="{ disabled: isSystemLock || !isPrivileges }"
            @click="showUpdateBox(scope.row)"
          >
            {{ $t('TPCM_UPDATE') }}
          </span>
        </template>
      </el-table-column>
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
  </div>
  <div v-if="tsbEnableStatus === 0" class="noStartService">
    <img class="monitorChartNoData" src="@/assets/common/image/no-data.svg" />
    <div class="noDataText">{{ $t('TPCM_TRUST_MESURE_OFF_TEXT') }}</div>
  </div>
  <div v-if="!tpcmConfigData.initMeasureState && tsbEnableStatus !== 0" class="noStartService">
    <img class="monitorChartNoData" src="@/assets/common/image/no-data.svg" />
    <div class="noDataText">{{ $t('TPCM_TRUST_MESURE_OFF_TEXT') }}</div>
  </div>

  <div v-if="updateBoxVisible" v-reqKeepAlive.dialog>
    <el-dialog
      :id="updateBox.id"
      v-model="updateBoxBasicVisible"
      :title="$t(updateBox.title)"
      width="30%"
    >
      <div>
        <el-alert
          :title="$t(updateTip)"
          type="info"
          show-icon
          :closable="false"
          class="alertDiv"
        />
        <el-form ref="updateBasicRef" label-width="auto" :rules="basicRules" :model="basicForm">
          <el-form-item :label="$t('TPCM_BASE_VALUE_LABEL')" prop="baselinePreValue">
            <el-input
              id="baselineVal"
              v-model="basicForm.baselinePreValue"
              clearable
              maxlength="64"
              @change="generateBaselineData"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span>
          <el-button
            id="webOkBtn"
            type="primary"
            :disabled="!updateSave"
            @click="updateClose('save')"
          >
            {{ $t('COMMON_SAVE') }}
          </el-button>
          <el-button id="webCancelBut" @click="updateClose('cancel')">
            {{ $t('ALARM_CANCEL') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <SecondPassword ref="passwordDialog" @close="pswSave" />
  </div>
</template>

<style lang="scss" scoped>
#sensorTableComponent {
  margin-top: 16px;
  :deep(.el-tag) {
    min-width: 40px !important;
  }
}
.noDataBox {
  padding-top: 48px;
  text-align: center;
  font-size: 14px;
  color: #727885;
  .noData {
    text-align: center;
    background: url('@/assets/common/image/no-data.svg') no-repeat center center;
    width: 100%;
    height: 100px;
    margin-bottom: 12px;
  }
}
.noStartService {
  margin-top: 50px;
  text-align: center;
  .monitorChartNoData {
    opacity: 0.7;
  }
}
.noDataText {
  color: #9ea4b3;
  font-size: 14px;
  margin-top: 17px;
}
.update {
  margin-right: 14px;
  color: var(--o-color-primary);
  cursor: pointer;
  &:hover {
    color: var(--o-color-primary-secondary);
  }
  &.disabled {
    color: #999;
    cursor: not-allowed;
    text-decoration: none;
  }
}
#baselineTip {
  width: 100%;
}

.match-text {
  font-size: 12px;
  color: var(--el-color-white);
  letter-spacing: 0;
  line-height: 12px;
}

.alertDiv {
  margin-bottom: 16px;
}
</style>