BannerJson = {}
ColoeJson = {}
pattr = []
PageType = true;
ProductId = "";
window.onload = function () {
    var uploader = new plupload.Uploader({ //创建实例的构造方法
        runtimes: 'html5,flash,silverlight,html4', //上传插件初始化选用那种方式的优先级顺序
        // browse_button: 'bannerbtn', // 上传按钮
        browse_button: $("#bannerbtn")[0], // 上传按钮
        url: "upload.php", //远程上传地址
        flash_swf_url: 'plupload/Moxie.swf', //flash文件地址
        silverlight_xap_url: 'plupload/Moxie.xap', //silverlight文件地址
        filters: {
            max_file_size: '200mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
            mime_types: [ //允许文件上传类型
                {
                    title: "files",
                    extensions: "jpg,png,gif,ico"
                }
            ]
        },
        multi_selection: true, //true:ctrl多文件上传, false 单文件上传
        init: {
            FilesAdded: function (up, files) { //文件上传前
                if ($("#ul_pics").children("li").length > 30) {
                    alert("您上传的图片太多了！");
                    uploader.destroy();
                } else {
                    var li = '';
                    plupload.each(files, function (file) { //遍历文件
                        li += "<li id='" + file['id'] + "'><div class='progress'><span class='bar'></span><span class='percent'>0%</span></div></li>";
                    });
                    $("#ul_pics").append(li);
                    uploader.start();
                }
            },
            UploadProgress: function (up, file) { //上传中，显示进度条
                var percent = file.percent;
                $("#" + file.id).find('.bar').css({
                    "width": percent + "%"
                });
                $("#" + file.id).find(".percent").text(percent + "%");
            },
            FileUploaded: function (up, file, info) { //文件上传成功的时候触发
                var data = eval("(" + info.response + ")");
                // $("#" + file.id).html("<div class='img'><img src='" + data.pic + "'/></div><input type='' value='' class='input'><span class='span'>删除</span>");
                // $("#" + file.id).html("<div class='img'><img src='" + data.pic + "'/></div><p>" + file.name + "</p><span class='span' onclick='DeleteBanner(" + file.id + ")'>删除</span>");
                $("#" + file.id).html(CreateBanner(data.pic, file.name, file.id));

                BannerJson[file.id] = data;
            },
            Error: function (up, err) { //上传出错的时候触发
                // alert(err.message);
                $.Huimodalalert('服务器错误！请联系管理员', 3000);
            }
        },
    });
    var uploader2 = new plupload.Uploader({ //创建实例的构造方法
        runtimes: 'html5,flash,silverlight,html4', //上传插件初始化选用那种方式的优先级顺序
        browse_button: 'colorbtn', // 上传按钮
        url: "upload.php", //远程上传地址
        flash_swf_url: 'plupload/Moxie.swf', //flash文件地址
        silverlight_xap_url: 'plupload/Moxie.xap', //silverlight文件地址
        filters: {
            max_file_size: '200mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
            mime_types: [ //允许文件上传类型
                {
                    title: "files",
                    extensions: "jpg,png,gif,ico"
                }
            ]
        },
        multi_selection: true, //true:ctrl多文件上传, false 单文件上传
        init: {
            FilesAdded: function (up, files) { //文件上传前
                if ($("#ul_pics2").children("li").length > 30) {
                    alert("您上传的图片太多了！");
                    uploader2.destroy();
                } else {
                    var li = '';
                    plupload.each(files, function (file) { //遍历文件
                        li += "<li id='" + file['id'] + "'><div class='progress'><span class='bar'></span><span class='percent'>0%</span></div></li>";
                    });
                    $("#ul_pics2").append(li);
                    uploader2.start();
                }
            },
            UploadProgress: function (up, file) { //上传中，显示进度条
                var percent = file.percent;
                $("#" + file.id).find('.bar').css({
                    "width": percent + "%"
                });
                $("#" + file.id).find(".percent").text(percent + "%");
            },
            FileUploaded: function (up, file, info) { //文件上传成功的时候触发
                var data = eval("(" + info.response + ")");
                // $("#" + file.id).html("<div class='img'><img src='" + data.pic + "'/></div><input type='' value='' class='input' placeholder='请输入颜色分类或其他说明'><span class='span' onclick='DeleteColor(" + file.id + ")'>删除</span>");
                $("#" + file.id).html(CreateColor(data.pic, "", file.id));
                ColoeJson[file.id] = data;
            },
            Error: function (up, err) { //上传出错的时候触发
                // alert(err.message);
                $.Huimodalalert('服务器错误！请联系管理员', 3000);
            }
        },
    });
    uploader.init();
    uploader2.init();

    //日历控件
    laydate.render({
        elem: '#CountDown', //指定元素
        type: 'datetime',
        // format: 'y/M/d',
        // format: 'd/M/y',
    });
    GetProductInfo();
}

