<template>
  <div class="">
    <a-upload
      v-model:file-list="fileList"
      list-type="picture-card"
      class="avatar-uploader"
      :action="apiUrl"
      :before-upload="beforeUpload"
      :headers="headers"
      name="file"
      @change="handleChange"
      @preview="handlePreview"
    >
      <div v-if="fileList.length < 8">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </a-upload>

    <a-modal :visible="previewVisible" title="预览" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, defineExpose, defineProps, watch } from 'vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getToken } from '/@/utils/auth';
  import { message, UploadChangeParam, UploadProps } from 'ant-design-vue';

  const props = defineProps(['editFileList']);
  const fileList = ref([]);
  const picLoading = ref<boolean>(false);
  const globSetting = useGlobSetting();
  const apiUrl = globSetting.uploadUrl;
  const token = getToken();
  const headers = {
    Authorization: token,
  };

  const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
      picLoading.value = true;
      return;
    }
    if (info.file.status === 'done') {
      picLoading.value = false;
    }
    if (info.file.status === 'error') {
      picLoading.value = false;
      message.error('上传失败');
    }
  };

  const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg' ||
      file.type === 'image/gif' ||
      file.type === 'image/webp';
    if (!isJpgOrPng) {
      message.error('请上传图片格式');
    }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //   message.error('Image must smaller than 2MB!');
    // }
    return isJpgOrPng;
  };

  const previewVisible = ref(false);
  const previewImage = ref('');

  const handleCancel = () => {
    previewVisible.value = false;
  };

  const handlePreview = async (file: UploadProps['fileList'][number]) => {
    previewImage.value = file.url;
    previewVisible.value = true;
  };

  watch(
    () => props.editFileList,
    (n) => {
      if (n) {
        console.log(n);

        fileList.value = n;
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  defineExpose({ fileList });
</script>

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