<script setup lang="ts">
import { traduction } from '@/utils/language';
import { showElMessage } from '@/utils/utils';
import { getMessageId } from '../utils/utils';
import { IconRemind } from '@computing/opendesign-icons';
import { ref, reactive, onMounted, PropType } from 'vue';

import GlobalStoreService from '@/services/gloabal-store-service';
import LocaluserService from '../../../../services/localuser.service';

import FileUpload from '@/components/FileUpload/FileUpload.vue';
import { getStoreData } from '@/utils/composition';

const props = defineProps({
  loginWithoutPassword: {
    type: Boolean,
    required: true,
    default: false,
  },
  item: {
    type: Object as PropType<any>,
    required: true,
    default: () => {},
  },
});

const emits = defineEmits(['cancel']);

defineExpose({
  show() {
    Object.assign(editData, {
      raido: 'publicFile',
      file: '',
      textValue: '',
      password: '',
    });
    dialogFormVisible.value = true;
  },
});

const pwdMaxLen = getStoreData('loct', 'pml');
const globalStoreService = new GlobalStoreService();
const dialogFormVisible = ref(false);

const editData: any = reactive({
  raido: 'publicFile',
  file: '',
  textValue: '',
  password: '',
});

const fileUpload = ref();
const isPwdError = ref(false);

const typeLimit = traduction('USER_SSH_ADD_FAILED_TYPE');
const nameLimit = traduction('USER_SSH_ADD_FAILED_TYPE');
const lengthLimit = traduction('COMMON_UPLOAD_FILE_MORN_1M_ERROR3');

const uploaderConfig = reactive({
  // 上传地址
  action: '',
  // 是否自动上传
  isAutoUpload: false,
  // 文件类型限制
  accept: '.pub',
  // 上传错误提示信息的id
  errorMsgId: 'fileSelectFailed',
  // 选择好文件后的回调
  onAddItem(file: any, list: any, errorMsg: any, value: any) {
    editData.file = '';
    // 必须是pub文件
    let type = file.name.substring(file.name.lastIndexOf('.') + 1);
    if (type !== 'pub') {
      fileUpload.value.setError(typeLimit);
      return false;
    }

    // 文件名称不能为空
    if (file.name.length === 4) {
      fileUpload.value.setError(nameLimit);
      return false;
    }

    // 文件大小不能超过2M
    if (file.size > 2 * 1024) {
      fileUpload.value.setError(lengthLimit);
      return false;
    }

    fileUpload.value.clearError();
    return true;
  },
  // 选择成功的回调
  onAddItemSuccess(response: any) {
    editData.file = response;
    setBtnState();
  },
  // 移除时的回调
  onRemove(fileItem: any) {
    saveBtnState.value = false;
    editData.file = '';
  },
});

const saveBtnState = ref(false);

// 单选框发生修改
function raidoChange(value: string) {
  Object.assign(editData, {
    raido: value,
    file: '',
    textValue: '',
    password: '',
  });

  isPwdError.value = false;
  fileUpload?.value?.clearError();
  fileUpload?.value?.clear();
  setBtnState();
}

// 输入框改变数据
function inputChange(value: string) {
  editData.password = value;
  isPwdError.value = false;
  setBtnState();
}

// 设置保存按钮的状态
function setBtnState() {
  saveBtnState.value = false;

  if (editData.raido === 'publicFile') {
    if (props.loginWithoutPassword && editData.file) {
      saveBtnState.value = true;
    } else if (editData.file && editData.password) {
      saveBtnState.value = true;
    }
  } else {
    if (props.loginWithoutPassword && editData.textValue) {
      saveBtnState.value = true;
    } else if (editData.textValue && editData.password) {
      saveBtnState.value = true;
    }
  }
}
function uploadSShFile(name: string, password: string, type: string, textValue?: string) {
  LocaluserService.uploadFile({
    userId: props.item.id,
    Content: textValue ? textValue : name,
    secPwd: password,
    type,
  })
    .then(() => {
      globalStoreService.setValue('isLoading', false);
      showElMessage('success', traduction('COMMON_SUCCESS'));
      cancel(true);
    })
    .catch((error: any) => {      
      globalStoreService.setValue('isLoading', false);
      const errorId = getMessageId(error)[0].errorId;
      if (errorId === 'ReauthFailed' || errorId === 'AuthorizationFailed') {
        isPwdError.value = true;
        return;
      }
      const msg = traduction(errorId + '.errorMessage') || traduction('COMMON_FAILED');
      showElMessage('error', msg);
      cancel();
    });
}

// 点击确认
function sureSave() {
  if (saveBtnState.value) {
    let formData: FormData;
    let password = '';
    let type = '';
    if (editData.password !== '') {
      password = window.btoa(editData.password);
    }
    const { raw, name } = editData.file;
    editData.password = '';
    saveBtnState.value = false;
    globalStoreService.setValue('isLoading', true);
    if (editData.raido === 'publicText') {
      type = 'Text';
      uploadSShFile(name, password, type, editData.textValue);
    } else {
      formData = new FormData();
      formData.append('imgfile', raw, name);
      type = 'URI';
      LocaluserService.uploadCerFile(formData)
        .then(() => {
          uploadSShFile(name, password, type);
        })
        .catch((error: any) => {
          globalStoreService.setValue('isLoading', false);
          const errorId = getMessageId(error)[0].errorId;
          if (errorId === 'ReauthFailed' || errorId === 'AuthorizationFailed') {
            isPwdError.value = true;
            return;
          }
          const msg = traduction(errorId + '.errorMessage') || traduction('COMMON_FAILED');
          showElMessage('error', msg);
          cancel();
        });
    }
  }
}

