
var textarealength=0;
$('.textarea-listener textarea').on('input',function() {
    textarealength = $(this).val().length;
    if(textarealength>0){
        $('#showTooltips').removeAttr("disabled");
    }else if(textarealength<=0 && uploadCount <= 0){
        $('#showTooltips').attr("disabled","disabled");
    }
    $('.textarea-listener .weui-textarea-counter span').html(textarealength);
})
var $loadingToast = $('#loadingToast');
document.querySelector('#uploaderFiles').addEventListener('click', function (e) {
    var target = e.target;

    while (!target.classList.contains('weui-uploader__file') && target) {
        target = target.parentNode;
    }
    if (!target) return;

    var url = target.getAttribute('style') || '';
    var id = target.getAttribute('data-id');

    if (url) {
        url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
    }
    // console.log(url,'llllll')
    var gallery = weui.gallery(url, {
        onDelete: function() {
            weui.confirm('确定删除该图片？', function () {
                var index;
                for (var i = 0, len = uploaderFiles.length; i < len; ++i) {
                    var file = uploaderFiles[i];
                    if (file.id == id) {
                        index = i;
                        break;
                    }
                }
                if (index) uploaderFiles.splice(index, 1);
                --uploadCount;
                $('#uploader #uploadCount').html(uploadCount);
                target.remove();
                gallery.hide();
            });
        }
    });
});

