<template>
  <Spin :spinning="loading">
    <Input placeholder="请上传文件" v-model:value="fileValue" style="width: calc(100% - 110px)" :disabled="true" />
    <Upload
      name="file"
      :multiple="true"
      :action="FIRMWARE_UPLOAD"
      :headers="{
        [TOKEN_KEY]: getToken()
      }"
      @change="handleChange"
      :showUploadList="false"
      class="upload-box"
    >
      <JButton type="primary">
        <div><AIcon type="UploadOutlined" /><span class="upload-text">上传文件</span></div>
      </JButton>
    </Upload>
  </Spin>
</template>

<script setup lang="ts" name="FileUpload">
  import { ref, watch } from 'vue';
  import { getToken } from '@jdlinker/func';
  import { TOKEN_KEY } from '@jdlinker/utils';
  import { FIRMWARE_UPLOAD } from '../../../../api/device/firmware';
  import { onlyMessage } from '@jdlinker/utils';
  import type { UploadChangeParam } from 'ant-design-vue';
  // @ts-ignore
  import { notification as Notification, Button as JButton, AIcon, Upload, Input, Spin } from 'linker-ui-components';

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

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

  const paths = '';

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

  const handleChange = async (info: UploadChangeParam) => {
    loading.value = true;
    if (info.file.status === 'done') {
      loading.value = false;
      const result = info.file.response?.result;
      // const f = `${paths || ''}/file/${result.id}?accessKey=${result.others.accessKey}`;
      onlyMessage('上传成功！', 'success');
      fileValue.value = result.downloadUrl;
      emit('update:modelValue', result.downloadUrl);
      emit('update:extraValue', result);
    } else {
      if (info.file.error) {
        Notification.error({
          // key: '403',
          message: '系统提示',
          description: '系统未知错误，请反馈给管理员'
        });
        loading.value = false;
      } else if (info.file.response) {
        loading.value = false;
      }
    }
  };

  watch(
    () => props.modelValue,
    (value) => {
      fileValue.value = value;
    }
  );
</script>

<style lang="less" scoped>
  .upload-box {
    :deep(.ant-btn) {
      width: 110px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
    .upload-text {
      margin: 0 10px;
    }
  }
</style>
