<template>
    <div class="uploadFolder">
        <div class="uploadFolder-form">
            <el-form ref="uploadForm" :model="form">
                <el-form-item>
                    <!-- <el-input style="width: 49%;" disabled size="mini" v-model="currentSceneName"></el-input> -->
                    <el-select class="firstScene" v-model="form.scene" placeholder="请选择场景" size="mini">
                        <el-option v-for="(item,index) of scenceList"
                                   :label="item.sceneName"
                                   :value="item.sceneId"
                                   :key="index"
                        >
                        </el-option>
                    </el-select>
                    <el-select class="secondScene" v-if="!!form.secondSceneId" v-model="form.secondSceneId"
                               placeholder="请选择场景" size="mini">
                        <el-option v-for="(item,index) of secondOptionList"
                                   :label="item.sceneName"
                                   :value="item.sceneId"
                                   :key="index"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <div class="selectFolder">
                        <el-input id="fileUploadInpt" size="mini" class="choose_all" disabled
                                  placeholder="请选择文件夹"></el-input>
                        <el-button class="uploadBtn" size="mini" style="background:#2a76cd;color:#fff;"
                                   @click="upload()">上传
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <ul class="fileListbox">
                        <li class="folderName">{{form.folderName}}</li>
                        <li class="fileListLi" v-for="(fileInfo,index) of fileList" :key="index">
                            <span class="filename">{{fileInfo.filename}}</span>
                            <div class="progress">
                                <el-progress :text-inside="true" :stroke-width="18"
                                             :percentage="fileInfo.progress"></el-progress>
                            </div>
                            <div class="uploadBtns">
                                <i v-if="fileInfo.status == 5"
                                   :class="[fileInfo.status == 1? 'el-icon-video-pause icon_warn' : 'el-icon-video-play icon_success']"
                                   @click="fileStatusToggle(fileInfo)"></i>
                            </div>
                        </li>
                    </ul>
                </el-form-item>
            </el-form>
        </div>
        <div class="footer">
            <el-button size="mini" class="fr" :disabled="isUpload" type="primary" style="margin-left: 20px;"
                       @click="distinguish">识别
            </el-button>
            <el-button size="mini" class="fr" type="default" @click="abort">取消</el-button>
        </div>
        <div class="fixedbox" v-if="OCRLoading">
            <div class="message">
                <span>文件上传成功，OCR识别需要几分钟时间，请稍候...</span><br>
                <span><b>{{timedown}}</b>秒后将跳转至列表页</span>
            </div>
        </div>
    </div>