var uploadCount = 0;
var uploadFileList = [];
var uploaderFiles =[];
var countA =[];
weui.uploader('#uploader', {
    url: '',
    auto: false,
    type: 'file',
    fileVal: 'fileVal',
    onBeforeQueued: function (files) {
        // `this` 是轮询到的文件, `files` 是所有文件

        if (["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0) {
            weui.alert('请上传图片');
            return false; // 阻止文件添加
        }
        if (this.size > 10 * 1024 * 1024) {
            weui.alert('请上传不超过10M的图片');
            return false;
        }
        if (files.length > 9) { // 防止一下子选择过多文件
            weui.alert('最多只能上传9张图片，请重新选择');
            return false;
        }
        if (uploadCount + 1 > 9) {
            weui.alert('最多只能上传9张图片');
            return false;
        }
        ++uploadCount;
        if (uploadCount > 0) { // 防止一下子选择过多文件
            $('#showTooltips').removeAttr("disabled");
        }else{
            $('#showTooltips').attr("disabled","disabled");
        }
        $('#uploader #uploadCount').html(uploadCount);

        // return true; // 阻止默认行为，不插入预览图的框架

        // $("#showTooltips").on("click", function () {
        //     asyncUploadImage();
        // })
    },
    onQueued: function () {
        uploaderFiles.push(this)
        var $del = $('<span class="delxxx"></span>');
        $del.click(function(e) {
            e.stopPropagation();
            var id = $(this).parent().data('id');
            var target = $(this).parent();
            weui.confirm('确定删除该图片？', function () {
                var index;
                for (var i = 0, len = uploaderFiles.length; i < len; ++i) {
                    var file = uploaderFiles[i];
                    if (file.id == id) {
                        index = i;
                        break;
                    }
                }
                // if (index)
                uploaderFiles.splice(index, 1);
                uploaderFiles.del
                --uploadCount;
                if (uploadCount > 0) { // 防止一下子选择过多文件
                    $('#showTooltips').removeAttr("disabled");
                }else if(textarealength <=0 && uploadCount<=0){
                    $('#showTooltips').attr("disabled","disabled");
                }
                $('#uploader #uploadCount').html(uploadCount);
                target.remove();
            });
        })
        $('#uploaderFiles li').html($del)
        // uploadFileList.push(this);
        // console.log(this.status);    // 文件的状态：'ready', 'progress', 'success', 'fail'
        // console.log(this.base64); // 如果是base64上传，file.base64可以获得文件的base64

        // this.upload(); // 如果是手动上传，这里可以通过调用upload来实现；也可以用它来实现重传。
        // this.stop(); // 中断上传

        // return true; // 阻止默认行为，不显示预览图的图像
    },
    onBeforeSend: function (data, headers) {
        console.log(this, data, headers);
        // $.extend(data, { test: 1 }); // 可以扩展此对象来控制上传参数
        // $.extend(headers, { Origin: 'http://127.0.0.1' }); // 可以扩展此对象来控制上传头部

        // return false; // 阻止文件上传
    },
    onProgress: function (procent) {
        console.log(this, procent);
        // return true; // 阻止默认行为，不使用默认的进度显示
    },
    onSuccess: function (ret) {
        // countA.push(ret.data)
        console.log(this, ret);
        // return true; // 阻止默认行为，不使用默认的成功态
    },
    onError: function (err) {
        console.log(this, err);
        // return true; // 阻止默认行为，不使用默认的失败态
    },

});
var dynamicId ="";


function uploadAndSave(){
    // $('#showTooltips').attr("disabled",true);
    document.getElementById('showTooltips').style.display = "block";
    $loadingToast.fadeIn(100);

    // $loadingToast.fadeOut(100);
    // setTimeout(function () {
    // },10)
    document.getElementById('showTooltips').disabled=true;


    // $('#showTooltips').css('background','#ccc');
    // $("#showTooltips").click(function() {
    // alert(1);
    // $('#showTooltips').attr("disabled",true);
    // $('#showTooltips').addClass('ss')
    var projectId = $("#projectId").val();
    var createUserid = $("#createUserid").val();

    // var timestamp = new Date().getTime().toString();
    var timestamp = (Date.parse(new Date())/1000).toString();
    // timestamp = timestamp.substring(8,timestamp.length);
    dynamicId = timestamp;

    //发送数据
    // send();
    setTimeout(function () {
        send();
    },1000)

    // var dis = document.getElementById("showTooltips").disabled;
    // alert(dis);
}

function doRequestUsingGET(url, callback) {
    xmlHttp.onreadystatechange = callback;
    // xmlHttp.open("GET", url + "&timeStamp=" + new Date().getTime(), true);
    // xmlHttp.send(null);
}
//以下是callback函数的定义
function changeNRNRState() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            if (parseInt(xmlHttp.responseText) == 1) {
                updateMsgCount("nrnr_count", "rnr_count");
            } else {
                alert("\u7559\u8a00\u72b6\u6001\u66f4\u65b0\u5931\u8d25!");
                location.href = "msg.do?m=admin_msg&state=nrnr";
            }
        }
    }
}

