const uploadMinxins = {
    props:{
        fkId: {
            required: true
        },
        fkType: String,
        isDisabled: {
            type: Boolean,
            default: false
        },
        candownload: {
            type: Boolean,
            default: true
        },
        plFileType: {// 逗号分隔的文件类型，.doc,.jpg。。
            type: String,
            default: ""
        },
        disableFileType: {// 禁止使用的文件类型，逗号分隔的文件类型，.doc,.jpg。。
            type: String,
            default: ""
        },
        isView: {//是否只可查看
            type: Boolean,
            default: false
        },
        limit: {
            type: Number,
            default: 0
        },
        extraPath: {
            type: String,
            default: ""
        },
        ifTempRemove: {
            type: Boolean,
            default: false
        },
        tempRemoveFile: {
            type: Array,
            default: () => {
                return [];
            }
        },//临时删除的附件
        field: {
            type: String,
        }, // 附件变更时的记录字段
        uploadFileRecord: {
            type: Function
        }, // 附件的变更记录方法
        downInstructions: { //是否需要下载日志
            type: Boolean,
            default: false
        },
        waterMakeConfig: {//水印
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    data(){
        return {
            fileFkId: "",
            uploadUrl: "",
            fileList: [],
            divId: "divId_" + this.COMMON_FUNC.getUUID(),
            defaultImg: 'this.src="' + require('../images/emipty.png') + '"',
            acceptFileType: "", // 允许上传的文件类型
            fileTypeValid: true, // 文件类型验证结果，当前element上传前验证失败触发了删除方法，但是我们不需要
            tempDialogVisible: false, //是否显示虚拟dialog
            // key即为文件类型又为图片名称
            objFileTypeImgs: {
                word: ["docx", "doc"],
                excel: ["xlsx", "xls"],
                powerpoint: ["ppt", "pptx"],
                compress: ["rar", "zip", "gz", "jar", "arj", "z"],
                video: ["mp4", "avi", "flv", "rmvb", "3gp", "mov", "m4v", "wmv", "asf", "asx", "rm", "dat", "mkv", "vob"],
                sound: ["mp3", "wma", "wav", "midi", "ape", "flac"],
                pdf: ["pdf"],
                txt: ["txt"],
                project: ["mpp"],
                visio: ["vsdx", "vsd"]
            },
            loading: false,
            objExtensionToImgType: {},
            //预览
            preview: {
                //显示音/视频预览
                audiovisualDialogVisible: false,
                audiovisualSrc: '',
                audiovisualType: '',
                audiovisualId: ''
            },
            ap: {
                container: '',
                audio: {
                    url: '',
                }
            },
            clickText: '播放',
            icon: "el-icon-video-play",
            type: "success",
            disableFileArr: [], // 不可以上传的文件类型
            hasWater: false,
            waterdialogVisible:false,
            checkWaterMarkText:"",
            downloadWaterMake:{
                waterMakeText: "我是水印",
                fileName:"水印下载",
                fileType:"png",
                fileUrl:""
            }
        }
    },
    watch: {
        fkId() {
            this.initUpload();
        },
        fkType() {
            this.initUpload();
        },
        fileList() {
            // 将调用此组件的v-model值设置为文件长度以设置必填（若有回调，在下一行增加回调方法）
            this.$emit('input', this.fileList.length == 0 ? "" : "" + this.fileList.length);
        }
    },

    created() {
        this.initSetting();
        this.initUpload();
    },
    methods:{
        /*
        ** 初始化配置
        */
        initSetting() {
            // 初始化文件上传类型
            this.hasWater = this.waterMakeConfig.hasWater;
            let uploadFileType = this.plFileType || ""; // 允许上传的附件类型
            if (uploadFileType) {
                // 转换为字符串，文件类型加上.，原项目无.
                let arr = uploadFileType.split(",");
                let typeArr = [];
                arr.forEach(type => {
                    if (type == "all") { // 原项目all是所有，所有在组件中就是""
                        typeArr.push("");
                    } else if ((type || "").indexOf(".") == -1) {
                        typeArr.push("." + type);
                    } else {
                        typeArr.push(type);
                    }
                });
                uploadFileType = typeArr.join(",");
            }
            this.acceptFileType = uploadFileType;

            this.objExtensionToImgType = {};
            for (let [img, exts] of Object.entries(this.objFileTypeImgs)) {
                exts.forEach(ext => {
                    this.objExtensionToImgType[ext] = img;
                });
            }

            if (this.disableFileType) {
                this.disableFileArr = this.disableFileType.split(",");
            }
        },
        /*
        ** 初始化上传组件
        */
        initUpload() {
            let vm = this;
            vm.fileFkId = (vm.fkId || "");
            if (vm.fkType) {
                vm.fileFkId += "_" + (vm.fkType || "");
            }
            if (!vm.fkId) {
                vm.fileList = [];
                return;
            }
            vm.uploadUrl = vm.api.baseUploadUrl + "upload";
            vm.initFiles();
        },
        /*
        ** 附件上传成功后调用
        */
        onSuccess() {
            this.$message("附件上传成功");
            this.initFiles();
        },
        onExceed() {
            this.$message("最大上传文件个数为：" + this.limit + "，无法继续上传！");
        },
        /*
        ** 文件上传前调用
        */
        beforeUpload(file) {
            Vue.set(file, "isPlay", false);
            let fileSuffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
            if (this.acceptFileType && this.acceptFileType.indexOf(fileSuffix) == -1) { // 判断上传类型
                this.$message.error('不支持' + fileSuffix + '文件类型！');
                this.fileTypeValid = false;
                return false;
            }
            if (this.disableFileArr.length > 0 && this.disableFileArr.indexOf(fileSuffix) > -1) { // 判断上传类型
                this.$message.error('不支持' + fileSuffix + '文件类型！');
                this.fileTypeValid = false;
                return false;
            }
            return true;
        },
        /*
        ** 预览文件
        */
        previewFile(file, index) {
            const type = file.extension.toLowerCase();
            if (type === "jpg" || type === "jpeg" || type === "png") {
                this.previewImg(file, index);
            } else {
                const dtype = this.objExtensionToImgType[type].toLowerCase();
                if (dtype === 'word' || dtype === 'excel' ||
                    dtype === 'powerpoint' || dtype === 'pdf') {
                    this.previewDoc(type, file.id);
                } else if (dtype === 'video') {
                    this.previewAudiovisual(type, file);
                } else if (dtype === 'sound') {
                    this.previewPlaySound(type, file);
                }
            }
        },
        /*
        ** 预览图片
        */
        previewImg(file, index) {
            const viewer = this.$el.querySelector('#viewer-selection').$viewer;
            viewer.images = viewer.images.filter(data => {
                if (data.currentSrc.indexOf("static/images/upload") == -1) {
                    return data;
                }
            });
            viewer.index = index;
            viewer.options.hide = () => {
                // 不延时关闭的话会影响原dialog隐藏显示
                setTimeout(() => {
                    this.tempDialogVisible = false;
                });
            };
            viewer.show();
            this.tempDialogVisible = true;
        },
        /*
        ** 预览文档
        */
        previewDoc(type, fjid) {
            let fjType = '';
            switch (type) {
                case 'doc':
                case 'docx':
                case 'txt':
                    fjType = 'document';
                    break;
                case 'xls':
                case 'xlsx':
                    fjType = 'excel';
                    break;
                case 'ppt':
                case 'pptx':
                    fjType = 'powerPoint';
                    break;
                case 'pdf':
                    fjType = 'pdf';
                    break;
                default:
            }
            const routeData = this.$router.resolve({
                path: '/pdfViewer',
                query: {fjid: fjid, fjType: fjType}
            });
            window.open(routeData.href, '_blank');
        },
        /*
        ** 预览视频
        */
        previewAudiovisual(type, file) {
            this.preview.audiovisualSrc = '';
            const dtype = this.objExtensionToImgType[type];
            this.preview.audiovisualDialogVisible = true;
            // if (dtype === 'video') {
            this.preview.audiovisualSrc = file.downloadUrl;
            this.preview.audiovisualType = 'video/' + type.toLowerCase();
            //自动播放
            this.$nextTick(() => {
                const $player = this.$refs.videoRef.dp;
                (this.preview.audiovisualId !== file.id) && $player.switchVideo({
                    url: file.downloadUrl
                });
                $player.paused && $player.play();
                this.preview.audiovisualId = file.id;
            });
            // }
        },
        /*
        **播放音频
        */
        previewPlaySound(type, file) {
            let audio = this.$refs.aplayer;
            if (this.ap.container) {
                if (!this.ap.audio.paused) {
                    this.ap.pause();
                    this.clickText = '播放';
                    this.icon = "el-icon-video-play";
                    this.type = "success";
                } else {
                    this.ap.play();
                    this.clickText = '暂停';
                    this.icon = "el-icon-video-pause";
                    this.type = "danger";
                }
            } else {
                const abc = new APlayer({
                    container: audio,
                    audio: {
                        url: file.downloadUrl,
                    }
                });
                abc.play();
                this.clickText = '暂停';
                this.icon = "el-icon-video-pause";
                this.type = "danger";
                this.ap = abc;
            }
        },
        /*
        ** 音/视频预览窗口关闭前调用
        */
        audiovisualBeforeClose(done) {
            const $player = this.$refs.videoRef.dp;
            !$player.paused && $player.pause();
            done();
        },
        /*
        ** 下载文件
        */
        downLoadWaterMarkFile(){
            if(!this.checkWaterMarkText){
                this.$message.error("请选择水印模板！");
                return false;
            }
            if(this.checkWaterMarkText||!this.waterdialogVisible){
                this.getImageFileFromUrl(this.downloadWaterMake.fileUrl, this.downloadWaterMake.fileName)
                    .then((response) => {
                        // 返回的是文件对象，使用变量接收即可
                        try {
                            this.getBase64(response).then((imgResult) => {
                                let waterMake = {
                                    waterMakeText: this.checkWaterMarkText||this.downloadWaterMake.waterMakeText,
                                    fileName:this.downloadWaterMake.fileName,
                                    fileType:this.downloadWaterMake.fileType
                                }
                                this.base64AddWaterMaker(imgResult, waterMake,"download").then((res) => {
                                    // 这里可以把添加水印后的文件传给后端，我这里只是举例并没有做
                                    this.downloadWaterMake={
                                        waterMakeText: this.waterMakeConfig.defaultWaterMake,
                                        fileName:"",
                                        fileType:"png",
                                        fileUrl:""
                                    }
                                    this.waterdialogVisible = false;
                                });
                            })
                        } catch (error) {
                            this.waterdialogVisible = false;
                            console.log('error:', error);
                        }
                    })
                    .catch((e) => {
                        this.waterdialogVisible = false;
                        console.error(e);
                    })
            }

        },
        downloadFile(url, file) {
            let type = file?file.extension:"";
            let fileName = file?file.name:"";
            if (this.hasWater && (type === "jpg" || type === "jpeg" || type === "png")) {
                this.downloadWaterMake={
                    waterMakeText: this.waterMakeConfig.defaultWaterMake,
                    fileName:fileName,
                    fileType:type,
                    fileUrl:url
                }
                //获取系统参数
                if (this.downInstructions) {
                    //弹出confime
                    this.$prompt('请填写用途', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /\S/,
                        inputValidator: this.validatorXzsm,
                        inputErrorMessage: '用途不能为空!'
                    }).then(({value}) => {
                        if(this.waterMakeConfig.waterArr&&this.waterMakeConfig.waterArr.length>0){
                            this.waterdialogVisible = true;
                        }else{
                            this.downLoadWaterMarkFile();
                        }
                        let loginUser = this.CACHE_GLOBAL.getLoginUser();
                        let downLoadUser = "&&";
                        if (loginUser && loginUser.id) {
                            downLoadUser = loginUser.id;
                        }
                        this.axios.post(this.api.upload.addUploadLog,
                            {"fkId": this.fkId,"id":file.id,"fileName":fileName,
                                "downloadUser":downLoadUser,"xzsm":value})
                    });
                }
                if(this.waterMakeConfig.waterArr&&this.waterMakeConfig.waterArr.length>0){
                    this.waterdialogVisible = true;
                }else{
                    this.downLoadWaterMarkFile();
                }
            } else {
                this.uploadPrompt(url);
            }
        },
        /*
        ** 下载文件
        */
        uploadPrompt(url) {
            let loginUser = this.CACHE_GLOBAL.getLoginUser();
            let downLoadUser = "&&";
            if (loginUser && loginUser.id) {
                downLoadUser = loginUser.id;
            }
            url = url + "&downloadUser=" + downLoadUser;
            //获取系统参数
            if (this.downInstructions) {
                //弹出confime
                this.$prompt('请填写用途', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /\S/,
                    inputValidator: this.validatorXzsm,
                    inputErrorMessage: '用途不能为空!'
                }).then(({value}) => {
                    url = url + "&xzsm=" + value;
                    this.startUpload(url);
                });
            } else {
                this.startUpload(url);
            }
        },
        /**
         * 开始下载
         * @param url
         */
        startUpload(url) {
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.click();
            link = null;
        },
        /**
         * 下载说明
         * @param value
         */
        validatorXzsm(value) {
            if (!value) {
                return "下载说明不能为空!";
            }
        }
    }
}

export default uploadMinxins;
