// 19.06.03 之前的版本，注册机构时需要填写很多信息
$(function() {
    $("#avatar_preview_panel").hide();

    var ue = UE.getEditor('editor');

    // 编辑器加载完成后清除其中内容，因为像迅雷插件可能会在编辑器加载的时候插入一段文本，导致用户未输入内容却检测内容不为空
    ue.addListener("ready", function() {
        ue.setContent("");
    });

    uptoken = getQNToken();
    newUploader("avatar_file", uptoken, function(file) {
        console.log(file.name);
        $("#avatar_preview_panel").show();
        $("#avatar_upload").hide();
    }, function(progress) {

    }, function(err) {
        alert("头像上传失败: ", err);
        console.log("上传失败", err);
    }, function(url) {
        $("#avatar_preview_img").attr("src", url);
    });

    $("#avatar_upload").click(function() {
        $("#avatar_file").click();
    });
    $("#avatar_preview_panel").click(function() {
        $("#avatar_file").click();
    });

    function getQNToken() {
        var token = ""
        $.ajax({
            url: "/application/qntoken",
            type: "GET",
            async: false,
            dataType: "json",
            success: function(json) {
                if (json.state == 1) {
                    token = json.data.token;
                } else {
                    console.log("获取token失败", json.msg);
                }
            },
            error: function() {
                console.log("连接失败，请检查网络");
            }
        });
        console.log("token：", token);
        return token;
    }

    function newUploader(bindID, token, addImageHandler, progressHandler, errorHandler, finishUploadHandler) {
        return Qiniu.uploader({
            runtimes: "html5,flash,html4",
            browse_button: bindID,
            uptoken: token,
            domain: "https://images.shengws.com/",
            max_file_size: "300kb",
            flash_swf_url: "/static/js/qiniu/Moxie.swf",
            dragdrop: false,
            auto_start: true,
            unique_names: false,
            save_key: false,
            max_retries: 3,
            multi_selection: false,
            filters: {
                mime_types: [{
                    title: "Image files",
                    extensions: "jpg,jpeg,png"
                }]
            },

            init: {
                "FilesAdded": function(up, files) {
                    console.log("文件添加进队列后,处理相关的事情");
                    plupload.each(files, function(file) {
                        // var nativeFile = file.getNative();
                        // var img = new Image();
                        // img.src = URL.createObjectURL(nativeFile)
                        // img.onload = function() {
                        //     var w = img.naturalWidth;
                        //     var h = img.naturalHeight;
                        //     if (w > 108 || h > 108) {
                        //         alert("机构头像尺寸太大，请选择108*108以内的图片");
                        //         up.removeFile(file);
                        //     } else {
                                addImageHandler(file);
                        //     }
                        // }
                    });
                },
                "BeforeUpload": function(up, file) {
                    console.log("上传之前");
                },
                "UploadProgress": function(up, file) {
                    console.log("上传进度：", file.percent + "%")
                    progressHandler(file.percent);
                },
                "FileUploaded": function(up, file, info) {
                    // info 为 json，格式是后台获取 token 时设置的 ReturnBody
                    var domain = up.getOption("domain");
                    var infoObj = JSON.parse(info);
                    var url = domain + infoObj.url;
                    // console.log("图片路径：", url);
                    finishUploadHandler(url);
                },
                "Error": function(up, err, errTip) {
                    console.log("上传出错：", err)
                    errorHandler(err);
                },
                "UploadComplete": function() {
                    console.log("队列文件处理完毕后,处理相关的事情");
                },
                "Key": function(up, file) {
                    console.log("自定义上传文件名");
                    var rand = Math.floor(Math.random() * 1000000000)
                    var date = new Date()
                    var ext = Qiniu.getFileExtension(file.name);
                    var key = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + "org_" + rand + "." + ext;
                    console.log(key);
                    return key;
                }
            }
        });
    }

    $("#province_select").change(function() {
        
        $("#city_select option").remove();
        $("#district_select option").remove();
        $("#city_select").append("<option value='0'>市</option>");
        $("#district_select").append("<option value='0'>区/县</option>");
        var province = $("#province_select option:selected").val();
        $.ajax({
            url: "/city",
            type: "GET",
            data: {
                province_id: province,
            },
            async: false,
            dataType: "json",
            success: function(json) {
                if (json.state == 1) {
                    var cities = json.data.list
                    var optionStr = ""
                    for (let index = 0; index < cities.length; index++) {
                        const city = cities[index];
                        optionStr = optionStr + "<option value = " + city.id + ">" + city.name + "</option>"
                    }
                    $("#city_select").append(optionStr);

                } else {
                    console.log("获取城市失败", json.msg);
                }
            },
            error: function() {
                console.log("连接失败，请检查网络");
            }
        });
    });

    $("#city_select").change(function() {
        
        $("#district_select option").remove();
        $("#district_select").append("<option value='0'>区/县</option>");
        var city = $("#city_select option:selected").val();
        $.ajax({
            url: "/district",
            type: "GET",
            data: {
                city_id: city,
            },
            async: false,
            dataType: "json",
            success: function(json) {
                if (json.state == 1) {
                    var districts = json.data.list
                    var optionStr = ""
                    for (let index = 0; index < districts.length; index++) {
                        const district = districts[index];
                        optionStr = optionStr + "<option value = " + district.id + ">" + district.name + "</option>"
                    }
                    $("#district_select").append(optionStr);

                } else {
                    console.log("获取区县失败", json.msg);
                }
            },
            error: function() {
                console.log("连接失败，请检查网络");
            }
        });
    });

    $("#cat_p_select").change(function() {
        $("#cat_c_select option").remove();
        $("#cat_c_select").append("<option value='0'>详细类型</option>");
        $("#cat_c_select").parent().hide();
        $("#org_category").val("0");
        var p_cat = $("#cat_p_select option:selected").val();
        $.ajax({
            url: "/get_org_cat",
            type: "GET",
            data: {
                pid: p_cat,
            },
            async: false,
            dataType: "json",
            success: function(json) {
                if (json.state == 1) {
                    var cats = json.data.list
                    if (cats.length == 0) {
                        $("#cat_c_select").parent().hide();
                        $("#org_category").val(p_cat);
                    } else {
                        var optionStr = ""
                        for (let index = 0; index < cats.length; index++) {
                            const cat = cats[index];
                            optionStr = optionStr + "<option value = " + cat.id + ">" + cat.short_name + "</option>"
                        }
                        $("#cat_c_select").append(optionStr);
                        $("#cat_c_select").parent().show();
                    }

                } else {
                    layer.msg("获取详细类型失败: " + json.msg);
                }
            },
            error: function() {
                layer.msg("连接失败，请检查网络");
            }
        });
    });

    $("#cat_c_select").change(function() {
        $("#org_category").val($("#cat_c_select option:selected").val());
    });

    $("#submit").on("click", function() {
        var checkErr = checkInfoFull(ue);
        if (checkErr.length > 0) {
            layer.msg(checkErr);
            return;
        }

        var ills = new Array();
        $("input[name='ill_checkbox']:checkbox:checked").each(function(){ 
            ills.push($(this).val());
        });
        var illstr = ills.join(",");

        var picsStr = $("#org_pics").val();
        if (picsStr.length > 2) {
            picsStr = picsStr.substr(2, picsStr.length - 2);
        }

        var postData = {
            name: $("#org_name").val(),
            short_name: $("#org_short_name").val(),
            intro: ue.getContent(),
            logo: $("#avatar_preview_img")[0].src,
            province: $("#province_select option:selected").val(),
            city: $("#city_select option:selected").val(),
            district: $("#district_select option:selected").val(),
            address: $("#address").val(),
            ill: illstr,
            category: $("#org_category").val(),
            org_phone: $("#org_phone").val(),
            business_week: $("#org_business_week").val(),
            business_time: $("#org_business_time").val(),
            business_state: $("input[name='org_business_state']:checked").val(),
            org_pics: picsStr,
        }
        postRequest("/org/create/submit", postData, doSuccess, doFail);

        function doSuccess(res) {
            if (res.state == 0) {
                serverErrorMsg(res);
                return;
            }
            layer.msg("创建成功");
            window.location.href = "/org/app/create"; //跳转网址
        }
    });

    $("input[name='week_checkbox']").change(function () {
        var business_week = [];
        $("input[name='week_checkbox']:checked").each(function () {
            var wid = $(this).attr('data-id');
            var wname = $(this).attr('data-name');
            business_week.push({ "id": wid, "name": wname });
        });
  
        if (business_week.length == 0) {
            $("#org_business_week").val('');
        } else if (business_week.length == 1) {
            $("#org_business_week").val(business_week[0]["name"]);
        } else {
            var blen = business_week.length;
            var lastindex = blen - 1;
            var btrue = true;
            for (let index = 0; index < lastindex; index++) {
                var sitem = parseInt(business_week[index]['id']);
                var eitem = parseInt(business_week[index + 1]['id']);
                sitem = sitem + 1;
                if (sitem != eitem) {
                    btrue = false;
                    break;
                }
            }
  
            if (btrue) {
                var week_show = business_week[0]["name"] + ' — ' + business_week[lastindex]["name"];
                $("#org_business_week").val(week_show);
            } else {
                var week_show = '';
                $.each(business_week, function (i, item) {
                    week_show += item["name"];
                    if (i != lastindex) {
                        week_show += '、';
                    }
                });
                $("#org_business_week").val(week_show);
            }
        }
    });
  
    $('input[name=time_checkbox_s], input[name=time_checkbox_x]').change(function () {
        if ($("input[name='time_checkbox_s']:checked").length == 0 || $("input[name='time_checkbox_x']:checked").length == 0) {
            return;
        }
        var thetime = $("input[name='time_checkbox_s']:checked").val();
        var mdatetime = $("input[name='time_checkbox_x']:checked").val();
        var timeshow = '上午' + thetime + '—' + '下午' + mdatetime;
        $("#org_business_time").val(timeshow);
    });

    Qiniu.uploader({
        runtimes: "html5,flash,html4",
        browse_button: "org_pic_uploader",
        uptoken: uptoken,
        domain: "https://images.shengws.com/",
        max_file_size: "4mb",
        flash_swf_url: "/static/js/qiniu/Moxie.swf",
        dragdrop: false,
        auto_start: true,
        unique_names: false,
        save_key: false,
        max_retries: 3,
        multi_selection: false,
        filters: {
            mime_types: [{
                title: "Image files",
                extensions: "jpg,jpeg,png"
            }]
        },

        init: {
            "FileUploaded": function(up, file, info) {
                // info 为 json，格式是后台获取 token 时设置的 ReturnBody
                var domain = up.getOption("domain");
                var infoObj = JSON.parse(info);
                var url = domain + infoObj.url;
                $("#org_pics_preview").append("<div class='article-cover-add border-radius'><img style='width: auto; height: 100%;' src=" + url + " /></div>");
                $("#org_pics").val($("#org_pics").val() + "@@" + url);
            },
            "Error": function(up, err, errTip) {
                console.log("上传出错：", err)
            },
            "UploadComplete": function() {
                console.log("队列文件处理完毕后,处理相关的事情");
            },
            "Key": function(up, file) {
                console.log("自定义上传文件名");
                var rand = Math.floor(Math.random() * 1000000000)
                var date = new Date()
                var ext = Qiniu.getFileExtension(file.name);
                var key = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + "org_pic_" + rand + "." + ext;
                console.log(key);
                return key;
            }
        }
    });
});

