<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { showElMessage } from '@/utils/utils';
import { refreshHardwareBase } from '../tpcm.service';
import { getErrorTranslate, traduction } from '@/utils/language';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import useStore from '@/stores';
import { getStoreData, showFailedMessage } from '@/utils/composition';
import Dialog from '@/components/Dialog/Dialog.vue';
import { detailKeyList, IdentityEntry, getDetailLabel, miniViewDetailKeyList, getStateStyleClass, getStatusLabel } from '../tpcm.datatype';
import { SecondAuthorityFail } from '@/model/base-enum';

const secondRef = ref();
const dialogRef = ref();
const viewWidth = ref<number>(0);
let resizeObserver: ResizeObserver | null = null;
const store = useStore();
const i18n = useI18n();
const nopwd = getStoreData('loct', 'nopwd');
const langOptions = computed(() => {
  return store.state.glob.langOptions;
});
const curLang = langOptions.value.filter((lang: any) => lang.id === i18n.locale.value)[0].id;

const props = defineProps<{
  srcData: {
    data: IdentityEntry[];
    [propKey: string]: any;
  };
}>();

const dialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
  id: 'hardwareDialog',
  alignItems: 'center',
});

function resetBtnClick(context: { reason: boolean; password: string }): void {
  const { reason, password } = context;
  if (reason) {
    refreshHardwareBase(password)
      .then((_: never) => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
        secondRef.value.hide();
      })
      .catch((error: any) => {
        let errorCode = error?.data?.error?.[0]?.code ?? 'COMMON_FAILED';
        if ([SecondAuthorityFail.REAUTHFAILED, SecondAuthorityFail.AUTHORIZATIONFAILED].includes(errorCode)) {
          secondRef.value.setErrorId();
          secondRef.value.clearPassword();
          showFailedMessage(getErrorTranslate(errorCode));
          return;
        } 
        if (errorCode === 'ActionNotSupported') {
          errorCode = 'ActionNotSupportedPowerOff';
        }
        showFailedMessage(getErrorTranslate(errorCode));
        secondRef.value.hide();
      });
  } else {
    secondRef.value.hide();
  }
}

function handleDialogClose(): void {
  refreshHardwareBase()
    .then((_: never) => {
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch((error: any) => {
      let errorCode = error?.data?.error?.[0]?.code ?? 'COMMON_FAILED';
      if (errorCode === 'ActionNotSupported') {
          errorCode = 'ActionNotSupportedPowerOff';
      }
      showFailedMessage(getErrorTranslate(errorCode));
    })
    .finally(() => {
      dialogRef.value.hide();
    });
}

function handleBtnClick(): void {
  if (nopwd) {
    dialogRef.value.show();
  } else {
    secondRef.value.show();
  }
}

function getColumn(): number {
  switch (curLang) {
    case 'zh':
      if (viewWidth.value > 1800) {
        return 3;
      } else if (viewWidth.value > 1350) {
        return 2;
      } else {
        return 1;
      }
    case 'en':
    case 'ja':
      if (viewWidth.value > 1800) {
        return 3;
      } else if (viewWidth.value > 1500) {
        return 2;
      } else {
        return 1;
      }
    case 'fr':
    case 'ru':
      if (viewWidth.value > 2000) {
        return 3;
      } else if (viewWidth.value > 1500) {
        return 2;
      } else {
        return 1;
      }
    default:
      return 3;
  }
}

onMounted(() => {
  resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
      const { width } = entry.contentRect;
      viewWidth.value = Math.round(width);
    }
  });

  resizeObserver.observe(document.body);
});

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.unobserve(document.body);
    resizeObserver.disconnect();
  }
});

</script>

<template>
  <el-alert
    :title="$t('TPCM_HARDWARE_TIP')"
    type="info"
    show-icon
    :closable="false"
  ></el-alert>
  <el-button class="refreshBtn" type="primary" @click="handleBtnClick">{{ $t('TPCM_UPDATE_BTN') }}</el-button>
  <el-table :data="props.srcData.data">
    <el-table-column type="expand">
      <template #default="scope">
        <div class="detail" v-for="detail of scope.row.details" :key="detail.name">
          <p class="deviceTitle">{{ detail.name }}</p>
          <el-descriptions size="small" :column="getColumn()">
            <el-descriptions-item
              min-width="200px"
              v-for="key of (getColumn() === 3 ? detailKeyList : miniViewDetailKeyList)"
              :label="$t(getDetailLabel(key))"
              :key="`${detail.name}-${key}`"
            >
              <template v-if="key === 'status'">
                <el-tag :type="getStateStyleClass(detail[key])">
                  <span :id="`${detail.name}-${key}`">{{ $t(getStatusLabel(detail[key])) }}</span>
                </el-tag>
              </template>
              <template v-else>
                <span :id="`${detail.name}-${key}`">{{ detail[key] }}</span>
              </template>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </template>
    </el-table-column>
    <el-table-column min-width="65%" :label="$t('COMMON_DEVICE_TYPE')">
      <template #default="scope">
        {{ $t(`TPCM_PART_${scope.row.name.toUpperCase()}`) }}
      </template>
    </el-table-column>
    <el-table-column min-width="35%" :label="$t('TPCM_CONSISTENCY')">
      <template #default="scope">
        <el-tag :type="scope.row.comparedResult === 0 ? 'success' : 'danger'">
          {{ $t(scope.row.comparedResult === 0 ? 'COMMON_YES' : 'COMMON_NO') }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
  <SecondPassword v-if="!nopwd" ref="secondRef" @close="resetBtnClick" />
  <Dialog v-else ref="dialogRef" :config="dialogConfig" @close="handleDialogClose"></Dialog>
</template>

<style scoped lang="scss">
.refreshBtn {
  margin: 16px 0;
}
.deviceTitle {
  font-size: 12px !important;
  padding-left: 16px;
  font-weight: 600;
  padding-bottom: 8px;
}
.detail:not(:first-child) {
  margin-top: 8px;
}
:deep(.el-descriptions__body) {
  background-color: transparent !important;
}
:deep(.el-descriptions__table tr) {
  background: transparent !important;
}
:deep(.el-tag) {
  min-width: 40px !important;
}
</style>