$(function () {
    'use strict';
    //初始化弹窗
    $.UploadModal.init(500, 'auto');

    //判断绑定服务器
    if ((parseInt(bindServer) > 0)) {
        var $select = $('#select-server');
        if ($select.length ) {
            if ($select.is('select')) {
                $select.find("option[value='"+bindServer+"']").attr("selected", true);
            } else {
                $select.val(bindServer);
            }
        }
    }

    if (activeDrive === 'qiniu') {
        uploadQiniu();
    } else if(activeDrive === 'alioss') {
        uploadAlioss();
    } else {
        uploadLocal();
    }
    
});

var $globalProgress = $('#global-progress');

var uploadQiniu = function () {
    var options = {
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bpm)$/i,
        dataType : 'json',
        filesContainer : $('#table-files'),
        progressContainer : $globalProgress,
        url: 'http://up.qiniu.com',
        paramName : 'file',
        getFilesFromResponse : function(data) {
            var response = [];
            if (data.result.files) {
                if ($.isArray(data.result.files)) {
                    response = data.result.files;
                } else {
                    response[0] = data.result.files;
                }
                response[0]['name'] = response[0]['result']['name'];
                response[0]['size'] = response[0]['result']['size'];
            } else {
                response[0] = data.result;
            }
            return response;
        }
    };

    $.each(uploadDom, function(i, e){
        var $uploader = $(e);
        var fileType = $uploader.data('file-type') || 'image';
        var uploadType = $uploader.data('upload-type') || 'cover';

        if (fileType === 'audio') {
            options.acceptFileTypes = /(\.|\/)(mp3|m4a|mp4|ogg|wav)$/i;
        } else {
            options.acceptFileTypes = /(\.|\/)(gif|jpe?g|png|bpm)$/i;
        }
        $uploader.fileupload(options);

        var sign;
        $uploader.fileupload(options).on('fileuploadadd',function(e, data) {
            var file = data.files[0];
            var response = $.ajax({
                url: qiniuGetUrl,
                data : {
                    filename : file.name,
                    file_type : file.type,
                    upload_type : uploadType,
                    size : file.size
                },
                async: false
            }).responseJSON;

            if (response.code === 0) {
                sign = response.result;
                data.formData =  {
                    'key' : sign.key,
                    'token': sign.token,
                };
                data.url = sign.host;
                $.UploadModal.show();
                $globalProgress.hide();
                return data;
            } else {
                alert(response.error);
                return false;
            }

        }).on('fileuploadstart', function(e, data) {
            $globalProgress.show();
        }).on('fileuploadfinished', function (e, data) {
            console.log(data);
            if (data.result.key) {
                data.textStatus = 'success';
                data.filesContainer.find('.start').hide();
                data.filesContainer.find('.cancel').replaceWith('<span class="label label-success">上传成功</span>');

                var targetPath = $(this).data('target-path');
                if ((typeof targetPath !== 'undefined') && $(targetPath).size() > 0) {
                    $(targetPath).val(sign.filepath);
                }
                var call = $(this).data('call');
                if ((typeof call !== 'undefined')) {
                    window[call](sign);
                }
                setTimeout(function(){
                    $.UploadModal.close();
                }, 800);
                data.files[0].error = null;
                return data;
            } else {
                data.filesContainer.find('.start').hide();
                data.filesContainer.find('.cancel').html(data.result.error);
            }

        }).on('fileuploadfailed', function(e, data){
            console.log(data);
        });
    });
    
};

/**
 * 阿里云上传
 */
