<template>
  <Spin :spinning="loading">
    <Textarea :rows="4" @change="textChange" v-model:value="keystoreBase64" :placeholder="placeholder" />
    <JUpload
      accept=".pem"
      listType="text"
      :action="NETWORK_CERTIFICATE_UPLOAD"
      :headers="{
        [TOKEN_KEY]: LocalStore.get(TOKEN_KEY)
      }"
      :showUploadList="false"
      @change="handleChange"
    >
      <JButton style="margin-top: 10px">
        <AIcon type="UploadOutlined" />
        上传文件
      </JButton>
    </JUpload>
  </Spin>
</template>

<script setup lang="ts" name="CertificateFile">
  import { onlyMessage } from '@jdlinker/utils';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { LocalStore, TOKEN_KEY } from '@jdlinker/utils';
  import { NETWORK_CERTIFICATE_UPLOAD } from '../../../../api/link/certificate';
  // @ts-ignore
  import { Button as JButton, AIcon, Spin, Textarea, Upload as JUpload } from 'linker-ui-components';
  import { ref, watch } from 'vue';

  const emit = defineEmits(['update:modelValue', 'change']);

  const props = defineProps({
    name: {
      type: String,
      default: () => ''
    },
    modelValue: {
      type: String,
      default: () => ''
    },
    placeholder: {
      type: String,
      default: () => ''
    }
  });

  const keystoreBase64 = ref(props.modelValue);
  const loading = ref(false);

  const handleChange = (info: UploadChangeParam) => {
    loading.value = true;
    if (info.file.status === 'done') {
      const result = info.file.response?.result;
      const reg = new RegExp(/\.pem$/i);
      if (reg.test(info.file.name)) {
        keystoreBase64.value = result;
        emit('change', result);
        emit('update:modelValue', result);
        onlyMessage('上传成功！', 'success');
      } else {
        onlyMessage('请上传.pem格式的文件', 'error');
      }
      loading.value = false;
    }
  };
  const textChange = () => {
    emit('change', keystoreBase64.value);
    emit('update:modelValue', keystoreBase64.value);
  };

  watch(
    () => props.modelValue,
    (v) => {
      keystoreBase64.value = v;
    },
    {
      deep: true,
      immediate: true
    }
  );
</script>

<style lang="less" scoped></style>
