<script setup lang="ts">
import { traduction, getErrorTranslate } from '@/utils/language';
import { ref, reactive, computed, onMounted } from 'vue';
import useStore from '@/stores';
import { IUpgradeFile } from '@/model/Manager/upgrade-interface';
import CustomAert from '@/components/CustAlert/CustAlert.vue';
import FileUpload from '@/components/FileUpload/FileUpload.vue';
import { getFileList, uploadFile, delSPUpdateFileList } from '../../upgrade.services';
import { reqPath } from '@/api/reqPath';
import { UploadFile } from 'element-plus/es/components/upload/src/upload';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import { loading } from '@/utils/composition';
import Dialog from '@/components/Dialog/Dialog.vue';
import { showElMessage, getMessageId, escapeHeader } from '@/utils/utils';
import { useRouter } from 'vue-router';
import { IconSuccess } from '@computing/opendesign-icons';

const store = useStore();
const router = useRouter();
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const loct = localStorage.getItem('loct');
const fileList: IUpgradeFile[] = reactive([]);
const alertInfo = traduction('IBMC_UPGRADE_UPLOAD_TP');
const upgradeRef = ref();
const signatureRef = ref();
const dialogRef = ref();
const spDialogRef = ref();

// 保存按钮状态
let upgradeDisabled = ref(true);
let signatureDisabled = ref(true);
let upgradeFileAddError: boolean = false;
let signatureFileAddError: boolean = false;

// 文件上传
let upgradeErrorTips: string = '';
let upgradeFormData: any;
let signatureErrorTips: string = '';
let signatureFormData: any;
const upgradeConfig = reactive({
  action: reqPath.ibmc.SPFWUpdate,
  headers: {
    'X-CSRF-Token': escapeHeader(loct ? JSON.parse(loct).to : ''),
    From: 'WebUI',
    Accept: '*/*',
  },
  id: 'fileUploadUpgrade',
  width: 320,
  disabled: isSystemLock,
  method: 'POST',
  name: 'Content',
  isAutoUpload: false,
  accept: '.zip',
  isNeedClearError: false,
  onAddItem: (file: UploadFile, list: UploadFile[], msg?: any, upload?: any): boolean => {
    upgradeFileAddError = false;
    upgradeFormData = file;
    upgradeDisabled.value = false;
    return true;
  },
  onError: (error: any, file: UploadFile) => {
    if (error.validResults.indexOf('type') >= 0) {
      upgradeErrorTips = 'IBMC_UPGRADE_ZIP_FORMAT';
    } else if (error.validResults.indexOf('maxSize') >= 0) {
      upgradeErrorTips = 'IBMC_SP_FILE_OUT_RANGE';
    }
    upgradeDisabled.value = true;
    upgradeFileAddError = true;
  },
  onRemove: (file: UploadFile, list: UploadFile[]) => {
    upgradeDisabled.value = true;
    upgradeFileAddError = false;
  },
});
const signatureConfig = reactive({
  action: reqPath.ibmc.firmwareUpdate,
  headers: {
    'X-CSRF-Token': escapeHeader(loct ? JSON.parse(loct).to : ''),
    From: 'WebUI',
    Accept: '*/*',
  },
  id: 'fileUploadSignature',
  width: 320,
  disabled: isSystemLock,
  method: 'POST',
  name: 'Content',
  isAutoUpload: false,
  accept: '.asc,.p7s',
  isNeedClearError: false,
  onAddItem: (file: UploadFile, list: UploadFile[], msg?: any, upload?: any): boolean => {
    signatureFileAddError = false;
    signatureFormData = file;
    signatureDisabled.value = false;
    return true;
  },
  onError: (error: any, file: UploadFile) => {
    if (error.validResults.indexOf('type') >= 0) {
      signatureErrorTips = 'IBMC_UPGRADE_ASC_FORMAT';
    } else if (error.validResults.indexOf('maxSize') >= 0) {
      signatureErrorTips = 'IBMC_SP_FILE_OUT_RANGE';
    }
    signatureDisabled.value = true;
    signatureFileAddError = true;
  },
  onRemove: () => {
    signatureDisabled.value = true;
    signatureFileAddError = false;
  },
});

function upgradeUpload() {
  const formData = new FormData();
  formData.append('ImagePath', upgradeFormData.raw, upgradeFormData.name);
  formData.append('SignaturePath', signatureFormData.raw, signatureFormData.name);
  loading(true);
  uploadFile({ formData })
    .then(res => {
      loading(false);
      upgradeRef.value.clear();
      signatureRef.value.clear();
      init();
      spDialogRef.value.show();
    })
    .catch(error => {
      loading(false);
      const errorId = getMessageId(error.data);
      const errorMsg = getErrorTranslate(errorId[0].code as string);
      showElMessage('error', errorMsg);
      upgradeRef.value.clear();
      signatureRef.value.clear();
      init();
    });
}

