<template>
    <div :class="[prefixCls + '-list', prefixCls + '-list-echo']" v-if="data.length || showWhenNoData">
        <div :class="prefixCls + '-choose'" 
            v-if="!disabledBatchDownload">
            <div :class="prefixCls + '-count'">{{t('upload.file')}}（{{data.length}}）</div>
            <YYButton type="ghost" size="small" @click="handleBatchDownload" v-if="batchDownloadable">{{t('upload.batchDownload')}}</YYButton>
        </div>
        <div 
            v-for="item in data"
            :class="prefixCls + '-item'" 
            :key="item.fileId">
            <div :class="prefixCls + '-item-info'" v-if="itemLayout == 'default'">
                <YYCheckbox 
                    v-if="!disabledBatchDownload"
                    v-model="item.checked" 
                    :disabled="!item.downloadEnable"></YYCheckbox>
                <span :class="prefixCls + '-item-security'" v-if="!disabledSecurity">
                    {{t('upload.secretLevel')}}：
                    <span :class="prefixCls + '-item-security-' + item.security">
                        {{security[item.security] && security[item.security].text || ''}}
                    </span>
                </span>
                <YYFileLogo :type="getType(item.fileName)"></YYFileLogo>
                <span :class="prefixCls + '-item-filename'" :title="item.fileName">{{item.fileName}}</span>
                <span 
                    v-if="item.downloadEnable"
                    :class="prefixCls + '-item-download'" 
                    @click="handleDownload(item)">{{t('upload.download')}}</span>
                <span 
                    :class="prefixCls + '-item-download'" 
                    @click="handlePreview(item)">{{t('upload.preview')}}</span>
                <span 
                    v-if="enableDelete && item.deletable"
                    :class="prefixCls + '-item-download'" 
                    @click="handleDelete(item)">{{t('upload.delete')}}</span>
                <span :class="prefixCls + '-item-filesize'">
                    {{item.fileSize | bytesToSize}}
                </span>
            </div>
            <div :class="prefixCls + '-item-dbline'" v-else-if="itemLayout == 'dbline'">
                <div>
                    <YYCheckbox 
                        v-if="!disabledBatchDownload"
                        v-model="item.checked" 
                        :disabled="!item.downloadEnable">
                    </YYCheckbox>
                    <YYFileLogo :type="getType(item.fileName)"></YYFileLogo>
                    <span :class="prefixCls + '-item-filename'" :title="item.fileName">{{item.fileName}}</span>
                </div>
                <div>
                    <span :class="prefixCls + '-item-security'" v-if="!disabledSecurity">
                        {{t('upload.secretLevel')}}：
                        <span :class="prefixCls + '-item-security-' + item.security">
                            {{security[item.security] && security[item.security].text || ''}}
                        </span>
                    </span>
                    <span>
                        <span 
                            v-if="item.downloadEnable"
                            :class="prefixCls + '-item-download'" 
                            @click="handleDownload(item)">{{t('upload.download')}}</span>
                        <span 
                            :class="prefixCls + '-item-download'" 
                            @click="handlePreview(item)">{{t('upload.preview')}}</span>
                        <span 
                            v-if="enableDelete && item.deletable"
                            :class="prefixCls + '-item-download'" 
                            @click="handleDelete(item)">{{t('upload.delete')}}</span>
                        <span :class="prefixCls + '-item-filesize'">
                            {{item.fileSize | bytesToSize}}
                        </span>
                    </span>
                </div>
            </div>
        </div>
        <div v-if="!data.length" :class="prefixCls + '-no-data'">{{t('upload.noFiles')}}</div>
    </div>
