/*
 * 版 本 PIT-ADMS V7.0.3 敏捷开发框架
 * Copyright (c) 2013-2018 Hexagon PPM
 * 创建人：研发部
 * 日 期：2017.03.22
 * 描 述：附件上传管理	
 */
var keyVaule = request('keyVaule');
var extensions = request('extensions');
var filePath = request('filePath');
var multiple = request("multiple");
var format = request("format");
var upload = 0;
var templateFile = request("templateFile");

var bootstrap = function ($, learun) {
    "use strict";
    if (format != undefined && format != ".*" && format != "") {
        var $item = $('.lr-form-layout-header');
        if (!!templateFile) {
            $item.append('<div style="width: 350px;top: -30px;right: -100px;position: relative;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;word-break: break-all;"title=' + format + '>支持格式:"' + format + '" <font color="red">&emsp;&emsp;&emsp;模板文件</font>:<a  style="color:blue" target="_blank" href="/Template/' + templateFile+'">' + templateFile+'</a></div>');

        } else {
            $item.append('<div style="width: 350px;top: -30px;right: -100px;position: relative;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;word-break: break-all;"title=' + format + '>支持格式:"' + format + '"</div>');
        }
    }
    $.lrSetForm(top.$.rootUrl + '/LR_SystemModule/Annexes/GetAnnexesFileList?folderId=' + keyVaule, function (data) {
        for (var i = 0, l = data.length; i < l; i++) {
            $('#lr_form_file_queue .lr-form-file-queue-bg').hide();
            var item = data[i];
            fileInfo[item.F_Id] = {
                fileGuid: item.F_Id,
                chunks: 1
            }
            var $item = $('<div class="lr-form-file-queue-item" id="lr_filequeue_' + item.F_Id + '" ></div>');
            $item.append('<div class="lr-file-image"><img id="image" src="' + top.$.rootUrl + '/Content/images/filetype/' + item.F_FileType + '.png" alt="" onerror="javascript:this.src=\'/Content/images/filetype/Scheme.png\'" ></div>');

            $item.append('<span class="lr-file-name">' + item.F_FileName + '(' + learun.countFileSize(item.F_FileSize) + ')</span>');
            //$item.append('<div class="lr-msg"><i class="fa fa-check-circle"></i></div>');
            if (ConstantZSJT.PREVIEWPICTURE.indexOf(item.F_FileType) > -1) {
                $item.append('<div class="lr-tool-bar" id="' + item.F_Id + '"><i class="fa fa-cloud-download" title="下载"  data-value="' + item.F_Id + '" ></i><i class="fa fa-times-circle" title="删除"  data-value="' + item.F_Id + '" ></i></div>')
            } else {
                if (item.F_FileType != 'xlsx' && item.F_FileType != 'xls' && item.F_FileType != 'docx' && item.F_FileType != 'doc' && item.F_FileType != 'ppt' && item.F_FileType != 'bmp' && item.F_FileType != 'txt' && item.F_FileType != 'csv' && item.F_FileType != 'pdf' && item.F_FileType != 'pptx' && item.F_FileType != 'ppt') {
                    $item.append('<div class="lr-tool-bar"><i class="fa fa-cloud-download" title="下载"  data-value="' + item.F_Id + '" ></i><i class="fa fa-times-circle" title="删除"  data-value="' + item.F_Id + '" ></i></div>');
                } else {
                    $item.append('<div class="lr-tool-bar"><i class="fa fa-cloud-download" title="下载"  data-value="' + item.F_Id + '" ></i><i class="fa fa-times-circle" title="删除"  data-value="' + item.F_Id + '" ></i></div>');
                }
            }
            $item.find('.lr-tool-bar .fa-eye').on('click', function () {
                var fileId = $(this).attr('data-value');
                var fileType = $(this).attr('F_FileType');
                if (ConstantZSJT.PREVIEWPICTURE.indexOf(fileType) <= -1) {
                     openViewForm(fileId, fileType);
                }
            });

            $item.find('.lr-tool-bar img').on('click', function () {
                var fileId = $(this).attr('data-value');
                var fileType = $(this).attr('F_FileType');
                if (ConstantZSJT.PREVIEWPICTURE.indexOf(fileType) > -1) {
                    ImagePreview.init({ id: fileId, url: 'data-original' });
                }
            });

           
            $item.find('.lr-tool-bar .fa-times-circle').on('click', function () {
                var fileId = $(this).attr('data-value');
                DeleteFile(fileId);
            });

            $item.find('.lr-tool-bar .fa-cloud-download').on('click', function () {
                var fileId = $(this).attr('data-value');
                DownFile(fileId);
            });

            $('#lr_form_file_queue_list').append($item);
            if (ConstantZSJT.PREVIEWPICTURE.indexOf(item.F_FileType) > -1) {
                ImagePreview.init({ id: item.F_Id, url: 'data-original' });
            }
        }
    });
    var openViewForm = function (fileId, fileType) {
        switch (fileType) {
            //case 'jpg':
            //case 'gif':
            //case 'png':
            //case 'jpeg':
            //learun.layerForm({
            //    id: 'PictureView',
            //    title: '图片预览',
            //    url: top.$.rootUrl + '/LR_SystemModule/Annexes/PictureView?fileId=' + fileId,
            //    width: 1080,
            //    height: 850,
            //    maxmin: true,
            //    btn: null
            //})
            // break
            case 'xlsx':
            case 'xls':
            case 'docx':
            case 'doc':
            case 'ppt':
            case 'bmp':
            case 'txt':
            case 'csv':
            case 'pdf':
                learun.layerForm({
                    id: 'PreviewForm',
                    title: '文件预览',
                    url: top.$.rootUrl + '/LR_SystemModule/Annexes/PreviewFile?fileId=' + fileId,
                    width: 1080,
                    height: 850,
                    maxmin: true,
                    btn: null
                })
                break
            case 'pptx':
                learun.layerForm({
                    id: 'PreviewForm',
                    title: '文件预览',
                    url: top.$.rootUrl + '/LR_SystemModule/Annexes/PreviewFile?fileId=' + fileId,
                    width: 1080,
                    height: 850,
                    maxmin: true,
                    btn: null
                })
                break
            case 'ppt':
                learun.layerForm({
                    id: 'PreviewForm',
                    title: '文件预览',
                    url: top.$.rootUrl + '/LR_SystemModule/Annexes/PreviewFile?fileId=' + fileId,
                    width: 1080,
                    height: 850,
                    maxmin: true,
                    btn: null
                })
                break
            default:
                learun.download({ url: top.$.rootUrl + '/LR_SystemModule/Annexes/DownAnnexesFile', param: { fileId: fileId, __RequestVerificationToken: $.lrToken }, method: 'POST' })
                break
        }

    }
    document.getElementById('lr_add_file_btn').addEventListener('click', function (event) {
        if (!JSON.parse(multiple)) {

            if (window.countWebuploaderElement <= 0) {
                var len = $(".lr-form-file-queue-item").length
                if (len > 0) {
                    learun.alert.error('只能上传一个附件，请先删除已有的附件');
                    event.preventDefault()
                }
            }
            window.countWebuploaderElement++;
        }
    }, false)

    $("#lr_cancel_file_btn").click(function () {
        learun.layerClose(window.name);
    })

    var fileInfo = {};

    // 触发合并文件碎片
    var mergeFileChunks = function (file) {
        var param = {};

        param['__RequestVerificationToken'] = $.lrToken;
        param['folderId'] = keyVaule;
        param['fileGuid'] = fileInfo[file.id].fileGuid;
        param['fileName'] = fileInfo[file.id].name;
        param['chunks'] = fileInfo[file.id].chunks;
        param['filePath'] = filePath;
        learun.httpAsyncPost(top.$.rootUrl + "/LR_SystemModule/Annexes/MergeAnnexesFile", param, function (res) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.find('.lr-uploader-progress').remove();
            if (res.code == learun.httpCode.success) {              
                learun.loading(false);
                // 文件保存成功后
                //$fileItem.append('<div class="lr-msg"><i class="fa fa-check-circle"></i></div>');
                $fileItem.append('<div class="lr-tool-bar"><i class="fa fa-times-circle" title="删除"  data-value="' + file.id + '" ></i></div>');
                $fileItem.find('.lr-tool-bar .fa-times-circle').on('click', function () {
                    var fileId = $(this).attr('data-value');
                    DeleteFile(fileId);
                });
            }
            else {
                learun.loading(false);
                //$fileItem.append('<div class="lr-msg"><i class="fa fa-exclamation-circle"></i></div>');
            }
        });
    }
    // 触发清楚文件碎片
    var reomveFileChunks = function (file) {
        var param = {};
        param['__RequestVerificationToken'] = $.lrToken;
        param['fileGuid'] = fileInfo[file.id].fileGuid;
        param['chunks'] = fileInfo[file.id].chunks;
        param['filePath'] = filePath;
        learun.httpAsyncPost(top.$.rootUrl + "/LR_SystemModule/Annexes/MergeAnnexesFile", param, function (res) { learun.loading(false); });
        var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
        $fileItem.find('.lr-uploader-progress').remove();
        $fileItem.append('<div class="lr-msg"><i class="fa fa-exclamation-circle"></i></div>');
    }
    // 删除文件
    var DeleteFile = function (fileId) {
        learun.layerConfirm('是否确认删除该项！', function (res) {
            if (res) {
                var param = {};
                param['__RequestVerificationToken'] = $.lrToken;
                param['fileId'] = fileInfo[fileId].fileGuid;
                learun.httpAsyncPost(top.$.rootUrl + "/LR_SystemModule/Annexes/DeleteAnnexesFile", param, function (res) { });
                var file = page.uploader.getFile(fileId);
                if (!!file) {
                    page.uploader.removeFile(file);
                }
                delete fileInfo[fileId];
                var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + fileId);
                $fileItem.remove();
                if ($('#lr_form_file_queue_list>div').length == 0) {
                    $('#lr_form_file_queue .lr-form-file-queue-bg').show();
                }
                console.log(fileInfo) 
            } else {
                return;
            }
        });
        
    }
    // 下载文件
    var DownFile = function (fileId) {
        learun.download({ url: top.$.rootUrl + '/LR_SystemModule/Annexes/DownAnnexesFile', param: { fileId: fileId, __RequestVerificationToken: $.lrToken }, method: 'POST' });
    }

    var page = {
        uploader: null,
        init: function () {
            if (!WebUploader.Uploader.support()) {
                alert('Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
                throw new Error('WebUploader does not support the browser you are using.');
            }

            if (!format) {
                format = "gif,jpeg,jpg,png,psd,rar,zip,pdf,doc,docx,ppt,pptx,txt,xls,xlsx"
            }

            if (!JSON.parse(multiple)) {
                var fileNumLimit = 1;
            } else {
                var fileNumLimit = 10;
            }

            page.uploader = WebUploader.create({
                auto: true,
                swf: top.$.rootUrl + '/Content/webuploader/Uploader.swf',
                // 文件接收服务端。
                server: top.$.rootUrl + "/LR_SystemModule/Annexes/UploadAnnexesFileChunk",
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: {
                    id: '#lr_add_file_btn',
                    multiple: JSON.parse(multiple)
                },
                dnd: '#lr_form_file_queue',
                paste: 'document.body',
                disableGlobalDnd: true,
                //accept: {
                //    extensions: extensions || "gif,jpeg,jpg,png,psd,rar,zip,pdf,doc,docx,ppt,pptx,txt,xls,xlsx"
                //},
                accept: {
                    extensions: format
                },
                multiple: JSON.parse(multiple),
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false,
                fileNumLimit: fileNumLimit,
                // 文件分片上传
                chunked: true,
                chunkRetry: 3,
                prepareNextFile: true,
                chunkSize: '1048576',
                //单个文件大小限制
                fileSingleSizeLimit: 524288000,
                // 上传参数
                formData: {
                    __RequestVerificationToken: $.lrToken
                }
            });
            page.uploader.on('fileQueued', page.fileQueued);
            page.uploader.on('uploadStart', page.uploadStart);
            page.uploader.on('uploadBeforeSend', page.uploadBeforeSend);
            page.uploader.on('uploadProgress', page.uploadProgress);
            page.uploader.on('uploadSuccess', page.uploadSuccess);
            page.uploader.on('uploadError', page.uploadError);
            page.uploader.on('uploadComplete', page.uploadComplete);
            page.uploader.on('error', page.error, page.fileQueued);

            $('#lr_form_file_queue').lrscroll();

        },
        fileQueued: function (file) {// 文件加载到队列
            if (!JSON.parse(multiple)) {
                var len = $(".lr-form-file-queue-item").length
                if (len > 0) {
                    learun.alert.error('只能上传一个附件，请先删除已有的附件');
                    event.preventDefault()
                    return false;
                }
            }
            fileInfo[file.id] = { name: file.name };
            $('#lr_form_file_queue .lr-form-file-queue-bg').hide();
            // 添加一条文件记录
            var $item = $('<div class="lr-form-file-queue-item" id="lr_filequeue_' + file.id + '" ></div>');
            $item.append('<div class="lr-file-image"><img src="' + top.$.rootUrl + '/Content/images/filetype/' + file.ext + '.png"  alt="" onerror="javascript:this.src=\'/Content/images/filetype/Scheme.png\'"></div>');
            $item.append('<span class="lr-file-name">' + file.name + '(' + learun.countFileSize(file.size) + ')</span>');
            $('#lr_form_file_queue_list').append($item);

        },
        uploadStart: function (file) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.append('<div class="lr-uploader-progress"><div class="lr-uploader-progress-bar" style="width:0%;"></div></div>');
        },
        uploadBeforeSend: function (object, data, headers) {
            data.chunk = data.chunk || 0;
            data.chunks = data.chunks || 1;
            fileInfo[data.id].fileGuid = fileInfo[data.id].fileGuid || WebUploader.Base.guid();
            data.fileGuid = fileInfo[data.id].fileGuid;
            fileInfo[data.id].chunks = data.chunks;
        },
        uploadProgress: function (file, percentage) {
            // learun.loading(true, "文件上传中...");
            upload = 1;
            $(".layui-layer-btn0").css('background-color', '#87CEFA')
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.find('.lr-uploader-progress-bar').css('width', (percentage * 100 + '%'));
        },
        uploadSuccess: function (file, res) {
            upload = 0;
            $(".layui-layer-btn .layui-layer-btn0").css('background-color', '#2e8ded')
            if (res.code == 200) {// 上传成功
                mergeFileChunks(file);

            }
            else {// 上传失败
                console.log(res);
                reomveFileChunks(file);
            }
        },
        uploadError: function (file, code) {
            console.log("上传失败");
            reomveFileChunks(file);
        },
        uploadComplete: function (file) {
        },
        error: function (type, file) {
            if (file.size == 0) {
                learun.alert.error('不允许上传空文件');
                return;
            }
            switch (type) {
                case 'Q_TYPE_DENIED':
                    learun.alert.error('当前文件类型不允许上传');
                    break;
                case 'Q_EXCEED_NUM_LIMIT':
                    learun.alert.error('只能上传一个附件，请先删除已有的附件');
                    break;
                case 'F_EXCEED_SIZE':
                    learun.alert.error('只能上传最大为500M的附件');
            };
        }
    };
    page.init();
}