//获取产品信息
var GetProductInfo = function () {
    var pid = GetUrlParam("pid");
    ProductId = pid;
    var parameter = pid ? urlEncode(["SelectProduct", pid]) : urlEncode(["SelectProductNumber"]);
    $.ajax({
        type: "post",
        url: "/malai/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
            if (!pid) {
                // if (data[0].number == null) {
                //     data[0].number += 1;
                // }
                // $("#ProductRemarks").val(data[0].number);
                PageType = true;
            }
            else {
                PrintProductInfo(data);
                PageType = false;
            }
        }
    });
}

//打印产品信息
var PrintProductInfo = function (data) {
    var input = $('input[type="text"]'), id, value = data[0][0];
    for (var i = 0; i < input.length; i++) {
        id = input.eq(i).attr("id");
        input.eq(i).attr("value", value[id]);
    }
    $("#ProductIntroduce").html(value.ProductIntroduce);
    // $("#ueditor_0").contents().find("body").html($("#ueditor_0").contents().find("body").html() + value.ProductInfo);
    //$("#ueditor_0").contents().find("body").html(value.ProductInfo);
    $("#ueditor_0").contents().find("body").html(unescape(value.ProductInfo));

    var banner = JSON.parse(value.ProductAttr)["7b824b9c-738b-11e8-a479-0610c52349b6"],
        color = JSON.parse(value.ProductAttr)["69d4e108-738a-11e8-a479-0610c52349b6"],
        size = JSON.parse(value.ProductAttr)['d6d6361b-acea-11e8-bbc6-0a4b7569e232'],
        classs = JSON.parse(value.ProductAttr)["cfb738c4-bff6-11e8-bbc6-0a4b7569e232"],
        comment = JSON.parse(value.ProductAttr)["d5cca263-c224-11e8-bbc6-0a4b7569e232"];
    for (var i in banner) {
        for (var j in banner[i]) {
            var id = NewGuid(),
                li = "<li id='" + id + "'></li>";
            $("#ul_pics").append(li);
            $("#" + id).html(CreateBanner(banner[i][j], "", id));
            // BannerJson[id] = banner[i][j];
        }
    }

    for (var i in color) {
        for (var j in color[i]) {
            var id = NewGuid(),
                li = "<li id='" + id + "'></li>";
            $("#ul_pics2").append(li);
            $("#" + id).html(CreateColor(color[i][j], j, id));
            // ColoeJson[id] = color[i][j];
        }
    }

    for (var i in size) {
        for (var j in size[i]) {
            AddSize(false, size[i][j]);
        }
    }

    $.each(classs, function (i, val) {
        AddClass(false, i, val);
    })


    for (var i in comment) {
        CreateComment(false, comment[i]);
    }

    $(".Submission").html("修改产品信息");
}

//创建banner、打印banner
var CreateBanner = function (src, name, id) {
    if (src.split("/malai").length > 1) {
        src = src;
    }
    else {
        src = "/malai/" + src;
    }

    var str = "<div class='img'><img src='" + src + "'/></div><p>" + name + "</p><span class='span' onclick='DeleteBanner(\"" + id + "\")'>删除</span>";
    return str;
}

