<template>
      <el-dialog title="资源上传" :visible.sync="show" @open="dialogOpen" @close="close" class="catalog-resources-upload-dlg">
      <el-form :model="tmpResource" ref="tmpResource" label-width="25%">
        <el-form-item label="文件：" props="file">
          <el-input disabled v-model="allowType" type="primary"
          style="width:200px;float: left;margin-right: 6px;"></el-input>
          <el-upload
            class="upload-Image"
            ref="resourceUpload"
            action=""
            :multiple="false"
            :auto-upload="false"
            :limit="1"
            :on-change="select"
            :before-upload="beforeUpload"
            :http-request="fileUpload"
            :on-remove="remove"
            :accept="allowType">
            <el-button type="primary">选择文件</el-button>
             <div slot="tip" v-show="allowTypeShow" :title="'只能上传的文件格式：'+ allowType" class="el-upload__tip upload-allow-hint">{{'只能上传的文件格式：'+allowType}}</div>
          </el-upload>
        </el-form-item>
        <div v-if="(uploadType.type==='image'||uploadType.type==='video')&&uploadType.ID">
          <el-form-item label="宽度：" props="width">
            <el-input-number :style="{width:'75%'}" v-model="tmpResource.width" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="高度：" props="height">
            <el-input-number :style="{width:'75%'}" v-model="tmpResource.height" :min="1"></el-input-number>
          </el-form-item>
        </div>
        <div v-if="isConvert">
          <el-form-item label="是否转换：">
            <el-switch v-model="tmpResource.convert" active-value="Y" inactive-value="N">
          </el-switch>
          </el-form-item>
        </div>
        <!-- <el-form-item prop="tag" label="标签"> -->
          <resource-tags :tags.sync="tmpResource.tag"></resource-tags>
        <!-- </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button @click="uploadClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="upload">确 定</el-button>
      </div>
    </el-dialog>
</template>
<script>
import util from '@src/common/util.js'
import resourceTag from './ResourceTags.vue'
export default {
  components: {
    'resource-tags': resourceTag
  },
  props: {
    uploadType: {
      type: Object,
      default: _ => ({
        ID: '',
        type: '',
        siteID: '',
        tag: ''
      })
    }
  },
  data() {
    return {
      loading: false,
      allowType: '',
      fileList: [],
      tmpResource: {},
      allowTypeShow: false,
      isConvert: false,
      videoTypes: []
    }
  },
  computed: {
    show: {
      set(val) {
        let uploadType = Object.assign(this.uploadType, {show: val})
        this.$emit('uploadType', uploadType)
      },
      get() {
        this.getResourceType()
        return this.uploadType.show
      }
    }
  },
  watch: {
    fileList(val) {
      let fileName = val && val.length > 0 && val[0].name
      let exsit = ''
      if (fileName) {
        let fileExt = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
        exsit = this.videoTypes.find(vtype => vtype === fileExt)
      }
      this.isConvert = exsit
    }
  },
  mounted() {
  },
  methods: {
    dialogOpen() {
      if ((this.uploadType.type === 'image' || this.uploadType.type === 'video') && this.uploadType.ID) {
        Vue.set(this.tmpResource, 'width', 120)
        Vue.set(this.tmpResource, 'height', 120)
      }
      Vue.set(this.tmpResource, 'convert', 'Y')
    },
    async getResourceType() {
      let res = await axios.get(`/ui/resourcelibray/getUploadType`, {params: {'resourceType': this.uploadType.type}})
      if (res.data) {
        this.allowType = res.data
      }
      let resp = await axios.get(`/ui/resourcelibray/getUploadType`, {params: {'resourceType': 'video'}})
      if (resp.data) {
        this.videoTypes = resp.data && resp.data.split(',')
      }
    },
    upload() {
      if (!this.fileList || this.fileList.length === 0) {
        this.$alert('请选择要上传的文件')
        return
      }
      this.$refs.resourceUpload.submit()
    },
    close() {
      this.clearForms()
      this.fileList = []
    },
    select(file, files) {
      this.fileList = JSON.parse(JSON.stringify(files.slice(-1)))
      this.beforeUpload(file)
    },
    // 文件列表移除文件
    remove(file, files) {
      this.fileList = JSON.parse(JSON.stringify(files))
      this.allowTypeShow = false
    },
    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      const extensions = this.allowType.split(',')
      for (var i = 0; i < extensions.length; i++) {
        let tmp = extensions[i]
        if (extension.toLowerCase() === tmp.toLowerCase()) {
          return true
        }
      }
      this.allowTypeShow = true
      return false
    },

    uploadClose() {
      this.clearForms()
      this.fileList = []
      this.allowTypeShow = false
      this.show = false
    },
    // 文件上传确定事件
    async fileUpload(event) {
      let file = event.file
      if (!this.fileList || this.fileList.length === 0) {
        util.showResponseMessage({message: '请选择要上传的文件'})
        return
      }
      try {
        if (!this.tmpResource.tag) {
          this.tmpResource.tag = ''
        }

        let formData = new FormData()
        formData.append('file', file)
        for (let i in this.tmpResource) {
          formData.append(i.toLowerCase(), this.tmpResource[i])
        }
        this.uploadType.ID && formData.append('id', this.uploadType.ID)
        this.loading = true
        let res = this.uploadType.ID
          ? await axios.post(`/ui/resourcelibray/${this.uploadType.ID}/reload`, formData)
          : await axios.post(`/ui/resourcelibray/upload`, formData)
        util.showResponseMessage(res.data)
        res.data.status === 1 && this.clearForms()
        this.show = false
        this.loading = false

        this.$emit('callback', '')
      } catch (e) {
        this.loading = false
      }
    },
    clearForms() {
      this.$refs['tmpResource'].resetFields()
      this.$refs.resourceUpload.clearFiles()
    }
  }
}
</script>

<style scoped>
.upload-allow-hint {
  display: -webkit-box;
  display: -moz-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

.el-pagination__rightwrapper {
    float: right;
}
.catalog-resource-list .logo-file {
  max-width: 124px;
  max-height: 108px;
  vertical-align: middle;
}
</style>
<style scoped>
.catalog-resources-upload-dlg .el-dialog {
  width: 650px;
}
@media (max-width: 480px) {
  .catalog-resources-upload-dlg .el-dialog {
    width: 96%;
  }
}
.resource-tags i{
  padding-right: 0
}
</style>
