<template>
  <div :class="isBtn?'file-upload-box2':'file-upload-box'">
    <n-upload action="#" :id="uuid" class="upload-demo my-upload-file"
      :class="fileList.length > 0 && !loading ? 'success-file' : ''" :multiple="multiple" ref="uploadRef" directory-dnd
      :disabled="loading ? true : self_disabled" v-model:file-list="fileList"
      @change="handleUploadChange" @remove="handleRemove" @before-upload="beforeUpload" :show-file-list="showFileList"
      :max="limit" >
      <template v-if="isBtn">
        <n-tooltip v-if="isBtn && btnTip" class="box-item" effect="dark" :content="btnTip" placement="top">
          <n-button icon="Upload" type="primary">点击上传</n-button>
        </n-tooltip>
        <n-button v-else icon="Upload" type="primary">点击上传</n-button>
      </template>
      <template v-else>
       <n-upload-dragger>
        <div>
          <n-icon size="40" color="#67c23a"  v-if="fileList.length > 0 && !loading">
            <FileDoneOutlined/>
          </n-icon>
          <n-icon size="40" v-else>
            <CloudUploadOutlined/>
          </n-icon>
        </div>
        <div v-if="!self_disabled">{{
          loading ? '上传中' : fileList.length > 0 ? '上传成功' : '点击或将文件拖拽到这里上传'
        }}</div>
         </n-upload-dragger>
      </template>
    </n-upload>
    <div v-if="!isBtn" class="n-upload__tip">
      <div v-if="props.fileType">支持扩展名：{{ props.fileType }}</div>
      <div v-if="props.multiple && props.limit">最多上传{{ props.limit }}个文件</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import {
  CloudUploadOutlined,
  FileDoneOutlined,
  UploadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ZoomInOutlined,
} from '@vicons/antd';
import { useNotification } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { generateUUID } from '@/utils/auth';

const uploadRef = ref();
import { upload } from '@/api/common';

// 接受父组件参数
const props = defineProps({
  zIndex: {
    default: -1,
  },
  width: {
    default: '220px',
  },
  height: {
    default: '120px',
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  isBtn: {
    type: Boolean,
    default: false,
  },
  showFileList: {
    type: Boolean,
    default: true,
  },
  btnTip: {
    type: String,
    default: '',
  },
  limit: {
    type: Number,
    default: undefined,
  },
  fileLists: {
    type: Array,
    required: true,
    default: [],
  },
  disabled: {
    default: false,
  },
  fileSize: {
    default: 200,
  },
  orderNo: {
    default: '',
  },
  fileType: {
    default: '',
  },
  name: {
    default: '',
  },
  autoUpload: {
    default: true,
  },
});

// 生成组件唯一id
const uuid = ref('id-' + generateUUID());

const delFlag= ref(false)

const fileList = computed({
  get: () => {
    props.fileLists.map(item=>item.status='finished')
    return props.fileLists;
  },
  set: (val) => {
    emit('update:modelValue',  fileList.value);
  },
});

const notification = useNotification()

// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled;
});

const emit = defineEmits(['upload']);

const loading = ref(false);
const handleHttpUpload = async (options) => {
  if (!props.autoUpload) {
    emit('upload', options);
    return;
  }
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', options.file.file);
    formData.append('name', props.name);
    const res = await upload(formData);
    if (props.multiple) {
      let list = JSON.parse(JSON.stringify(fileList.value));
      list.push({
        url: res.fileUrl,
        name: res.originalName,
        filePath: res.fileUrl,
        fileName: res.originalName,
        status:'finished'
      });
      emit('upload', list, props.zIndex);
    } else {
      emit('upload', res.fileUrl, res.originalName, props.zIndex);
    }
  } catch (error) {
    notification.error({
      message: '温馨提示',
      duration:2000,
      description: '上传文件失败！',
    });
    if (props.multiple) {
      emit('upload', fileList.value, props.zIndex);
    } else {
      uploadRef.value!.clear();
      emit('upload', '', '', props.zIndex);
    }
    options.onError(error as any);
  } finally {
    loading.value = false;
  }
};
const handleUploadChange= (data: { fileList: UploadFileInfo[] })=> {
  console.log(data)
  if(!delFlag.value) {
    handleHttpUpload(data)
  }
};

const handleRemove = (file: any) => {
  delFlag.value = true
  if (props.multiple) {
    emit(
      'upload',
      fileList.value.filter((f) => !(f.url === file.file.url)),
      props.zIndex,
    );
  } else {
    uploadRef.value!.clear();
    emit('upload', '', '', props.zIndex);
  }
};

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload = (rawFile) => {
  const imgSize = rawFile.file.file.size / 1024 / 1024 < props.fileSize;
  if (!imgSize) {
    notification.warning({
      message: '温馨提示',
      duration:2000,
      description: `上传文件大小不能超过 ${props.fileSize}M！`,
    });
    return false;
  }
  if (props.fileType) {
    let fileType = props.fileType.replace(/\s/g, '');
    fileType.split('.').join('|');
    let fileIndex = rawFile.file.file.name.lastIndexOf('.');
    let substrName = rawFile.file.file.name.substr(fileIndex);
    if (fileType.indexOf(substrName) == -1) {
      notification.warning({
        message: '温馨提示',
        duration:2000,
        description: '上传文件不符合所需的格式！',
      });
      return false;
    }
  }
  return true;
};
</script>
<style lang="less" scoped>
.file-upload-box {
  flex:1;
  :deep {
    .n-upload {
      >div.n-upload-trigger {
        width: v-bind(width);
        height: v-bind(height);
      }
    }
  }
    .n-upload__tip {
      line-height: 18px;
      font-size: 12px;
      margin-top: 12px;
    }
}
// .success-file.n-upload.n-upload-drag {
//   border-width: 3px;
//   border-color: #67c23a !important;
// }

// .file-upload-box {
//   .my-upload-file.n-upload.n-upload-drag {
//     height: 160px !important;

//     .n-upload {
//       display: flex;
//       flex-direction: column;
//       align-items: center;
//       justify-content: center;
//     }
//   }

//   .n-upload__tip {
//     line-height: 18px;
//     font-size: 12px;
//     margin-top: 7px;
//   }
// }
</style>