//删除banner图
var DeleteBanner = function (el) {
    var flag = confirm("是否确定删除banner图？");
    if (flag) {
        var id = el.id;
        // delete BannerJson[id];
        $("#" + el).remove();
    }
}

//创建颜色分类、打印颜色分类
var CreateColor = function (src, name, id) {
    if (src.split("/malai").length > 1) {
        src = src;
    }
    else {
        src = "/malai/" + src;
    }
    name == "" ? "" : name;
    var str = "<div class='img'><img src='" + src + "'/></div><input type='' value='" + name + "' class='input' placeholder='请输入颜色分类或其他说明'><span class='span' onclick='DeleteColor(\"" + id + "\")'>删除</span>";
    return str;
}

//删除颜色分类图片
var DeleteColor = function (el) {
    var flag = confirm("是否确定删除颜色分类？");
    if (flag) {
        var id = el.id;
        delete ColoeJson[id];
        $("#" + el).remove();
    }
}

//添加尺寸
var AddSize = function (flag, size) {
    if (flag) {
        var li = '<li><input type="" value="" class="input" placeholder="请输入尺寸"><span class="span" onclick="DeleteSize()">删除</span></li>';
    }
    else {
        var li = '<li><input type="" value="' + size + '" class="input" placeholder="请输入尺寸"><span class="span" onclick="DeleteSize()">删除</span></li>';
    }
    $("#ul_pics3").append(li);
}

//删除尺寸
var DeleteSize = function () {
    var flag = confirm("是否确定删除尺寸？");
    if (flag) {
        event.target.parentNode.remove();
    }
}

//添加套餐
var AddClass = function (flag, indexof, obj) {
    var li, ul, ul_length;
    li = '<li>' +
        '<div class="number_select">' +
        '<span>销售数量选择</span>' +
        '<select>' +
        '<option>0</option>' +
        '<option>1</option>' +
        '<option>2</option>' +
        '<option>3</option>' +
        '<option>4</option>' +
        '<option>5</option>' +
        '</select>' +
        '</div>' +
        '<input type="" value="" class="input" placeholder="请输入套餐说明">' +
        '<input type="" value="" class="input" placeholder="请输入套餐价格">' +
        '<span class="span" onclick="DeleteClass()">删除</span>' +
        '</li>';

    ul = $("#ul_pics4").append($(li));
    if (flag) {
        ul_length = ul.find("li").length;
        ul.find("select").eq(ul_length - 1).val(ul_length);
        if (ul_length == 1) {
            ul.find("input").eq(1).val($("#ProductPrice").val())
        }
    }
    else {
        $.each(obj, function (i, val) {
            if (i == "type") {
                ul.find("select").eq(indexof).val(val);
            }
            else {
                ul.find("li").eq(indexof).find("input").eq(0).val(val);
                ul.find("li").eq(indexof).find("input").eq(1).val(i);
            }
        });
    }
}

//删除套餐
var DeleteClass = function () {
    var flag = confirm("是否确定删除套餐？");
    if (flag) {
        event.target.parentNode.remove();
    }
}

//添加评价
var CreateComment = function (flag, obj) {
    var id = NewGuid();
    var li = '<li>' +
        '<div class="comment_header">' +
        '<input class="comment_username" placeholder="请输入用户名" type="text"/>' +
        '<span class="comment_delete" onclick="DeleteComment()">删除</span>' +
        '</div>' +
        '<div class="comment_content">' +
        '<textarea placeholder="请输入评价"></textarea>' +
        '</div>' +
        '<div class="comment_picture_warp">' +
        '<div class="comment_picture" id="' + id + '" style="cursor: pointer">' +
        '<img src="../images/addphoto.png"  style="cursor: pointer"/>' +
        '</div>' +
        '</div>' +
        '<div class="comment_footer">' +
        '<input type="text" class="comment_footer_input" placeholder="请输入评价日期">' +
        '</div>' +
        '</li>';
    $(".ul_pics_comment").append(li);
    var el = $("#" + id)[0];
    FileUpload(el, function (r) {
        CreateCommentImg(el, r.pic, true);
        console.log(r);
    });

    //日历控件
    laydate.render({
        elem: $(el).parents().eq(1).find(".comment_footer_input").eq(0)[0], //指定元素
        type: 'datetime',
        format: 'd/M/y'
    });


    if (!flag) {
        $(el).parents().eq(1).find("input[type=text]").eq(0).val(obj['name']);
        $(el).parents().eq(1).find("textarea").val(obj['text']);
        $(el).parents().eq(1).find("input[type=text]").eq(1).val(obj['time']);
        var img = obj['imgurl'].split(",");
        img.forEach(function (val) {
            CreateCommentImg(el, val, false);
        });
    }
}

