<template>
  <view class="upBox">
    <uni-file-picker
      v-model="list"
      :limit="limit"
      :fileMediatype="fileMediatype"
      @select="picSelect"
      @success="picSuccess"
      @fail="picFail"
      @delete="picDelete"
      :mode="mode"
      :delIcon="delIcon"
      :imageStyles="imageStyles"
    >
      <slot></slot>
    </uni-file-picker>
  </view>
</template>

<script>
export default {
  name: 'uploadFile',
  model: {
    prop: 'fileList',
    event: 'change'
  },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    module: {
      type: String,
      default: ''
    },
    fileMediatype: {
      type: String,
      default: 'all'
    },
    limit: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: ''
    },
    imageStyles: {
      type: Object,
      default: () => ({})
    },
    delIcon: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      list: []
    }
  },
  watch: {},
  computed: {
    // list: {
    //   get () {
    //     return this.fileList.map(item => ({
    //       extname: item.name.split('.').pop(),
    //       url: window.location.origin + item.accessUrl,
    //       ...item
    //     }))
    //   },
    //   set (val) {
    //     console.log(val, 'val')
    //     this.$emit('change', val)
    //     return val
    //   }
    // }
  },
  methods: {
    //选择图片,上传
    picSelect (e) {
      const tempFilePaths = e.tempFilePaths
      console.log(tempFilePaths)
      uni.showLoading({
        title: '上传中'
      })
      uni.uploadFile({
        url: this.apiUrl + '/data/doc/add',
        filePath: tempFilePaths[0],
        name: 'file',
        formData: {
          module: this.module
        },
        success: res => {
          let info = JSON.parse(res.data)
          console.log(res.data, 'this.$attrs.limit=', this.$attrs.limit)
          uni.hideLoading()
          info.data.type = info.data.type?.id
          this.$emit(
            'change',
            this.$attrs.limit == 1 ? [info.data] : [...this.fileList, info.data]
          )
        },
        fail: () => {
          uni.hideLoading()
          uni.showToast('上传失败!')
        }
      })
    },
    //上传成功
    picSuccess () {
      uni.showToast({
        icon: 'none',
        title: '上传成功',
        duration: 2000
      })
    },
    //上传失败
    picFail () {
      uni.showToast({
        icon: 'none',
        title: '上传失败，请重新上传!',
        duration: 2000
      })
    },
    //删除图片
    picDelete (e) {
      console.log(this.list)
      // this.$emit(
      //     'change',
      //     this.$attrs.limit == 1 ? [] : [...this.fileList, info.data]
      //   )
      console.log(e)
    }
  }
}
</script>

<style lang="scss" scoped>
.upBox {
  width: 100%;
  display: block;
}
</style>
