<template>
  <el-form-item class="image-item" :label="label" :label-width="labelWidth" :rules="requireRule(required, label)" :prop="prop">
      <el-upload
        ref="upd"
        :action="uploadImgUrl"
        class="avatar-uploader"
        :list-type="listType"
        :data="data"
        :disabled="disabled"
        :show-file-list="false"
        :fileList="fileLists || fileList"
        :limit="limit"
        with-credentials
        :on-success="handleAvatarSuccess"
        :before-upload="beforeImageUpload"
        :onRemove="handleRemove"
        style="width: 148px;overflow: hidden"
        :multiple="false"
        :on-exceed="handleExceed"
      >
        <!--      <el-button size="small" type="primary" v-if="addOrEditVisible" class="upload-button">点击上传</el-button>-->
        <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100%;height: 100%">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <input style="display: none" v-model="$parent.model[prop]"></input>
        <!--      <label class="left-view">-->
        <!--        <i  class="inner-icon el-icon-view"></i>-->
        <!--      </label>-->
      </el-upload>
      <el-button size="small" type="primary" v-if="imageUrl" :disabled="false" @click="handlePictureCardPreview" class="upload-button">查看</el-button>
      <el-button size="small" type="danger" v-if="imageUrl&&!disabled" @click="removePic"  class="upload-button">删除</el-button>

      <el-dialog :visible.sync="dialogVisible" :title="title" :append-to-body="true" width="600px">
        <div style="width: 100%">
          <img width="100%" height="100%" :src="imageUrl" alt="">
        </div>

      </el-dialog>
    </el-form-item>
</template>

<script>
import mixin from './mixin'
// import { fileupload, getFile } from '@/api/oa/file.js'
import { pull, join } from 'lodash'
// import {download} from "../../../../api/utils";

// 通过字符串获取文件列表
const extractFiles = (value) => {
  if (!value || value.trim() === '') {
    return []
  }
  return value.split(',').map((data) => {
    const strs = data.split('::')
    const name = strs[0]
    const url = strs[1]
    return { uid: url, url, name, status: 'success' }
  })
}

/**
 * 文件上传组件
 */
export default {
  mixins: [mixin],
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    addOrEditVisible: {
      type: Boolean,
      default: true,
    },
    uploadImgUrl:{
      type: String,
      default: "",
    },
    listType:{
      type:String,
      default:"picture-card"
    },
    data:{
      type:Object,
      default:{}
    },
    hasCode: {
      type: Boolean,
      default: false,
    },
    form:{
      type:Object,
      default:{}
    },
    fileLists:{
      type:Array,
      default: function() {
      return []
      }
    },
    labelWidth:{
      type: String,
    },
    beforeMessage:{
      type:String,
      default:'请先获取车牌号！'
    },
    baseUrl:{
      type:String,
      default:''
    },
    title:{
      type: String,
      default:'图片详情'
    }
  },
  data() {
    return {
      imageUrl: '',
      dialogVisible: false
    };
  },
  computed: {
    value() {
      return this.$parent.model[this.prop]
    },
    fileList() {
      return extractFiles(this.value)
    },
  },
  created() {
    // 修复表单校验问题，有些自定义组件有值但校验失败
    // Vue.set(this.$parent.model, this.prop, undefined)
    if(this.$parent.model[this.prop]){
      this.imageUrl = process.env.VUE_APP_BASE_API + '/oss/filedownload/' +  this.$parent.model[this.prop]
    }
  },
  methods: {
    removePic(){
      this.$parent.model[this.prop] = ""
      this.imageUrl = ""
      this.$refs.upd.clearFiles();
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if(res.code == 200 || res.code == 0){
        this.$parent.model[this.prop] = res.result || undefined;
        this.msgSuccess("上传成功！");
      }

    },
    beforeImageUpload(file) {
      if(!this.hasCode){
        this.$message.error(this.beforeMessage);
        return false
      }
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 500;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG或PNG 格式!");
      }
      return isJPG;
    },
    extractFiles,
    handleRemove({ name, url }) {
      const key = `${name}::${url}`
      const urls = (this.value || '').split(',')
      const newValue = join(pull(urls, key), ',')
      this.$parent.model[this.prop] = newValue
      setTimeout(() => this.$parent.validateField(this.prop), 500)
    },
    handleDownload({ name, url }) {
      download(url).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 = name
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      })
    },
    handleExceed(files,fileList){
     if(files && files.length > 0){
       this.$message.error("请先删除已上传的图片")
     }
    }
  },
}
</script>


<style scoped>
  .inner-icon{
    transform: rotate(45deg);
    display: inline-block;
  }
  .left-view{
    position: absolute;
    left: 25px;
    top: -3px;
    width: 50px;
    height: 26px;
    background: #13ce66;
    text-align: center;
    transform: rotate(45deg);
    box-shadow: 0 1px 1px #ccc;
  }
.image-item .is-disabled .upload-button {
  display: none !important;
}
.image-item {
  height: auto;
  min-height: 146px;

}
.image-item .el-upload-list__item {
  transition: none !important;
}
.image-item .el-icon-close-tip {
  display: none;
}


</style>
