<template>
  <div>
    <xy-dialog :is-show.sync="isShow" title="商户文件" ok-text="保存" @on-ok="submit">
      <el-upload
        :multiple="true"
        class="upload-demo"
        :action="action"
        :before-upload="handleBefore"
        :on-success="handleSuccess"
        :on-preview="handlePreview"
        :before-remove="handleBeforeRemove"
        :on-remove="handleRemove"
        :file-list="fileList"
        list-type="picture" multiple>
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png/mp4文件，且不超过10M</div>
      </el-upload>
    </xy-dialog>
  </div>
</template>

<script>
import {getPicture,storePicture,destroyPicture} from '@/api/confinementClub'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      id:'',
      isShow:false,
      action:`${process.env.VUE_APP_BASE_API}api/admin/upload-file`,

      fileList:[],
      pics:[],//需要上传的文件
    }
  },
  methods: {
    getPic(){
      getPicture({confinement_services_id:this.id}).then(res => {
        this.fileList = []
        this.fileList.push(...res.map(item => {
          return { url:item.picture,name:item.name || item.picture,id:item.id  }
        }))
      })
    },

    handleBefore(file){
      console.log(file)
      if((file.size/1000) > 10240){
        Message({
          type:'warning',
          message:'上传文件/视频大小超过10M！'
        })
        return false
      }
    },
    handleRemove(file, fileList) {
      //console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleSuccess(response, file, fileList){
      this.pics.push(response.url)
    },
    handleBeforeRemove(file){
      console.log(file)
      if(file.id){
        destroyPicture({id:file.id}).then(res => {
          Message({
            type:'success',
            message:'删除文件成功'
          })
        }).catch(err => {
          this.getPic()
        })
      }else{
        this.pics.splice(this.pics.indexOf(file.response.id),1)
      }
    },

    submit(){
      Promise.all(this.pics.map(item => {
        return storePicture({
          confinement_services_id:this.id,
          picture:item
        })
      })).then(res => {
        Message({
          type:'success',
          message:`新增${res.length}张文件`
        })
        this.isShow = false
      }).catch(err => {
        console.log(err)
      })
    }
  },
  watch:{
    isShow(newVal){
      if(newVal){
        this.getPic()
      }else{
        this.id = ''
        this.fileList = []
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>
