<template>
  <div class="module">
    <div :class="className">
      <span class="spanTitle1">{{ title }}</span>
      <van-uploader
        :after-read="afterRead"
        v-model="fileList"
        accept="image/*"
        multiple
        :before-delete="handleDelete"
      >
        <img src="@/assets/images/photo.png" alt="" />
      </van-uploader>
      <b v-if="verify" class="verify">*</b>
    </div>

    <p class="reminder" v-if="reminder">当前项为必填项</p>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { upload } from '@/api/danger.js'
export default {
  props: ['title', 'value', 'verify'],
  name: 'ImageUpload',
  watch: {
    value: {
      handler (val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',')
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === 'string') {
              if (item.indexOf(this.baseUrl) === -1) {
                item = { name: this.baseUrl + item, url: this.baseUrl + item }
              } else {
                item = { name: item, url: item }
              }
            }
            return item
          })
        } else {
          // this.reminder = true
          this.className = 'el_input_focus1'
          this.fileList = []
          return []
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapState('baseUrl', ['baseUrl'])
  },
  data () {
    return {
      className: 'el_input_focus',
      internalValue: this.value,
      reminder: false,
      fileList: [],
      uploadList: []
    }
  },

  mounted () {
    if (this.value) {
      this.className = 'el_input_focus1'
      this.reminder = false
    }
  },

  methods: {
    async afterRead (file) {
      const files = new window.File(
        [this.dataURLtoBlob(file.content)],
        '图片.jpg',
        { type: 'jpg' }
      ) // 转成file类型
      const formData = new FormData()
      formData.append('file', files)
      const { data } = await upload(formData)
      if (data.code === 200) {
        this.uploadList.push({ name: data.fileName, url: data.fileName })
        this.$emit('input', this.listToString(this.uploadList))
      }
    },
    // 对象转成指定字符串分隔
    listToString (list, separator) {
      let strs = ''
      separator = separator || ','
      for (const i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, '') + separator
        }
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : ''
    },
    // Base64 转 Blob
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',') // 分割为数组，分割到第一个逗号
      const mime = arr[0].match(/:(.*?);/)[1] // 获取分割后的base64前缀中的类型
      const bstr = window.atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    handleDelete (file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name)
      if (findex > -1) {
        this.fileList.splice(findex, 1)
        this.uploadList.splice(findex, 1)
        this.$emit('input', this.listToString(this.uploadList))
      }
    },
    focus () {
      if (!this.value || this.value === '@#%__+!') {
        this.className = 'el_input_focus1'
      }
    },
    blur () {
      if (this.verify) {
        if (this.fileList) {
          this.className = 'el_input_focus1'
          this.reminder = false
        } else {
          this.reminder = true
          this.className = 'el_input_focusTrue1'
        }
      } else {
        if (this.fileList) {
          this.className = 'el_input_focus1'
        } else {
          this.className = 'el_input_focus1'
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
img {
  width: 40px;
  height: 33px;
  margin: 10px;
}
</style>