var CreateCommentImg = function (el, img, flag) {
    if (img == "" && !flag) {
        return;
    }
    img = flag ? '/malai/' + img : img;
    var div = '<div class="comment_picture" ><img src="' + img + '"><img src="../images/close.png" class="closeimg" onclick="CreateCommentImgDelete()"/></div>';
    $(el).parents().eq(0).append(div);
}

var CreateCommentImgDelete = function () {
    var flag = confirm("是否确定此图片？");
    if (flag) {
        event.target.parentNode.remove();
    }
}

//删除评价
var DeleteComment = function () {
    var flag = confirm("是否确定删除评价？");
    if (flag) {
        event.target.parentNode.parentNode.remove();
    }
}

//上传产品
var UploadNewProduct = function () {
    var pn = $("#ProductName").val(),
        pt1 = $("#ProductIntroduce").val(),
        pt2 = $("#ueditor_0").contents().find("body")[0].innerHTML,
        pr1 = $("#ProductPrice").val(),
        pr2 = $("#ProductPrimeCost").val(),
        num = $("#ProductRemarks").val(),
        dis = $("#Discount").val(),
        so = $("#Sold").val(),
        prom = $("#Promotion").val(),
        cd = $("#CountDown").val(),
        meal = $("#ul_pics4 li");

    if (pn.trim() == "") {
        $.Huimodalalert('请输入产品名称', 3000);
    }
    // else if (pt1.trim() == "") {
    //     $.Huimodalalert('产品介绍', 3000);
    //     return;
    // }
    else if (pr1.trim() == "") {
        $.Huimodalalert('请输入产品原价', 3000);
    }
    else if (pr2.trim() == "") {
        $.Huimodalalert('请输入产品售价', 3000);
    }
    else if (dis.trim() == "") {
        $.Huimodalalert('请输入产品折扣', 3000);
    }
    else if (so.trim() == "") {
        $.Huimodalalert('请输入产品已售', 3000);
    }
    else if (prom.trim() == "") {
        $.Huimodalalert('请输入产品促销信息', 3000);
    }
    else if (cd.trim() == "") {
        $.Huimodalalert('请输入产品倒计时', 3000);
    }
    // else if ($.isEmptyObject(BannerJson)) {
    //     $.Huimodalalert('请上传banner图', 3000);
    // }
    // else if ($.isEmptyObject(ColoeJson)) {
    //     $.Huimodalalert('请上传颜色分类图片', 3000);
    // }
    else if (pr2 == "<p><br></p>") {
        $.Huimodalalert('请填写详细内容', 3000);
    }
    else if (meal.length == 0) {
        $.Huimodalalert('请填写产品套餐', 3000);
    }
    else {
        //公用变量
        var flag,
            src,
            obj = {},
            colorarray = [],
            bannerarray = [],
            sizearray = [],
            classsarray = [],
            commentarray = [];


        /************************************************************************************banner整合（必填）************************************************************************************/

        var banner = $("#ul_pics li img");
        if (banner.length == 0) {
            $.Huimodalalert('请上传banner图', 3000);
            return;
        }
        else {
            for (var i = 0; i < banner.length; i++) {
                flag = i;
                src = banner.eq(i).attr("src");
                obj = {};
                obj[flag] = src;
                bannerarray.push(obj);
            }
            pattr["7b824b9c-738b-11e8-a479-0610c52349b6"] = bannerarray;
        }

        /************************************************************************************产品颜色分类整合（必填）*******************************************************************************/

        var color = $("#ul_pics2 li"),
            color_input = $("#ul_pics2 li input");
        if (color.length == 0) {
            $.Huimodalalert('请上传颜色分类图', 3000);
            return;
        }
        else {
            for (var i = 0; i < color_input.length; i++) {
                if (color_input.eq(i).val().trim() == "") {
                    $.Huimodalalert('请输入第' + (i + 1) + '个颜色或者说明', 3000);
                    return;
                }
                flag = color_input.eq(i).val();
                src = $($("#ul_pics2 li input")[i]).parent().find("img").attr("src");
                obj = {};
                obj[flag] = src;
                colorarray.push(obj);
                pattr["69d4e108-738a-11e8-a479-0610c52349b6"] = colorarray;
            }
        }

        /************************************************************************************尺寸整合（可填）***************************************************************************************/

        var size = $("#ul_pics3 .input");
        for (var i = 0; i < size.length; i++) {
            if (size.eq(i).val().trim() == "") {
                $.Huimodalalert('请输入尺寸', 3000);
                return;
            }
            flag = i;
            src = size.eq(i).val();
            obj = {};
            obj[flag] = src;
            sizearray.push(obj);
        }
        pattr["d6d6361b-acea-11e8-bbc6-0a4b7569e232"] = sizearray;

        /************************************************************************************套餐整合（必填）***************************************************************************************/

        var classs = $("#ul_pics4 li"),
            classs_select, classs_input;
        for (var i = 0; i < classs.length; i++) {
            obj = {};
            classs_select = classs.eq(i).find("select");
            if (classs_select == 0) {
                $.Huimodalalert('请选择第' + (i + 1) + "个套餐框中的销售数量", 3000);
                return;
            }
            obj["type"] = classs_select.eq(0).val();
            classs_input = classs.eq(i).find("input");
            for (var j = 0; j < classs_input.length; j++) {
                if (classs_input.eq(j).val() == "") {
                    $.Huimodalalert('请填写第' + (i + 1) + '个套餐框中的第' + (j + 1) + '个输入框说明', 3000);
                    return;
                }
            }

            flag = classs_input.eq(1).val();
            src = classs_input.eq(0).val();
            obj[flag] = src;
            classsarray.push(obj);
        }
        pattr['cfb738c4-bff6-11e8-bbc6-0a4b7569e232'] = classsarray;

        /************************************************************************************评价整合（可填）***************************************************************************************/

        var comment = $(".ul_pics_comment li");
        for (var i = 0; i < comment.length; i++) {
            if (comment.eq(i).find('input[type=text]').eq(0).val().trim() == "") {
                $.Huimodalalert('请输入第' + (i + 1) + "个评价框中的用户名", 3000);
                return;
            }
            if (comment.eq(i).find('textarea').val().trim() == "") {
                $.Huimodalalert('请输入第' + (i + 1) + "个评价框中的评价内容", 3000);
                return;
            }

            if (comment.eq(i).find('input[type=text]').eq(1).val().trim() == "") {
                $.Huimodalalert('请输入第' + (i + 1) + "个评价框中的评价时间", 3000);
                return;
            }

            obj = {};
            obj['name'] = comment.eq(i).children().eq(0).children('input').val();
            obj['text'] = comment.eq(i).children().eq(1).children().val();
            obj['time'] = comment.eq(i).find("input[type=text]").eq(1).val();
            flag = comment.eq(i).children().eq(2).children(".comment_picture");
            src = "";
            for (var j = 1; j < flag.length; j++) {
                j == 1 ? "" : src += ',';
                src += flag.eq(j).children("img").eq(0).attr("src");
            }
            obj['imgurl'] = src;
            commentarray.push(obj);
        }
        pattr["d5cca263-c224-11e8-bbc6-0a4b7569e232"] = commentarray;

        /************************************************************************************所有整合结束***************************************************************************************/

        var str = JsonToString(pattr);
        var parameter = PageType ? urlEncode(["UploadNewProduct", pn, pt1, escape(pt2), pr1, pr2, num, str, dis, so, prom, cd]) : urlEncode(["UpdateProductInfo", ProductId, pn, pt1, escape(pt2), pr1, pr2, str, dis, so, prom, cd]);
      /*  $(".Submission")[0].onclick = function () {
        }*/
        $.ajax({
            type: "post",
            url: "/malai/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (PageType) {
                    if (data.length == 1 && data != -1) {
                        alert("上传成功！");
                        window.location.href = "product.html?pid=" + data[0].ProductId;
                    }
                }
                else {
                    if (data.length == 1 && data != -1) {
                        alert("修改成功！");
                        window.location.href = "product-add.html?pid=" + data[0].ProductId;
                    }
                }
            }
        });
    }
}