var uploadAlioss = function () {
    var options = {
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bpm)$/i,
        dataType : 'json',
        filesContainer : $('#table-files'),
        progressContainer : $globalProgress,
        url: 'http://oss.aliyuncs.com',
        paramName : 'file'
    };

    //var uploader = [];
    $.each(uploadDom, function(i, e){
        var $uploader = $(e);
        var fileType = $uploader.data('file-type') || 'image';
        var uploadType = $uploader.data('upload-type') || 'cover';

        if (fileType === 'audio') {
            options.acceptFileTypes = /(\.|\/)(mp3|m4a|mp4|ogg|wav)$/i;
        } else {
            options.acceptFileTypes = /(\.|\/)(gif|jpe?g|png|bpm)$/i;
        }
        $uploader.fileupload(options);

        var sign;
        $uploader.fileupload(options).on('fileuploadadd',function(e, data) {
            var file = data.files[0];
            var response = $.ajax({
                url: ossGetUrl,
                data : {
                    filename : file.name,
                    file_type : file.type,
                    upload_type : uploadType,
                    size : file.size
                },
                async: false
            }).responseJSON;

            if (response.code === 0) {
                sign = response.result;
                data.formData =  {
                    'key' : sign.key,
                    'policy': sign.policy,
                    'OSSAccessKeyId': sign.accessid,
                    'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                    //'callback' : sign.callback,
                    'signature': sign.signature
                };
                data.url = sign.host;
                $.UploadModal.show();
                $globalProgress.hide();
                return data;
            } else {
                alert(response.error);
                return false;
            }

        }).on('fileuploadstart', function(e, data) {
            $globalProgress.show();
        }).on('fileuploadfail', function (e, data) {
            $globalProgress.show();
            if (data.jqXHR.status === 200) {
                data.textStatus = 'success';
                data.filesContainer.find('.start').hide();
                data.filesContainer.find('.cancel').replaceWith('<span class="label label-success">上传成功</span>');

                var targetPath = $(this).data('target-path');
                if ((typeof targetPath !== 'undefined') && $(targetPath).size() > 0) {
                    $(targetPath).val(sign.filepath);
                }
                var call = $(this).data('call');
                if ((typeof call !== 'undefined')) {
                    window[call](sign);
                }
                setTimeout(function(){
                    $.UploadModal.close();
                }, 800);
                return false;
            }
        }).on('fileuploadfailed', function(e, data){
            console.log(data);
        });
    });
};

//本地上传
var uploadLocal = function () {
    var options = {
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bpm)$/i,
        dataType : 'json',
        filesContainer : $('#table-files'),
        multipart : true,
        progressContainer : $globalProgress,
        url: uploadServer
    };

    //var uploader = [];
    $.each(uploadDom, function(i, e){
        var $uploader = $(e);
        var fileType = $uploader.data('file-type') || 'image';

        if (fileType === 'audio') {
            options.acceptFileTypes = /(\.|\/)(mp3|m4a|mp4|ogg|wav)$/i;
        } else {
            options.acceptFileTypes = /(\.|\/)(gif|jpe?g|png|bpm)$/i;
        }

        var uploadType = $uploader.data('upload-type');
        var query = 'file_type=' + fileType + '&upload_type=' + uploadType;
        if (uploadServer.indexOf('?') > 0) {
            options.url = uploadServer + '&' + query;
        } else {
            options.url = uploadServer + '?' + query;
        }
        $uploader.fileupload(options).on('fileuploadadd',function(e) {
            $.UploadModal.show();
            $globalProgress.hide();
        }).on('fileuploadstart', function(e) {
            $globalProgress.show();
        }).on('fileuploadcompleted', function (e, data) {

            if (typeof (data.result.files) === 'undefined') {
                return ;
            }
            var files = data.result.files;
            file = $.isArray(files)? files[0] : files;
            if (typeof(file.error) === 'undefined') {
                var targetId = $(this).data('target-id');
                if ((typeof targetId !== 'undefined') && $(targetId).size() > 0) {
                    $(targetId).val(file.id);
                }

                var call = $(this).data('call');
                if ((typeof call !== 'undefined')) {
                    window[call](data.result);
                }

                var targetPath = $(this).data('target-path');
                if ((typeof targetPath !== 'undefined') && $(targetPath).size() > 0) {
                    $(targetPath).val(file.filepath);
                }

                data.filesContainer.find('.cancel')
                    .replaceWith('<span class="label label-success">文件上传成功</span>');
                setTimeout(function(){
                    $.UploadModal.close();
                }, 800);
            }

        }).on('fileuploadfailed', function(e, data) {
            console.log(data);
        });
    });
};