function send(){
    var formData = new FormData();
    var xhr= new XMLHttpRequest()
    var reader = new FileReader();
    for(var i = 0;i<uploaderFiles.length;i++){
        formData.append("file[]",uploaderFiles[i], uploaderFiles[i].name);
    }

    // xhr.open("post", "/project/adddynamicpic", true);
    // xhr.send(formData)
    // var stime1 = new Date().getTime();
    // xhr.onreadystatechange = function () {
    //     switch ( xhr.readyState ) {
    //         case 0:
    //             stime = new Date().getTime()-stime1;console.log('time0 : '+stime+' ms');
    //             console.log( "xhr请求已初始化" );
    //             break;
    //         case 1:
    //             stime = new Date().getTime()-stime1;console.log('time1 : '+stime+' ms');
    //             console.log( "xhr请求已打开" );
    //             break;
    //         case 2:
    //             stime = new Date().getTime()-stime1;console.log('time2 : '+stime+' ms');
    //             console.log( "xhr请求已发送" );
    //             break;
    //         case 3:
    //             //console.log(xhr.getAllResponseHeaders());
    //             stime = new Date().getTime()-stime1;console.log('time3 : '+stime+' ms');
    //             console.log( "xhr请求已响应");
    //             break;
    //         case 4:
    //             stime = new Date().getTime()-stime1;console.log('time4 : '+stime+' ms');
    //             if ( xhr.status == 200 ) {
    //                 console.log( "xhr请求成功："+xhr.responseText );
    //             } else {
    //                 console.log( "xhr请求失败："+xhr.readyState );
    //             }
    //             break;
    //         default :
    //             break;
    //     }
    // }

    $.ajax({
        url: "adddynamicpic",
        type: "POST",
        async: false,
        timeout : 30000, //超时时间设置，单位毫秒
        cache: false,
        processData: false,// 告诉jQuery不要去处理发送的数据
        contentType: false,// 告诉jQuery不要去设置Content-Type请求头
        data: formData,
        dataType: 'JSON',
        beforeSend:function(){
        },
        success: function(data){
            $.each(data.data, function (n, img) {
                addAttachment(img, n, data);
            });
        },
        error: function(){
            $loadingToast.fadeOut(100)
            showMessage("error", "系统异常,请稍后重试");
            return false;
        },
        complete: function(XMLHttpRequest, textStatus){

            if(textStatus == "success"){
                var projectId = $("#projectId").val();
                var createUserid = $("#createUserid").val();
                var createUsername = $("#createUsername").val();
                var projectName = $("#projectName").val();
                var dynamicContent = $('.textarea-listener textarea').val();
                $.ajax({
                    url: "savedynamic",
                    type: "POST",
                    data: {
                        projectId: projectId,
                        createUserid: createUserid,
                        createUsername: createUsername,
                        dynamicId: dynamicId,
                        dynamicContent: dynamicContent,
                        projectName: projectName
                    },
                    dataType: 'JSON',
                    // async: false,
                    success: function(data){
                        $loadingToast.fadeOut(100)
                        if(data.result=="1"){
                            showMessage("success", "提交成功", 2000, "back");
                        }
                        // window.location.href="getprojectdynamiclist?projectId="+projectId+"&projectName="+projectName;
                    },
                    error: function () {
                        $loadingToast.fadeOut(100)
                        showMessage("error", "提交失败");
                    }
                });

                // window.location.href="getprojectdynamiclist?projectId="+projectId+"&projectName="+projectName;
            }else{
                $loadingToast.fadeOut(100);
                showMessage("error", "信号异常，请稍后重试");
            }
        }
    });


}



function addAttachment(img, n, data){

    $.ajax({
        url: "savePicInfo2Attachment",
        data: {
            resourceId: img.resourceId,
            resourceType: img.resourceType,
            bizType: img.bizType,
            name: img.name,
            suffix: img.suffix,
            size: img.size,
            remotePath: img.remotePath,
            dynamicId: dynamicId
        },
        type: "post",
        async: false,
        success: function (resultData) {
            // if(uploadCount == data.data.length && resultData.result == "1"){
            //
            // }else{
            //     $loadingToast.fadeOut(100)
            // }
            // $loadingToast.fadeIn(2000);
            //
            // setTimeout(function () {
            //     $loadingToast.fadeOut(100);
            // }, 3000);
        },
        error: function () {
            addNumber =0;
            // showMessage("error", "提交失败");
            $loadingToast.fadeOut(100)
            alert("系统异常，请联系管理员");
        }
    });
}

function showMessage(type, message, timeout, url) {
    var $toast = $('#toast');
    if (type == "error") {
        $toast.find("i").removeClass().addClass("weui-icon_toast")
    } else if (type == "success") {
        $toast.find("i").removeClass().addClass("weui-icon_toast").addClass("weui-icon-success-no-circle")
    }
    $toast.find("p").text(message);
    if ($toast.css('display') != 'none') return;

    setTimeout(function () {
        $toast.fadeIn(1000);
    }, 1000);

    setTimeout(function () {
        $toast.fadeOut(100);
        if (url != undefined) {
            backToUrl()
        }
    }, timeout);
}