//文件上传接口
var FileUpload = function (el, cb) {
    var file = new plupload.Uploader({ //创建实例的构造方法
        runtimes: 'html5,flash,silverlight,html4', //上传插件初始化选用那种方式的优先级顺序
        browse_button: el, // 上传按钮
        url: "upload.php", //远程上传地址
        flash_swf_url: 'plupload/Moxie.swf', //flash文件地址
        silverlight_xap_url: 'plupload/Moxie.xap', //silverlight文件地址
        filters: {
            max_file_size: '200mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
            mime_types: [ //允许文件上传类型
                {
                    title: "files",
                    extensions: "jpg,png,gif,ico"
                }
            ]
        },
        multi_selection: true, //true:ctrl多文件上传, false 单文件上传
        init: {
            FilesAdded: function (up, files) { //文件上传前
                file.start();
            },
            UploadProgress: function (up, file) { //上传中，显示进度条
            },
            FileUploaded: function (up, file, info) { //文件上传成功的时候触发
                var data = eval("(" + info.response + ")");
                cb && cb(data);
            },
            Error: function (up, err) { //上传出错的时候触发
                // alert(err.message);
                alert();
                $.Huimodalalert('服务器错误！请联系管理员', 3000);
            }
        },
    });
    file.init();
}

//连接字符串
var urlEncode = function (arr) {
    var i; //循环初始化
    for (i = 0; i < arr.length; i++) {
        arr[i] = encodeURIComponent(encodeURIComponent(arr[i]));
    }
    return arr.join();
}

