<template>
  <div class=" flex flex-wrap">
    <input type="file" class=" hidden" multiple ref="inputDom" @change="handleFileChange">
    <div v-for="(item,index) in urlList" :key="item.name" class=" w-1/3 h-32 p-1 relative">
        <img :src="item.url" alt="" class=" w-full h-full rounded">
        <div class=" h-8 text-center absolute bottom-1 left-1 right-1 bg-gray-500 opacity-80 text-white leading-8 text-xs" v-if="index == 0">默认封面</div>
        <app-icon name='icon-fahangnft' class="delete-icon absolute top-1 right-2 w-1/6" size='22px' color='#f68585' @click.native="deleteImg(index)"></app-icon>
    </div>
    <div v-if="fileList.length < maxCount" @click="upload" class=" h-32 w-1/3 text-zx-blue-light p-1">
        <div class=" h-full w-full bg-zx-btn-disabled-bg relative">
          <app-icon name='icon-shanchu' class="upload-icon" size="25px" color='#A7B5CD'></app-icon>
        </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue"
export default Vue.extend({
    props: {
        fileList: Array,
        maxCount: Number,
    },
    components:{
        'app-icon':()=>import('@/components/common/Icon.vue')
    },
    methods: {
        upload():void{
            const dom = this.$refs.inputDom as HTMLInputElement
            dom.click()
        },
        handleFileChange(e:any):void{
            const dom = this.$refs.inputDom as HTMLInputElement
            for(let item of e.target.files) {
              const type_name = item.name.substring(item.name.lastIndexOf('.'),item.name.length)
              if(['.png','.jpg','.jpeg','.PNG','.JPG','.JPEG'].indexOf(type_name) == -1) {
                 this.$toast('请上传指定类型文件~')
                 dom.value = ''
                 return
              }
            }
            this.$emit('fileChange',e.target.files)
            dom.value = ''
        },
        deleteImg(index:number):void{
            this.$emit('deleteImg',index)
        }
    },
    computed: {
        urlList():Array<any>{
            return this.fileList.map((item:any)=>{
                if(item.fileUrl) {//本来就有文件地址
                    return {
                        url: item.fileUrl
                    }
                }else {//文件类型的数据
                    return {
                        url: window.URL.createObjectURL(item)
                    }
                }

            })
        }
    }
})
</script>

<style>
.delete-icon {
    transform: rotate(45deg);
}
.upload-icon {
    position:absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%) rotate(45deg);
}

</style>