<template>
    <van-cell :title="label" :required="required">
        <van-uploader
        slot="label"
        v-model="fileList" 
        :disabled="disabled"
        :max-count="limit"
        :multiple="false"
        :after-read="handleUpload"
        @delete="handleDelete"/>
    </van-cell>
    
</template>

<script>
import mixin from './mixin'
import {uploadImage} from '@/api/system/common'
import {join} from 'lodash'
/**
 * 文件上传组件
 */
export default {
  mixins: [mixin],
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
      limit: {
          type: Number,
          default: 1
      }
  },
  data() {
      return {
          fileList: this.extractFiles()
      }
  },
  watch: {
      value(){
          this.fileList = this.extractFiles()
      }
  },
  methods: {
      async handleUpload(file){
          file.status = 'uploading'
          const {code, url} = await uploadImage(file.file)
          if(code === 200){
              this.$emit('change', this.generateUrl(url))
          } else {
              file.status = 'failed'
          }
      },
      handleDelete(){
        if (!this.fileList || this.fileList.length === 0) {
            this.$emit('change', null)
            return
        }
        const urls = this.fileList.map(({url}) => url)
        this.$emit('change', urls)
      },
      extractFiles() {
          return this.value?.split(',').map(url => ({url, status: 'done'})) || []
      },
      generateUrl(url) {
          const urls = this.value?.split(',') || []
          if (url && url.length > 0) {
            urls.push(url)
          }
          return join(urls, ',')
      }
  }
}
</script>
