<script lang="ts" setup>
import { traduction } from '@/utils/language';
import { ref, onMounted, computed } from 'vue';

import { showElMessage } from '@/utils/utils';
import GlobalStoreService from '@/services/gloabal-store-service';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import { IconSuccess } from '@computing/opendesign-icons';
import { editUsbData, getUsbData } from './usb.server';

const globalStoreService = new GlobalStoreService();
const successMsg = traduction('COMMON_SUCCESS');
const errorMsg = traduction('COMMON_FAILED');

const store = useStore();
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const hasBasicConfig = checkPrivil(UserPrivil.baseConfig);
const enableStatus = ref(false);
const usbSystemStatus = ref(false);
// 获取数据
function getData() {
  globalStoreService.setValue('isLoading', true);
  getUsbData()
    .then((data: any) => {
      enableStatus.value = data.ServiceEnabled;
      usbSystemStatus.value = data.USBDevicePresence;
      globalStoreService.setValue('isLoading', false);
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
    });
}

onMounted(() => {
  // 获取数据
  getData();
});

function save() {
  editUsbData({ ServiceEnabled: enableStatus.value })
    .then((data: any) => {
      enableStatus.value = data.ServiceEnabled;
      usbSystemStatus.value = data.USBDevicePresence;
      showElMessage('success', successMsg);
    })
    .catch(() => {
      showElMessage('error', errorMsg);
    });
}
</script>

<template>
  <div id="usbContentId" class="usb-box">
    <el-form label-position="left" label-width="auto">
      <el-form-item :label="$t('IBMC_USB_ENABLED')">
        <el-switch
          id="usbEnable"
          v-model="enableStatus"
          :disabled="!hasBasicConfig || isSystemLock"
          @change="save()"
        ></el-switch>
      </el-form-item>
      <el-form-item :label="$t('IBMC_USB_PORT')">
        <el-icon id="picGteenSucceed" :size="16" :class="{ 'not-detected': !usbSystemStatus }">
          <IconSuccess />
        </el-icon>
        <span class="status-text">
          {{ usbSystemStatus ? $t('IBMC_USB_DETECTED') : $t('IBMC_USB_NOTDETECTED') }}
        </span>
      </el-form-item>
    </el-form>
  </div>
</template>

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

  .el-form-item {
    height: 16px;
  }
  .status-text {
    margin-left: 8px;
  }

  :deep(.el-form) {
    .el-form-item__label {
      padding: 0 24px 0 0;
    }

    .not-detected svg path:first-child {
      fill: var(--o-border-color-lighter);
    }

    .status-text {
      line-height: 16px;
    }
  }
}
</style>
