<template>
    <div class="uploadFolder">
        <div class="uploadFolder-form">
            <el-form ref="uploadForm" :model="uploadFormData">
                <el-form-item >
                    <el-input :style="{width: !!isShowSecond?'45%': '100%'}" disabled size="mini" v-model="currentSceneName"></el-input>
                    <el-select v-if="!!isShowSecond" v-model="uploadFormData.secondSceneId" placeholder="请选择场景" size="mini"  style="width: 45%" >
                        <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="fileList">
                        <li class="folderName">{{uploadFormData.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="26" :percentage="fileInfo.progress"></el-progress>
                            </div>
                            <div class="uploadBtns">
                               <i :class="[fileInfo.status == 1? 'el-icon-video-play icon_success' : 'el-icon-video-pause icon_warn']" @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">OCR识别进行中，请稍候...</div>
        </div>
    </div>
</template>
<script type="text/javascript">
    export default{
        name: 'UploadFile',
        props: ['sceneId'],
        data(){
            return {
                uploadFormData: {
                    // scene: '',
                    // folderName: '',
                },
                scenceList: [],
                fileList: [],
                uploader: '',
                isUpload: true, //  是否未上传或正在上传完毕
                currentSceneName: '', // 当前场景的名称
                isShowSecond: false,
                secondOptionList: [],
                folderIds: [],
                OCRLoading: false,
                guid: '',
            }
        },
        mounted(){
            this.getScenceList();
            this.uploadFormData.scene = this.sceneId;
            let self = this;
            this.uploader = WebUploader.create({
                auto: false, // 选完文件后，是否自动上传
                swf: './static/WebUploader/Uploader.swf', // swf文件路径
                server: '/demo/upload', // 文件接收服务端
                formData: self.uploadFormData,
                pick: '.choose_all', // 选择文件的按钮。可选
                chunked: false,
                chunkSize: 1024*500,
                threads: 1,
                timeout: 0,
                isFolder: false,
                // 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){
                    files.forEach((file,index)=>{
                        let filename = file.name;
                        file.guid = WebUploader.Base.guid();
                        self.fileList.push({
                            file: file,
                            filename: filename,
                            progress: 0,
                            isSelect: true,
                            status: 0,
                        });
                    });
                }
            });

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

            // 文件上传进度
            this.uploader.on('uploadProgress',(file,percentage) => {
                self.fileList.forEach( (item,index) => {
                    if(item.file.id === file.id){
                        item.progress = Math.floor(percentage * 100);
                    }
                });
            });

            this.uploader.on('uploadSuccess',(file,res) => {
                console.log(res._raw);
                self.$ocrhttp({
                    url: '/demo/show?fileName=/usr/project/server/iimg/IMG_4463.JPG',
                    type: 'GET',
                    time: 1000 * 60 * 5,
                    // data:{
                    //     // fileName: res._raw

                    // },
                    success: (res) => {
                        if(res.code == 200){
                            // this.scenceList = res.data;
                            console.log(res);
                        }
                    },
                    error: (err) => {

                    }
                })
            });

            // 所有文件上传完成判断是否可进行识别
            this.uploader.on('uploadFinished',(a,b) => {
                if(self.uploader.getStats().successNum == self.fileList.length){
                    self.isUpload = false;
                }
            });
        },
        methods: {
            getScenceList(){
                this.$ocrhttp({
                    url: '/folder/findSceneDict/0',
                    type: 'GET',
                    success: (res) => {
                        if(res.code == 200){
                            this.scenceList = res.data;
                            this.$nextTick( () => {
                                this.currentSceneName = this.getScenceName();
                            });
                        }
                    },
                    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.isShowSecond = true;
                            this.secondOptionList = item.ocrSceneDistList;
                            this.uploadFormData.secondSceneId = this.secondOptionList[0].sceneId;
                        }else{
                            this.isShowSecond = false;
                             this.secondOptionList = [];
                            this.uploadFormData.secondSceneId = '';
                        }
                        return true;
                    }else{
                        return false;
                    }
                });
                if(!!arr && arr.length > 0){
                    return arr[0].sceneName;
                }else{
                    return '';
                }
            },
            upload(){
               this.uploader.upload();
            },
            fileStatusToggle(fileInfo){
                if(fileInfo.status == 1){
                    this.uploader.stop(fileInfo.file,true);
                    fileInfo.status = 0;
                }else if(fileInfo.status == 0){
                    this.uploader.upload(fileInfo.file,true);
                    fileInfo.status = 1;
                }
            },
            distinguish(){
                this.OCRLoading = true;
                $.ajax({
                    url: '/ocr/recognize',
                    type: 'POST',
                    headers:{
                        'Content-Type': 'application/json;charset=UTF-8'
                    },
                    data: JSON.stringify({
                        folderIds: this.folderIds,
                        scenceId: this.uploadFormData.scene
                    }),
                    success: (res) => {
                        this.OCRLoading = false;
                        if(res.code == 200){
                            this.$message({
                                type: 'info',
                                message: `OCR识别成功`
                            });
                            this.$nextTick( () => {
                                this.$router.push({path: '/viewOCR'});
                            });
                        }else{
                            this.$message({
                                type: 'info',
                                message: `OCR识别失败`
                            });
                            this.$nextTick( () => {
                                this.$router.push({path: '/viewOCR'});
                            });
                        }
                    },
                    error: (err) => {
                        this.OCRLoading = false;
                        if(err){
                            this.$message({
                                type: 'info',
                                message: `OCR识别失败`
                            });
                            this.$nextTick( () => {
                                this.$router.push({path: '/viewOCR'});
                            });
                        }
                    }
                });
            },
            abort(){
                if(!!this.isUpload){
                    this.$confirm('关闭本页面后已上传文件将删除，请确认是否删除', '提示',{
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then( (res)=> {
                        this.uploader.stop(true);
                        this.uploadFormData = {
                            scene: '',
                            folderName: ''
                        };
                        this.fileList = [];
                        document.getElementById('fileUploadInpt').value = '';
                        this.$bus.emit('closeFileUploadDialog',true);
                    }).catch( (err) => {

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

            },
        },
    }

</script>
<style type="text/css" scoped>
    .uploadFolder{
        margin-top: -5px;
        width: 100%;
        height: 100%;
        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;
    }

    ul .fileListLi{
        position: relative;
        padding-right: 70px;
        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: 5px;
    }

    ul .fileListLi .uploadBtns{
        position: absolute;
        top: 3px;
        right: 0px;
        width: 60px;
        height: 30px;
    }
    ul .fileListLi .uploadBtns button{
        position: relative;
        display: inline-block;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 20px;
        background: none;
        border: 1px solid #BCA234;
        outline: none;
    }
    ul .fileListLi .uploadBtns button.play{
        border: 1px solid #277C5F;
    }
    ul .fileListLi .uploadBtns button.play i{
        position: absolute;
        top: 0px;
        left: -1px;
    }
    ul .fileListLi .uploadBtns > i{
        font-size: 20px;
        line-height: 20px;
    }
    ul .fileListLi .uploadBtns .closeFile{
        color: red;
    }

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


    .uploadFolder .footer{
        margin-top: -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-top: -90px;
        margin-left: -200px;
        width: 400px;
        height:180px;
        text-align: center;
        line-height: 180px;
        background: #fff;
        font-size: 20px;
        border-radius: 3px;
    }
</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;
    }

    .uploadBtns button.reset{
        vertical-align: 2px;
        padding: 3px 10px;
    }

</style>