function delList() {
  dialogRef.value.show();
}

const dialogConfig = reactive({
  value: '',
  id: '',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK'),
});

const spDialogConfig = reactive({
  type: 'success',
  content: '',
  title: traduction('COMMON_INFORMATION'),
});

function dialogClose(reason: any) {
  dialogRef.value.hide();
  if (reason) {
    loading(true);
    delSPUpdateFileList()
      .then(res => {
        init();
        loading(false);
        showElMessage('success', traduction('COMMON_SUCCESS'));
      })
      .catch(error => {
        loading(false);
        showElMessage('error', traduction('COMMON_FAILED'));
      });
  }
}

function spDialogClose(reason: boolean) {
  if (reason) {
    router.push('/navigate/manager/sp/sp-manage');
  }
  spDialogRef.value.hide();
}

function init() {
  getFileList().then(res => {
    fileList.length = 0;
    const list = res?.data?.UpdateFileList;
    if (list && Array.isArray(list)) {
      list.forEach((item: any) => {
        let obj: IUpgradeFile = {
          id: item.Id,
          name: item.Name,
        };
        fileList.push(obj);
      });
    }
  });
}

onMounted(() => {
  init();
});
</script>
<template>
  <div id="spUpgrade" class="spUpgrade-container">
    <CustomAert id="spUpgradeLock" :content="alertInfo" />
    <el-form label-width="auto">
      <el-form-item :label="$t('IBMC_MANUAL_UPDATE')">
        <FileUpload ref="upgradeRef" :data="upgradeConfig"></FileUpload>
        <span class="upload-tip">{{ $t('IBMC_UPGRADE_ZIP_FORMAT') }}</span>
      </el-form-item>
      <el-form-item :label="$t('IBMC_UPGRADE_SIGNATURE_FILE')">
        <FileUpload ref="signatureRef" :data="signatureConfig"></FileUpload>
        <span class="upload-tip">{{ $t('IBMC_UPGRADE_ASC_FORMAT') }}</span>
      </el-form-item>
      <el-form-item class="submit-item">
        <el-button
          id="upgradeUpload"
          :disabled="signatureDisabled || upgradeDisabled"
          type="primary"
          @click="upgradeUpload"
        >
          {{ $t('COMMON_UPLOAD') }}
        </el-button>
      </el-form-item>
    </el-form>
    <h3>{{ $t('IBMC_UPGRADE_EXISTING_FILE') }}</h3>
    <el-button id="upgradeDelete" :disabled="isSystemLock || fileList.length == 0" @click="delList">
      {{ $t('IBMC_SP_LIST_CLEAR') }}
    </el-button>
    <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose"></Dialog>
    <Dialog ref="spDialogRef" :config="spDialogConfig" @close="spDialogClose">
      <template #other>
        <dl class="dn-dialog">
          <dt>
            <el-icon :size="24">
              <IconSuccess />
            </el-icon>
          </dt>
          <dd>
            <p class="title">{{ $t('IBMC_UPGRADE_UPLOAD_SUCCESS') }}</p>
            <p class="content">{{ $t('IBMC_UPGRADE_UPLOAD_SP') }}</p>
          </dd>
        </dl>
      </template>
    </Dialog>
    <el-table v-addId.table="'spUpgradeTable'" border :data="fileList">
      <el-table-column label="ID">
        <template #default="scope">
          <span class="sp-file-id">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('COMMON_NAME')">
        <template #default="scope">
          <span class="sp-file-name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
  </div>
</template>
<style lang="scss" scoped>
.spUpgrade-container {
  .upload-tip {
    margin-left: 8px;
    color: #8d98aa;
  }
  .submit-item {
    margin-bottom: 32px;
  }
  .el-form {
    margin-top: 16px;
    :deep(.el-input) {
      max-width: 320px;
    }
  }
  h3 {
    margin-bottom: 16px;
  }
  .el-table {
    margin-top: 16px;
    min-height: 608px;
  }
}
.dn-dialog {
  display: flex;
  width: 100%;
  overflow: hidden;
  dd {
    flex: 1;
    margin-left: 16px;
    .title {
      font-size: 16px;
      color: var(--o-color-black);
      font-weight: 600;
      line-height: 24px;
    }
    .content {
      color: var(--o-text-color-secondary);
      margin-top: 16px;
    }
  }
}
</style>
