<template>
  <el-form-item :label="label" :rules="requireRule(required, label)" :prop="prop" :label-width="labelWidth"
                >
    <el-upload
      :action="uploadImgUrl"
      class="upload-demo"
      :list-type="listType"
      :data="data"
      :disabled="disabled"
      :show-file-list="showFileList"
      :limit="limit"
      with-credentials
      :on-success="handleAvatarSuccess"
      :before-upload="beforeFileUpload"
      :onRemove="handleRemove"
      :before-remove="beforeRemove"
      :on-preview="handlePreOrDown"
      :on-change="handleChange"
      :style="{width: changeWidth?changeWidth:'350px',overflow: 'hidden'}"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :multiple="multiple">
      <input style="display: none" v-model="formRef.model[prop]"/>
      <el-button size="small" type="primary"  :disabled="disabled" v-if="!disabled">点击上传</el-button>
      <el-button size="small" type="primary"  :disabled="disabled" v-if="disabled">点击上传</el-button>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-form-item>
</template>

<script>

import mixin from './mixin'
import { pull, join } from 'lodash'
// import {download} from "../../../../api/utils";
import {isBlank} from "../../../../utils";

/**
 * 文件上传组件
 */
export default {
  mixins: [mixin],
  props: {
    limit: {
      type: Number,
      default: 10,
    },
    labelWidth: {
      type: String
    },
    changeWidth: {
      type: String
    },
    multiple:{
      type: Boolean,
      default: false
    },
    addOrEditVisible: {
      type: Boolean,
      default: true,
    },
    uploadImgUrl:{
      type: String,
      default: "",
    },
    listType:{
      type:String,
      default:"text"
    },
    data:{
      type:Object,
      default:{}
    },
    prompts:{
      type:String,
      default:""
    },
    hasCode: {
      type: Boolean,
      default: false,
    },
    form:{
      type:Object,
      default:{}
    },
    //是否显示已上传的文件
    showFileList:{
      type: Boolean,
      default: true
    },
    disabled:{
      type:Boolean,
      default:false
    },
    maxSize:{
      type:Number,
      default: 20,
      desc:'单个文件大小限制MB'
    }
  },
  data() {
    return {
      imageUrl: '',
      dialogVisible: false,
      fileList:[],
      resultList:[],
      needConfirm:true,
      first:true,
      dialogImageUrl:""
    };
  },
  created() {
    this.$watch(() => this.$parent.model[this.prop], val => {
      if(val && this.first){
        this.fileList = val
      }
    }, {immediate: true})

    if(this.$parent.model[this.prop]){
      this.imageUrl = process.env.VUE_APP_BASE_API + '/oss/filedownload/'

    }
  },
  mounted() {
  },
  methods: {
    handleAvatarSuccess(res, file,fileList) {
      this.first  =  false
      setTimeout(()=>{
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code == 200 || res.code == 0){
          this.$parent.model[this.prop] =  fileList.map(file => {
            if(file.response != undefined){
              return file.response != undefined ? file.response.result[0] : undefined
            }else{
              return file
            }
          })
          // this.msgSuccess("上传成功！");
        }
      },100)
    },
    beforeFileUpload(file) {
      return  new Promise((resolve,reject)=>{
        let size = file.size
        if(size > this.maxSize * 1024 * 1024){
          this.$message.error("单个文件不能超过" + this.maxSize + "MB")
          this.needConfirm = false
          reject('error')
        }
        if(!this.hasCode){
          this.$message.error(this.prompts == "" ? "请先扫码获取运单号！" : this.prompts);
          reject('error')
        }
        resolve()
      })

    },
    handleChange(file,fileList){

    },
    handleRemove({ name, url }) {
      if(this.needConfirm){
        this.$parent.model[this.prop] = this.$parent.model[this.prop].filter(item => item.url != url)
      }
      this.needConfirm = true
    },
    beforeRemove(file, fileList) {
      if(this.needConfirm){
        return this.$confirm(`确定移除 ${ file.name }？`,'提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type: 'warning'
        });
      }
    },
    handlePreview(){

    },
    handleExceed(files, fileList) {
      this.$message.error(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },

    handlePreOrDown(file){
      if(this.listType == 'picture-card'){

        //照片墙，使用预览方法
        this.handlePictureCardPreview(file);
      }else {
        //其他下载
        this.handleDownload(file);
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      const fileName =  file ? file.url : null
      if(fileName){
        download(fileName).then(data => {
          let blob = new Blob([data]) //type是文件类，详情可以参阅blob文件类型
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = blobURL
          a.download = file.name
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        })
      }
    },
  },
}
</script>