</template>
<script>
    import Locale from '../../../mixins/locale'
    import Empty from '../../base/empty'
    import axios from 'axios'
    import YYFileLogo from '../../base/file-logo/'
    import YYLoading from '../../base/loading/'
    import YYMessage from '../../base/message/'
    import { bytesToSize } from '../../../utils/assist'
    
    const prefixCls = 'yy-security-upload'
    export default {
        name: 'YYSecurityUpload',
        mixins: [ Locale ],
        components: {
            YYFileLogo,
            Empty
        },
        props: {
            objectName: {
                type: String,
                required: true
            },
            objectId: {
                type: String | Number,
                required: true
            },
            disabledSecurity: { // 禁止显示密级
                type: Boolean,
                default: false
            },
            disabledBatchDownload: { // 禁止显示批量下载
                type: Boolean,
                default: false
            },
            host: {
                type: String,
                // default: '//ezone.imp.pub.caep'
                default: 'http://ezone.pub-dev.caep'
            },
            downLoadDescription: {
                type: String,
                default: ''
            },
            itemLayout: {
                type: String,
                default: 'default' // default -> 默认单行布局, dbline -> 两行布局
            },
            showWhenNoData: {
                type: Boolean,
                default: false
            },
            enableDelete: { // 是否启用删除按钮
                type: Boolean,
                default: false
            },
            beforeDelete: { // 删除前置判断
                type: Function,
                default: () => true
            },
            authDelete: {   // 单个文件删除控制
                type: Function,
                default: () => true
            },
            withCreator: {  // 接口返回的数据是否包含上传者信息
                type: [Number, String],
                default: 0
            }
        },
        data() {
            return {
                prefixCls,
                data: [],
                security: { // 密级
                    PUBLIC: {
                        limit: 0,
                        text: this.t('upload.public')
                    },
                    INTERNAL: {
                        limit: 1,
                        text: this.t('upload.internal')
                    },
                    SECRET: {
                        limit: 2,
                        text: this.t('upload.secret')
                    },
                    CONFIDENTIAL: {
                        limit: 3,
                        text: this.t('upload.confidential')
                    }
                },
                isIe: false
            }
        },
        computed: {
            downloadIds() { // 整理批量下载id
                return this.data.filter(item => item.checked).map(item => item.fileId).join(',') || ''
            },
            batchDownloadable() {
                return this.data.some(e => e.downloadEnable)
            }
        },
        filters: {
            bytesToSize
        },
        methods: {
            getFiles() { // 向外暴露获取files方法
                return this.data
            },
            getType(data) { // 获取当前文件类型
                if(typeof data != 'string') return ''
                return data.split('.').pop().toLocaleLowerCase() || ''
            },
            getLastFileFormData() { // 获取最后一次上传的文件列表
                const action = `${this.host}/cooperation/rest/v1/file/security/${this.objectName}/${this.objectId}?withCreator=${this.withCreator}`
                axios.get(action, {
                    withCredentials: true
                }).then(res => {
                    let data = res.data && res.data.data || []
                    data.forEach(item => {
                        item.checked = false
                        item.deletable = true
                        this.confirmOperation(this.authDelete, item).then(deletable => {
                            item.deletable = deletable
                        })
                    })
                    this.data = data
                }).catch(err => {
                    this.data = []
                    console.error(err)
                })
            },
            handleDownload(data) { // 下载
                if (this.isIe) {
                    YYMessage.warning('请切换到360极速模式')
                    return
                }
                const action = `${this.host}/cooperation/rest/v1/file/security/${data.fileId}/url/download?businessId=${this.objectId}&businessType=${this.objectName}`
                
                YYLoading.show()
                axios.get(action, {
                    withCredentials: true
                }).then(res => {
                    YYLoading.hide()
                    if(res.data && res.data.url) {
                        window.open(res.data.url, '_blank')
                    }
                }).catch((error) => {
                    YYLoading.hide()
                })
            },
            handleBatchDownload() { // 批量下载
                if (this.isIe) {
                    YYMessage.warning('请切换到360极速模式')
                    return
                }
                let downloadIds = this.downloadIds
                if(!this.downloadIds) {
                    downloadIds = this.data.filter(item => item.downloadEnable).map(item => item.fileId).join(',') || ''
                }
                if(!downloadIds) return YYMessage.warning(this.t('upload.pleaseSelectFile'))
                let action = ''
                let downLoadDescription = this.downLoadDescription
                if(downLoadDescription) {
                    action = `${this.host}/cooperation/rest/v1/file/security/file/list/zip/stream?downloadFlag=true&fileIds=${downloadIds}&description=${downLoadDescription}&businessId=${this.objectId}&businessType=${this.objectName}`
                } else {
                    action = `${this.host}/cooperation/rest/v1/file/security/file/list/zip/stream?downloadFlag=true&fileIds=${downloadIds}&businessId=${this.objectId}&businessType=${this.objectName}`
                }
                window.open(action, '_blank')
            },
            handlePreview(data) { // 预览
                if (this.isIe) {
                    YYMessage.warning('请切换到360极速模式')
                    return
                }
                const action = `${this.host}/cooperation/rest/v1/file/security/${data.fileId}/url/preview?businessId=${this.objectId}&businessType=${this.objectName}`
                YYLoading.show()
                axios.get(action, {
                    withCredentials: true
                }).then(res => {
                    YYLoading.hide()
                    if(res.data && res.data.url) {
                        window.open(res.data.url, '_blank')
                    }
                }).catch((error) => {
                    YYLoading.hide()
                })
            },
            handleDelete(data) {
                this.confirmOperation(this.beforeDelete, data).then(flag => {
                    if (flag) {
                        YYLoading.show()
                        axios.delete(`${this.host}/cooperation/rest/v1/file/security/${this.objectName}/${this.objectId}/${data.fileId}`, {
                            withCredentials: true
                        }).then(res => {
                            YYLoading.hide()
                            if (res.data && res.data.n == 1) {
                                let index = -1
                                for (let i = 0;i < this.data.length;i ++) {
                                    if (this.data[i].fileId == data.fileId) {
                                        index = i
                                        break
                                    }
                                }
                                if (index != -1) {
                                    this.data.splice(index, 1)
                                    this.$forceUpdate() //强制刷新页面
                                }
                                YYMessage.success(this.t('upload.deleteSucceeded'))
                            }
                        }).catch(err => {
                            console.error(err)
                            YYLoading.hide()
                        })
                    }
                })
            },
            confirmOperation(func, ...args) {
                return new Promise((resolve, reject) => {
                    if (typeof func != 'function') return resolve(false)
                    const result = func(...args)
                    if (result instanceof Promise) {
                        return resolve(result)
                    }
                    resolve(!!result)
                })
            }
        },
        created() {
            if (!!window.ActiveXObject || "ActiveXObject" in window) this.isIe = true
            this.getLastFileFormData()
        }
    }
</script>