<template>
	<view class="mz-upload-container">
    <uv-upload
        :width="width"
        :height="height"
        :fileList="fileList"
        name="1"
        multiple
        :maxCount="10"
        uploadIcon="plus"
        @delete="(res) => {uploadDel(res)}"
        @afterRead="(res) => {uploadPut(res)}"
    ></uv-upload>
	</view>
</template>

<script>
	import { imghost } from '@/config/host.js'
  import api from "@/utils/functions";
	export default{
		name:'MzUpload',
		props:{
      value:{
        type:Array,
        default:[]
      },
      width:{
        type:String,
        default:'160rpx'
      },
      height:{
        type:String,
        default:'160rpx'
      },
      format:{
        type:String,
        default:'array'
      }
		},
		data() {
			return {
        fileList:[],
			}
		},
		methods: {
      uploadSubmit(data){
        if(this.format === 'array'){
          return data.map(item => {
            return {
              url:item.url,
              type:item.type
            };
          });
        }else{
          return data.map(item => {
            return item.url;
          });
        }
      },
      uploadShow(data){
        let result = [];
        try{
          data.forEach(item => {
            let rowData = {};
            if(typeof item === 'string'){
              rowData.url = item;
              rowData.type = item || api.getFileType(item);
            }else{
              rowData.url = item.url;
              rowData.type = item.type || api.getFileType(item.type);
            }
            result.push(rowData)
          })
        }catch (e){
          this.fileList = [];
        }
        this.fileList = result;
      },
      uploadPut(event){
        let lists = [].concat(event.file);
        let fileListLen = this.fileList.length;
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中',
          });
        });
        for (let i = 0; i < lists.length; i++) {
          const fileType = api.getFileType(lists[i].url);
          api.uploadOssFile(lists[i].url).then(res => {
            let item = this.fileList[fileListLen];
            this.fileList.splice(fileListLen, 1, {
              ...item,
              status: 'success',
              message: '',
              url: res.show_path,
              thumb: res.show_path,
              type:fileType
            });
            fileListLen++;
          })
        }
      },
      uploadDel(fileIndex){
        this.fileList.splice(fileIndex.index,1);
      },
		},
    mounted() {
      this.uploadShow();
    },
    watch:{
        fileList: {
          handler(newVal,oldVal){
            this.$emit('update:modelValue',this.uploadSubmit(newVal));
          },
          deep:true,
        }
    },
	}
</script>

<style lang="scss">
	@import './components/index.scss';
</style>