<template>
    <div :class="prefixCls">
        <div 
            v-for="(item, index) in imagesData"
            :class="prefixCls + '-item'" 
            :key="index">
            <img :src="item"/>
            <div :class="prefixCls + '-operate'">
                <span @click="handlePreview(item)">预览</span>
                <span @click="handleRemoveFile(fileFormData[index], index)">删除</span>
            </div>
        </div>
        <div 
            v-for="(item, index) in lastFileFormData"
            :class="prefixCls + '-item'" 
            :key="item.fileId">
            <img :src="item.thumbUrl"/>
            <div :class="prefixCls + '-operate'">
                <span @click="handlePreview(item.url)">预览</span>
                <span @click="handleRemoveLastFile(item, index)" v-if="!readonly">删除</span>
            </div>
        </div>
        <Upload
            v-if="!readonly"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            :max-size="maxSize"
            :accept="accept"
            action="security-image-upload"
            multiple>
            <div :class="[prefixCls + '-item', prefixCls + '-control']">
                +
            </div>
        </Upload>
        <YYDialog v-model="showDialog"
            :transfer="true"
            title="查看图片">
            <img :src="currentImage" style="max-width: 100%"/>
        </YYDialog>
    </div>
</template>
<script>
    import { deepCopy, bytesToSize } from '../../../utils/assist'
    import axios from 'axios'
    import Upload from '../../base/upload/'
    import YYMessage from '../../base/message/'
    import YYDialog from '../../base/dialog/'
    import YYLoading from '../../base/loading/'
    import Sortable from 'sortablejs'

    const prefixCls = 'yy-security-image-upload'
    export default {
        name: 'YYSecurityImageUpload',
        components: {
            Upload,
            YYMessage,
            YYLoading
        },
        props: {
            objectName: {
                type: String,
                required: true
            },
            objectId: {
                type: String | Number,
                required: true
            },
            lastId: {
                type: String | Number
            },
            maxSize: {
                type: Number | String,
                default: 300 * 1024
            },
            security: {
                type: String,
                default: 'PUBLIC'
            },
            host: {
                type: String,
                default: 'http://ezone.imp.pub.caep'
                // default: '//ezone.pub-dev.caep'
            },
            readonly: {
                type: Boolean,
                default: false
            },
            compress: {
                type: Boolean,
                default: false
            },
            accept: {
                type: String,
                default: 'image/*'
            }
        },
        data() {
            return {
                prefixCls,
                fileForm: [], // 上传文件本地数据
                imagesData: [], // 本地回显图片地址
                fileFormData: [], // 上传文件, 提交后台数据
                lastFileFormData: [],
                deleteFileIds: [],
                showDialog: false,
                currentImage: ''
            }
        },
        filters: {
            bytesToSize
        },
        watch: {
            lastId: {
                immediate: true,
                handler: function () {
                   this.getLastFileFormData() 
                }
            }
        },
        methods: {
            getLastFileFormData() {
                if(this.lastId) {
                    const action = `${this.host}/cooperation/rest/v1/image/security/${this.objectName}/${this.lastId}/list?businessId=${this.objectId}&businessType=${this.objectName}`
                       
                    axios.get(action, {
                        withCredentials: true
                    }).then(res => {
                        this.lastFileFormData = res.data && res.data.list || []
                    })
                }
            },
            getFiles() { // 获取所有files
                const files = this.fileFormData.concat(this.lastFileFormData)
                return files
            },
            handlePreview(path) {
                this.showDialog = true
                this.currentImage = path
            },
            handleRemoveFile(item, key) { // 删除当前上传文件
                this.fileForm.splice(key, 1)
                this.fileFormData.splice(key, 1)
                this.imagesData.splice(key, 1)
                this.$emit('on-file-remove', item)
            },
            handleRemoveLastFile(item, key) { // 删除曾经上传文件
                this.lastFileFormData.splice(key, 1)
                this.deleteFileIds.push(item.fileId)
                this.$emit('on-file-remove', item)
            },
            handleStartUpLoad() {
                return new Promise((resolve, reject) => {
                    // 没有附件时直接resolve
                    if(!this.fileFormData.length 
                    && !this.deleteFileIds.length 
                    && !this.lastFileFormData.length) return resolve(true)
                    
                    let formData = new FormData()
                    this.fileForm.forEach((file) => {
                        formData.append('files', file)
                    })
                    formData.append('params', JSON.stringify(this.fileFormData))

                    // 更换当前已存在fileId的objectId映射
                    if(this.lastFileFormData.length) {
                        const fileIds = this.lastFileFormData.map(item => {
                            return item.fileId
                        })
                        formData.append('fileIds', JSON.stringify(fileIds))
                    }


                    // 更新已删除文件
                    if(this.deleteFileIds.length) {
                        formData.append('deleteFileIds', JSON.stringify(this.deleteFileIds))
                    }
                    
                    const action = `${this.host}/cooperation/rest/v1/image/security/${this.objectName}/${this.objectId}?compress=${this.compress}&businessId=${this.objectId}&businessType=${this.objectName}`
                    YYLoading.show({
                        text: '正在上传附件'
                    })
                    axios.defaults.timeout = 1000 * 60 * 60 * 24
                    axios.post(action, formData, {
                        withCredentials: true
                    }).then(res => {
                        YYLoading.hide()
                        resolve(true)
                    }).catch(()=> {
                        YYLoading.hide()
                        YYMessage.error('附件上传失败')
                        resolve(false)
                    })
                })
            },
            beforeUpload (file) {
                if(file.size > this.maxSize * 1024) {
                    YYMessage.error('附件超过单附件大小限制')
                    return false
                }

                let key = -1
                this.fileFormData.forEach((item, index) => {
                    if(item.fileName === file.name) {
                        key = index
                    }
                })
                const param = {
                    fileSize: file.size,
                    fileName: file.name,
                    downloadEnable: true,
                    security: this.security
                }
    
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload =  (e) => {
                    if(key === -1) {
                        this.fileForm.push(file)
                        this.fileFormData.push(deepCopy(param))
                        this.imagesData.push(e.target.result) 
                    } else {
                        this.fileForm.splice(key, 1, file)
                        this.imagesData.splice(key, 1, e.target.result) 
                        this.fileFormData.splice(key, 1, deepCopy(param))
                    }
                }
                
                this.$emit('on-change', this.getFiles())
                return false
            }
        }
    }
</script>