<template>
  <div class="clearfix">
    <a-upload :action="action" multiple :fileList="fileList" list-type="picture-card" @preview="handlePreview" @change="handleChange" :customRequest="customRequest" :remove="handleRemove" :beforeUpload="beforeUpload">
      <div v-if="fileList.length < maxSize">
        <a-icon type="upload" style="margin-left: 15px" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" :width="1200">
      <img style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/upms/file'
export default {
  name: 'UploadImg',
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      action: process.env.VUE_APP_API_BASE_URL + '/upms/files/upload',
    }
  },
  props: {
    maxSize: {
      type: Number,
      default: 1,
    },
    value: {
      type: Array,
    },
  },
  watch: {
    fileList: {
      handler(newV, oldV) {
        this.fileList = newV
        this.$emit('change', newV)
      },
      deep: true,
      immediate: true,
    },
    value: {
      deep: true,
      immediate: true,
      handler: function (newV) {
        console.log(newV)
        // 数据为空的三种情况
        if (newV === null || newV === '' || newV === undefined) {
          this.fileList = []
          this.isWatch = true
          return
        }
        if (this.isWatch) {
          this.isWatch = false
          if (newV.length > 0) {
            this.fileList = this.BaseTool.UPLOAD.transImg(newV)
          } else {
            this.isWatch = true
          }
        }
      },
    },
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      // this.fileList = fileList
      // this.$emit('catchFile', fileList)
    },
    async customRequest(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      data.onProgress()
      this.$loading.show()
      uploadFile(formData).then((res) => {
        this.$loading.hide()
        data.onSuccess()
        const reg = new RegExp('[；，。！？;,]')
        if (reg.test(res.data.fileName)) {
          this.$message.error(`文件名包含非法字符`)
        } else {
          this.fileList.push({
            uid: '-1',
            name: res.data.name,
            status: 'done',
            url: this.BaseTool.Constant.FILE_URL + res.data.url,
          })
        }
        this.$emit('catchFile', this.fileList)
      })
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.$emit('catchFile', this.fileList)
      return true
    },
    beforeUpload(file, fileList) {
      const reg = /\.(jpg|png|zip|png|jpg|gif|jpeg|webp)(\?.*)?$/
      // if (this.fileType === 1) {
      //   reg = /\.(jpg|png|gif)(\?.*)?$/
      // }
      return new Promise((resolve, reject) => {
        if (reg.test(file.name.toLowerCase())) {
          resolve()
        } else {
          this.$message.error(`请上传正确的图片格式`)
          reject(new Error('请上传正确的图片格式'))
        }
      })
    },
  },
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.ant-upload-btn {
  margin-top: 20px;
}
</style>