//获取网址
var GetUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

//json转换为string
var JsonToString = function (obj) {
    var i,
        _type = false,
        _str = "",
        _type = typeof (obj); //获取类型
    //开始序列化
    if (obj == null) {
    }
    else {
        obj = obj.valueOf(); //获取值 同时类型也为对应
        if ("boolean,number".indexOf(_type) > -1) {//bool和number类型转化
            _str = obj.toString();
        }
        else if (_type == "string") {//json处理字符串时需要加上 "\""符号
            _str = "\"" + obj + "\"";
        }
        else if (typeof obj == "array") { //数组处理
            _str = "[";
            for (i = 0; i < obj.length; i++) {
                _str += JsonToString(obj[i]) + ((i < obj.length - 1) ? "," : "")
            }
            ;_str += "]";
            return _str
        }
        else {//object处理
            _str = "{";
            for (i in obj) {
                if (obj.hasOwnProperty(i)) {
                    if (_str.length > 1) {
                        _str += ","
                    }
                    ;_str += "\"" + i + "\":" + JsonToString(obj[i]);
                }
            }
            _str += "}";
        }
        return _str;
    }
}

//生成GUID
var NewGuid = function () {
    var _UN, i, _UGID = "";
    for (i = 0; i < 32; i++) {
        _UGID += Math.floor(Math.random() * 16).toString(16); //随机0  - 16 的数字 转变为16进制的字符串
        _UN = Math.floor((i - 7) / 4);                        //计算 (i-7)除4
        if (_UN > -1 && _UN < 4 && (i == (7 + 4 * _UN))) {    //会使guid中间加 "-"   形式为xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
            _UGID += "-";
        }
    }
    return _UGID;
}