// 取消
function cancel(refresh?: boolean) {
  dialogFormVisible.value = false;
  Object.assign(editData, {
    raido: 'publicFile',
    file: '',
    textValue: '',
    password: '',
  });
  // 是否刷新数据
  if (refresh) {
    emits('cancel');
  }
}

onMounted(() => {
  raidoChange('publicFile');
});
</script>

<template>
  <div v-if="dialogFormVisible" id="uploadSSH" v-reqKeepAlive.dialog class="dialog-box">
    <el-dialog
      v-model="dialogFormVisible"
      :title="$t('USER_SSH_PUBLIC_UPLOAD')"
      :close-on-click-modal="false"
      destroy-on-close
      :append-to-body="false"
    >
      <div class="text">
        <el-icon><IconRemind /></el-icon>
        {{ $t('USER_SSH_MODAL_SUPPORT_MESSAGE') }}
      </div>

      <!-- 公钥文件-公钥文本 -->
      <div class="radio-box">
        <el-radio
          v-model="editData.raido"
          v-addId.radio="'radioCtrl0'"
          label="publicFile"
          size="large"
          @change="raidoChange"
        >
          {{ $t('USER_SSH_PUBLIC_FILE') }}
        </el-radio>
        <el-radio
          v-model="editData.raido"
          v-addId.radio="'radioCtrl1'"
          label="publicText"
          size="large"
          @change="raidoChange"
        >
          {{ $t('USER_SSH_PUBLIC_TEXT') }}
        </el-radio>
      </div>

      <el-form label-position="left" label-width="auto">
        <!-- 公钥文件 -->
        <el-form-item
          v-show="editData.raido === 'publicFile'"
          :label="$t('USER_SSH_PUBLIC_SELECT_FILE')"
        >
          <FileUpload id="fileUpload" ref="fileUpload" :data="uploaderConfig" />
        </el-form-item>

        <!-- 公钥文本 -->
        <el-form-item
          v-show="editData.raido === 'publicText'"
          :label="$t('USER_SSH_PUBLIC_TEXTINFO')"
        >
          <el-input
            v-model="editData.textValue"
            v-addId.input="'textControl'"
            type="textarea"
            :rows="4"
            maxlength="2048"
            show-word-limit
            autocomplete="off"
            :placeholder="$t('USER_SSH_PUBLIC_PLACEHOLDER')"
            @input="setBtnState"
          />
        </el-form-item>

        <!-- 登录密码 -->
        <el-form-item
          v-if="!loginWithoutPassword"
          :label="$t('COMMON_LOGIN_PASSWORD')"
          :class="[isPwdError ? 'is-error' : '', 'pwd']"
        >
          <el-input
            v-model="editData.password"
            v-addId.input="'userPwd'"
            v-clearable
            clearable
            type="password"
            :maxlength="pwdMaxLen"
            autocomplete="new-password"
            :placeholder="$t('COMMON_PASSWORD_PLACEHOLDER')"
            @keyup.enter="sureSave"
            @input="inputChange($event)"
            @clear="inputChange('')"
          />
          <div v-if="isPwdError" id="userPwdError" class="error-text">
            {{ $t('COMMON_SECONDPWD_ERROR') }}
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button
            id="save"
            size="small"
            type="primary"
            :disabled="!saveBtnState"
            @click="sureSave"
          >
            {{ $t('COMMON_OK') }}
          </el-button>
          <el-button id="cancel" size="small" @click="cancel">
            {{ $t('COMMON_CANCEL') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.dialog-box {
  :deep(.el-overlay) {
    .el-dialog {
      width: 544px;

      .text {
        line-height: 16px;
        padding: 8px 16px;
        border-radius: 4px;
        background-color: var(--o-color-state-primary-secondary);
        display: flex;

        .el-icon {
          margin-right: 12px;
          display: inline-block;
          width: 16px;
          height: 16px;
          color: rgba(0, 119, 255, 1); //icon不随品牌色变化
          font-size: 18px;
        }
      }

      .radio-box {
        margin-top: 5px;
        margin-bottom: 11px;
      }

      .el-form-item:nth-child(3) {
        margin-bottom: 0;
      }

      .el-form-item__label {
        position: relative;

        &::before {
          position: absolute;
          left: -6px;
        }
      }

      .error-text {
        position: relative;
        top: -8px;
        margin-top: 0px;
        color: var(--o-color-danger);
        line-height: 16px;
      }

      .file-upload {
        max-height: 32px;
      }

      .pwd {
        max-height: 48px;

        .el-form-item__label::before {
          content: '*';
          position: absolute;
          left: -6px;
          color: var(--el-color-danger);
          font-size: 12px;
        }

        .error-text {
          position: relative;
          top: 0px;
          margin-top: 0px;
          color: var(--o-color-danger);
          line-height: 16px;
        }
      }
    }
  }
}
</style>
