<template>
        <el-form-item class="image-item" :label="label" :rules="requireRule(required, label)" :prop="prop">
            <el-upload
                action=""
                :fileList="fileList"
                :before-upload="beforeUpload"
                :httpRequest="httpRequest"
                :onChange="handleChange"
                :onRemove="handleRemove"
                accept="image/jpg, image/png, image/jpeg"
                :on-preview="handlePictureCardPreview"
                :class="{'is-disabled': fileList.length >= limit || disabled}"
                listType="picture-card" 
                :multiple="false">
                <i class="el-icon-picture-outline" style="font-size:60px;margin-top:40px;"></i>
                <div slot="file" slot-scope="{file}" v-if="disabled">
                    <el-image :src="file.url" alt="" fit="cover" style="height:146px;width:146px;"></el-image> 
                    <span class="el-upload-list__item-status-label">
                        <i class="el-icon-upload-success el-icon-check"></i>
                    </span>
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <i class="el-icon-zoom-in"></i>
                        </span>
                    </span>
                </div>
            </el-upload>
            
          
            <el-dialog :visible.sync="dialogVisible" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <el-dialog  title="图片剪切" 
                    style="z-index: 9999"
                    :visible.sync="isOpen" 
                    width="1000px"  
                    append-to-body="true"
                    modal-append-to-body="true"
                    :close-on-press-escape="false" 
                    :close-on-click-modal="false"
                    :before-close="colseCut"> 
            <cut-picture
                :Name="cropperName"
                @uploadImgSuccess = "httpRequest"
                ref="child"
                :width="width"
                :height="height">
            </cut-picture>
        </el-dialog>
        </el-form-item>
</template>

<script>
import mixin from './mixin'
import {uploadImage} from '@/api/system/common'
import CutPicture from '@/views/merchant/service/components/CutPicture'
import {join} from 'lodash'


// 通过字符串获取文件列表
const extractFiles = value => {
    if (!value || value.trim() === '') {
        return []
    }
    return value.split(',').map(url => ({uid: url, url, status: 'success'}))
}
// 将图片路径合并到一个字符串
const extractUrls = fileList => {
    return join(fileList.map(file => file.url), ',')
}

/**
 * 图片选择组件
 */
export default {
components: {CutPicture},
  mixins: [mixin],
  props: {
    limit: {
      type: Number,
      default: 1
    },
    CutFlag:{
        type:Boolean,
        default:false
    },
    width:{
        type:Number,
        default:750
    },
    height:{
        type:Number,
        default:600
    }
  },
  data(){
    return {
      fileList: extractFiles(),
      dialogVisible: false,
      dialogImageUrl: '',
      url:"",
      isOpen:false,
      files:"",
      cropperName:""
    }
  },
  created(){
      this.$watch(() => this.$parent.model[this.prop], (value, oldValue) => {
          if (value && !oldValue) {
              this.fileList = extractFiles(value)
          }
    }, {immediate: true}) 
  },
  methods: {
        httpRequest({file}){
            if(this.CutFlag){
                this.isOpen = !this.isOpen
            }
            const prom =  new Promise((resolve, reject) => {
                uploadImage(file).then(res => {
                    const {code, url} = res
                    let target = null
                    console.log(this)
                    for (let i = 0; i < this.fileList.length; i++) {
                        const element = this.fileList[i]
                        if (element.uid === file.uid) {
                            target = i
                            break
                        }
                    }
                    if (target === null) {
                        this.$message.warning('文件上传异常')
                        return
                    }

                    if (code === 200){
                        this.fileList[target].url = url
                        const image = new Image()
                        image.src = url
                        this.dialogImageUrl = url;
                        
                        setTimeout(() => this.$parent.clearValidate(), 600)
                    } else {
                        this.fileList.splice(target, 1)
                        this.$message.warning('上传失败, 请重新上传')
                    }
                    this.$parent.model[this.prop] = extractUrls(this.fileList)
                    resolve()
                })
            })
            prom.abort = () => {}
            return prom
        },
        beforeUpload(e){
            if(this.CutFlag){
                this.isOpen = !this.isOpen
                this.files = e
                this.fileList.push(e)
                setTimeout(() => this.$refs.child.selectImg(e),100)
                return false
            }
            return true
        },
        handleRemove(file, fileList){
            this.fileList = fileList
            this.$parent.model[this.prop] = extractUrls(this.fileList)
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        colseCut(){
            this.fileList.pop();
            this.isOpen=false
            this.$parent.model[this.prop] = extractUrls(this.fileList)
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        handleChange(file, fileList) {
            this.fileList = fileList
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        }
  }
}
</script>

<style>
.image-item .is-disabled .el-upload--picture-card{
  display: none !important;
}
.image-item{
    height: 146px;
}
.image-item .el-upload-list__item {
    transition: none !important;
}
</style>