function checkInfoFull(ue) {
    if ($("#org_name").val().length == 0) {
        return "请填写机构名称";
    }
    if ($("#org_short_name").val().length == 0) {
        return "请填写机构简称";
    }
    var intro = ue.getContent();
    console.log(intro);
    if (intro.length == 0) {
        return "请填写机构介绍";
    }
    if ($("#avatar_preview_img")[0].src.length == 0) {
        return "请上传机构头像";
    }
    if ($("#province_select option:selected").val() == "0") {
        return "请选择省份";
    }
    if ($("#city_select option:selected").val() == "0") {
        return "请选择城市";
    }
    if ($("#district_select option:selected").val() == "0") {
        return "请选择区县";
    }
    if ($("#address").val().length == 0) {
        return "请填写地址";
    }
    var selectIll = false;
    $("input[name='ill_checkbox']:checkbox:checked").each(function(){ 
        selectIll = true;
        return false;
    });
    if (selectIll == false) {
        return "请选择服务病种";
    }
    if ($("#org_category").val().length == 0 || $("#org_category").val() == "0") {
        return "请选择机构类型";
    }
    if ($("#org_phone").val().length > 0) {
        if (/^(\d{3,4}-?\d{7,8}$)|(1\d{10}$)/.test($("#org_phone").val()) == false) {
            return "请填写正确的机构电话";
        }
    }
    return "";
}

function doFail(res) {
    serverErrorMsg(res);
}