</template>
<script type="text/javascript">
    export default {
        name: 'UploadFolder',
        // props: ['sceneId'],
        data() {
            return {
                form: {
                    scene: '',
                    secondSceneId: '',
                },
                uploafForm: {
                    sceneId: '',
                    folderName: '',
                },
                scenceList: [],
                fileList: [],
                uploader: '',
                isUpload: true, //  是否未上传或正在上传完毕
                currentSceneName: '', // 当前场景的名称
                secondOptionList: [],
                folderIds: [],
                OCRLoading: false,
                timedown: 3,
            }
        },
        mounted() {
            this.getScenceList();
            // this.form.scene = this.sceneId;
            let self = this;
            this.uploader = WebUploader.create({
                auto: false, // 选完文件后，是否自动上传
                swf: './static/WebUploader/Uploader.swf', // swf文件路径
                server: '/upload/uploadFolder', // 文件接收服务端
                formData: self.uploafForm,
                pick: '.choose_all', // 选择文件的按钮。可选
                chunked: false,  // 不分片
                chunkSize: 1024 * 500,
                threads: 1,
                timeout: 0,
                isFolder: true,
                timedown: 3,
                // fileNumLimit: 8, //限制上传个数
                // fileSingleSizeLimit: 2048000 //限制单个上传图片的大小
            });

            // 选择文件事件
            this.uploader.on('filesQueued', (files) => {
                if (self.fileList.length > 0) {   //  若是已有文件则删除
                    self.fileList.forEach((fileInfo) => {
                        self.uploader.removeFile(fileInfo.file);
                    });
                    self.fileList = [];
                    self.folderIds = [];
                }
                if (files.length > 0) {
                    self.uploafForm.folderName = files[0].source.source.webkitRelativePath.split('/')[0];
                    self.uploafForm.folderid = 'folderid_' + new Date().getTime();
                    self.uploafForm.fileCount = files.length;
                    document.getElementById('fileUploadInpt').value = self.uploafForm.folderName;
                    files.forEach((file, index) => {
                        let filename = file.name;
                        let filenameonly=filename.split('.')[0];
                        if (this.getScenceName() == 'SPPI') {
                            if(filenameonly.indexOf("信托计划上层合同") != -1 || filenameonly.indexOf("信托计划底层合同") != -1 || filenameonly.indexOf("债权计划上层合同") != -1 || filenameonly.indexOf("债权计划底层合同") != -1){
                                file.guid = WebUploader.Base.guid();
                                self.fileList.push({
                                    file: file,
                                    filename: filename,
                                    progress: 0,
                                    isSelect: true,
                                    status: 0,  //  0 为未开始上传或上传完成  1正在上传 2暂停

                                });
                            } else {
                                this.$notify({
                                    title: '提示',
                                    message: '此种方式命名，否则提示文件名称不标准请重新上传',
                                    type: 'error',
                                    duration: 1500
                                });
                            }
                        } else {
                            file.guid = WebUploader.Base.guid();
                            self.fileList.push({
                                file: file,
                                filename: filename,
                                progress: 0,
                                isSelect: true,
                                status: 0,  //  0 为未开始上传或上传完成  1正在上传 2暂停

                            });
                        }

                    });
                }


            });

            this.uploader.on('uploadStart', function (file) {
                let localFile = self.getLocalFile(file);
                localFile.status = 1;
                self.isUpload = true; // 有文件上传则禁用识别按钮
            });

            // 文件分片开始上传之前
            this.uploader.on('uploadBeforeSend', (obj, data, headers) => {
                obj.chunked = data.chunk;
                data.guid = obj.file.guid;
            });

            // 文件上传进度
            this.uploader.on('uploadProgress', (file, percentage) => {
                let localFile = self.getLocalFile(file);
                localFile.progress = Math.floor(percentage * 100);
            });

            this.uploader.on('uploadSuccess', (file, res) => {
                let localFile = self.getLocalFile(file);
                localFile.status = 0;
            });

            // 所有文件上传完成判断是否可进行识别
            this.uploader.on('uploadFinished', (a, b) => {
                // if(self.uploader.getStats().successNum == self.fileList.length){
                self.isUpload = false;
                // }
            });
        },
        methods: {
            getLocalFile(file) {
                let files = this.fileList.filter((item, index) => {
                    return item.file.id === file.id;
                });
                if (!!files && files.length > 0) {
                    return files[0];
                } else {
                    return {};
                }
            },
            getScenceList() {
                this.$ocrhttp({
                    url: '/folder/findSceneDict/0',
                    type: 'GET',
                    success: (res) => {
                        if (res.code == 200) {
                            this.scenceList = res.data;
                        }
                    },
                    error: (err) => {

                    }
                })
            },
            getScenceName() {
                let arr = this.scenceList.filter((item, index) => {
                    if (item.sceneId == this.sceneId) {
                        if (item.ocrSceneDistList instanceof Array && item.ocrSceneDistList.length > 0) {
                            this.secondOptionList = item.ocrSceneDistList;
                            this.form.secondSceneId = this.secondOptionList[0].sceneId;
                        } else {
                            this.secondOptionList = [];
                            this.form.secondSceneId = '';
                        }
                        return true;
                    } else {
                        return false;
                    }
                });
                if (!!arr && arr.length > 0) {
                    return arr[0].sceneName;
                } else {
                    return false;
                }
            },
            upload() {
                this.uploafForm.sceneId = this.form.secondSceneId || this.form.scene;
                this.uploader.option('formData', this.uploafForm);
                if (!this.uploafForm.sceneId) {
                    this.$notify({
                        title: '提示',
                        message: '请选择场景',
                        type: 'error',
                        duration: 1500
                    });
                    return false;
                }
                if (this.fileList.length < 1) {
                    return false;
                } else {
                    this.uploader.upload();
                }
            },
            fileStatusToggle(fileInfo) {
                if (fileInfo.status == 1) {
                    this.uploader.cancelFile(fileInfo.file);
                    fileInfo.status = 2;
                } else if (fileInfo.status == 2) {
                    this.uploader.upload(fileInfo.file);
                    fileInfo.status = 1;
                }
            },
            distinguish() {
                this.$router.push({name: 'viewOCR', params: {}});
                return false;
                let self = this;
                let intervalId = null;
                this.OCRLoading = true;
                intervalId = setInterval(() => {
                    self.timedown--
                    if (self.timedown == 0) {
                        clearInterval(intervalId);
                        self.OCRLoading = false;
                    }
                }, 1000);
            },
            abort() {
                if (!!this.isUpload) {
                    this.$confirm('关闭本页面后已上传文件将删除，请确认是否删除', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then((res) => {
                        this.uploader.stop(true);
                        this.form = {
                            scene: '',
                            folderName: ''
                        };
                        this.fileList = [];
                        document.getElementById('fileUploadInpt').value = '';
                        this.$bus.emit('closeFileUploadDialog', true);
                    }).catch((err) => {

                    });
                } else {
                    this.form = {
                        scene: '',
                        folderName: ''
                    };
                    this.fileList = [];
                    document.getElementById('fileUploadInpt').value = '';
                    this.$bus.emit('closeFileUploadDialog', true);
                }

            },
        },
        computed: {
            scene() {
                return this.form.scene;
            }
        },
        watch: {
            scene(newval) {
                if (!!newval) {
                    this.sceneId = newval;
                    this.uploafForm.sceneId = newval;
                    this.getScenceName();
                }
            }
        }
    }

</script>
<style type="text/css" scoped>
    .uploadFolder {
        margin-top: -5px;
        width: 100%;
        height: 510px;
        background: #fff;
        border-bottom: 1px solid #dbdcdc;
    }

    .uploadFolder .uploadFolder-form {
        padding: 20px 20px 0px;
    }

    .selectFolder {
        position: relative;
        width: 100%;
        height: 30px;
    }

    .selectFolder .choose_all {
        margin-top: -6px;
        float: left;
        height: 30px;
        width: calc(100% - 60px);
    }

    .selectFolder .uploadBtn {
        position: absolute;
        top: -2px;
        right: 0px;
        width: 64px;
        height: 32px;
        background: #2a76cd !important;
    }

    .secondScene {
        float: right;
    }

    ul.fileListbox {
        width: 100%;
        height: 240px;
        overflow: auto;
    }

    ul .fileListLi {
        position: relative;
        padding-right: 50px;
        height: 35px;
        line-height: 35px;
    }

    ul .fileListLi .filename {
        float: left;
        width: 35%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    ul .fileListLi .progress {
        float: left;
        width: 65%;
        margin-top: 11px;
    }

    ul .fileListLi .uploadBtns {
        position: absolute;
        top: 3px;
        right: 0px;
        width: 40px;
        height: 30px;
    }

    ul .fileListLi .uploadBtns > i {
        cursor: pointer;
        font-size: 28px;
        line-height: 20px;
    }

    ul .fileListLi .uploadBtns > i.icon_success {
        color: #037C05;
    }

    ul .fileListLi .uploadBtns > i.icon_warn {
        color: #D88B03;
    }

    /*ul .fileListLi .uploadBtns .closeFile{
        color: red;
    }

    ul .fileListLi .uploadBtns .selectFile{
        color: #29F54D;
    }*/

    .uploadFolder .footer {
        position: absolute;
        left: 0px;
        bottom: 10px;
        padding: 10px 20px;
        width: 100%;
        height: 50px;
        border-top: 1px solid #dbdcdc;
    }

    .uploadFolder .footer button {
        padding: 0px;
        width: 64px;
        height: 28px;
        line-height: 28px;
    }

    .fixedbox {
        position: fixed;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
    }

    .message {
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -90px 0px 0px -200px;
        padding-top: 40px;
        width: 400px;
        height: 180px;
        line-height: 40px;
        background: #fff;
        font-size: 20px;
        text-align: center;
        border-radius: 3px;
    }

    .message b {
        margin-right: 5px;
        font-size: 24px;
        color: red;
    }

</style>
<style type="text/css">
    .el-form-item {
        margin-bottom: 15px;
    }

    .el-input--mini .el-input__inner {
        height: 30px;
        line-height: 30px;
    }

    .el-input__inner {
        -webkit-appearance: none;
        background-color: #FFF;
        background-image: none;
        border-radius: 4px;
        border: 1px solid #dbdcdc;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: inherit;
        height: 40px;
        line-height: 40px;
        outline: 0;
        padding: 0 15px;
        -webkit-transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
        transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
        width: 100%;
    }

    .el-select {
        display: inline-block;
        position: relative;
        width: 100%;
        height: 30px;
    }

    .selectFolder .choose_all > div {
        width: 100%;
        background: none;
    }

    .selectFolder .choose_all > div:hover {
        background: none;
    }

    .selectFolder .choose_all > div.webuploader-pick {
        padding: 0px;
    }

    .selectFolder .choose_all > div.webuploader-pick + div {
        width: 100%;
        height: 30px;
    }

</style>
