var res = "";
/*var UserID = sessionStorage.getItem("MiaoMuUserID");
var userInfo = JSON.parse(sessionStorage.getItem("miaomuUserInfo"));*/
if(UserID!=null&&UserID!=""){
    var forShow = userInfo.name;
    if(forShow==null||forShow==""){
        forShow = userInfo.mobile;
    }
}
var pdType = "";
function checkPin() {
    var pin = $("#pin").val();
    pin = pin.toUpperCase();
    if (pin == res) {
        return true;
    } else {
        return false;
    }
}
$(function () {
    loadMes();
    if (UserID != null && UserID != "") {
        $("#topInfo").html("你好" + forShow + "用户!【<a onclick='logout()' href='javascript:void(0);'>退出</a>】");
        $("#mess1").html("<a href='message.html' target='_blank'>未读消息【0】</a>");
        $("#mess2").html("<a>最新交易【0】</a>");
        countMes();
    }
    //看不清 换一张
    $("#showPin").click(function () {
        draw();
    });
    //省市区
    region_init("sf", "cs", "dq");

    $("#type").on("change",function () {
        pdType = $(this).val();
        if(pdType==""){
            $(".xs").hide();
            $(".yc").hide();
            $(".ggm").html("æ ª");
        }else if(pdType == "绿化乔木"){
            $(".yc").hide();
            $(".xs").show();
            $(".qm").show();
            $(".ggm").html("æ ª");
        }else if(pdType == "绿化灌木"){
            $(".yc").hide();
            $(".xs").show();
            $(".gm").show();
            $(".ggm").html("æ ª");
        }else if(pdType == "球类苗木"){
            $(".yc").hide();
            $(".xs").show();
            $(".ql").show();
            $(".ggm").html("æ ª");
        }else if(pdType == "花草种苗"){
            $(".yc").hide();
            $(".xs").show();
            $(".hc").show();
            $(".ggm").html("æ ª");
        }else if(pdType == "绿植盆景"){
            $(".yc").hide();
            $(".xs").show();
            $(".hc").show();
            $(".ggm").html("æ ª");
        }else if(pdType == "地被草坪"){
            $(".yc").hide();
            $(".cp").show();
            $(".ggm").html("平米");
        }else if(pdType == "苗木种子"){
            $(".yc").hide();
            $(".cp").show();
            $(".ggm").html("æ–¤");
        }else if(pdType == "苗木资材"){
            $(".yc").hide();
            $(".cp").show();
            $(".ggm").html("个");
        }
    });
    $(".not-nes").click(function () {
        var flag = $(".not-nes>img").attr("src");
        $(".detail").slideToggle();
        if (flag == "../images/down1.png") {
            $(".not-nes>img").attr("src", "../images/up1.png");
        } else {
            $(".not-nes>img").attr("src", "../images/down1.png");
        }
    });

    //图片回显
    $("#tp1").on("change", function () {
        var img = $(this).val();
        if (img == null || img == "") {
            $("#tpd1").css("background-image", "url(\"../images/上传照片.jpg\")");
            $("#tpd1").nextAll().remove();
            flag01 = true;
            flag02 = true;
            flag03 = true;
        }else if(this.files[0].type.split("/")[0]!="image"){
            layer.msg("请选择图片文件",{icon:2});
        } else {
            showMask('读取中,请稍候');
            var file = this.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                $("#tpd1").css("background-image", "url(\"" + this.result + "\")");
                hideMask();
            };
        }
    });

    //取消
    $("#cancel").click(function () {
        layer.confirm('内容将不会保存,确定取消发布吗?', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            sessionStorage.removeItem("MiaoMuUserID");
            layer.msg('即将跳转', { icon: 0 });
            setTimeout(function () {
                window.location.href = "../manage/";
            }, 2000);
        }, function () {
            layer.msg('取消操作', {
                time: 2000 });
        });
    });
    //确认发布
    $("#sure").click(function () {
        release();
    });
    $("#my,#myl").click(function () {
        var check = $("#my").is(":checked");
        if (check) {
            $("#jg").val("");
            $("#jg").attr("disabled", "true");
        } else {
            $("#jg").removeAttr("disabled");
        }
    });
    $("#mr,#mrl").click(function () {
        var check = $("#mr").is(":checked");
        if (check) {
            $("#lxr,#tel,#company,#mobile,#sf,#cs,#dq,#add").val("");
            $("#lxr,#tel,#company,#mobile,#sf,#cs,#dq,#add").attr("disabled", "true");
        } else {
            $("#lxr,#tel,#company,#mobile,#sf,#cs,#dq,#add").removeAttr("disabled");
        }
    });
});
function randomRgbColor() {
    //随机生成RGB颜色
    var r = Math.floor(Math.random() * 156); //随机生成256以内r值
    var g = Math.floor(Math.random() * 156); //随机生成256以内g值
    var b = Math.floor(Math.random() * 156); //随机生成256以内b值
    return "rgb(" + r + "," + g + "," + b + ")"; //返回rgb(r,g,b)格式颜色
}
window.onload = function () {
    draw();
};

function draw() {
    res = "";
    var canvas = document.getElementById("showPin");
    var context = canvas.getContext("2d");
    canvas.width = 120;
    canvas.height = 40;
    context.strokeRect(0, 0, 120, 40);
    var aCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,1,2,3,4,5,6,7,8,9";
    console.log(aCode.split(","));
    var aLength = aCode.split(",").length;
    for (var i = 0; i <= 3; i++) {
        var x = 10 + i * 28;
        var y = 25 + Math.random() * 5;
        var j = Math.floor(Math.random() * aLength);
        var deg = Math.random() * 30 * Math.PI / 180; //随机弧度
        var txt = aCode.split(",")[j];
        res += txt;
        context.fillStyle = randomRgbColor();
        context.font = "bold 28px 微软雅黑";
        //修改坐标原点和旋转角度
        context.translate(x, y);
        context.rotate(deg);
        context.fillText(txt, 0, 0);
        //恢复坐标原点和旋转角度
        context.rotate(-deg);
        context.translate(-x, -y);
    }
    //干扰线
    for (var i = 0; i < 8; i++) {
        context.strokeStyle = randomRgbColor();
        context.beginPath();
        context.moveTo(Math.random() * 120, Math.random() * 40);
        context.lineTo(Math.random() * 120, Math.random() * 40);
        context.stroke();
    }
    /**绘制干扰点**/
    for (var i = 0; i < 100; i++) {
        context.fillStyle = randomRgbColor();
        context.beginPath();
        context.arc(Math.random() * 120, Math.random() * 40, 1, 0, 2 * Math.PI);
        context.fill();
    }
}
function createNum(userid) {
    var result = "";
    var d = new Date();
    var t = "" + d.getFullYear() + add0(d.getMonth() + 1) + add0(d.getDate()) + add0(d.getHours()) + add0(d.getMinutes()) + add0(d.getSeconds());
    //let t = ""+d.getFullYear()+add0(d.getMonth()+1)+add0(d.getDate());
    t += "1";
    t += add02(userid);
    $.ajax({
        url:url+"/mysj/info/listbianhao",
        data: { "dingdanbianhao": t },
        type: "get",
        dateType: "json",
        async: false,
        success: function success(response, status, xhr) {
            if (response.length > 0) {
                layer.msg("网络波动,请重试!", { icon: 0 });
            } else {
                result = t;
            }
        },
        error: function error(e) {
            layer.msg("系统错误,请联系客服!", { icon: 5 });
            console.log("查询编号ajax错误");
            console.log(e.status);
            console.log(e.responseText);
        }
    });
    return result;
}
function add0(num) {
    if (num < 10) {
        return "0" + num;
    } else {
        return num;
    }
}
function add02(num) {
    num += "";
    var temp = 7 - num.length;
    if (temp != 0) {
        for (var i = 0; i < temp; i++) {
            num = "0" + num;
        }
    }
    return num;
}
/*function logout() {
    layer.confirm('确定退出登录吗?', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        sessionStorage.removeItem("MiaoMuUserID");
        sessionStorage.removeItem("miaomuUserInfo");
        layer.msg('即将退出', { icon: 0 });
        setTimeout(function () {
            window.location.href = "../";
        }, 2000);
    }, function () {
        layer.msg('取消操作', {
            time: 2000 });
    });
}*/
function loadMes(){
    if(UserID!=null&&UserID!=""&&userInfo!=null){
        $.ajax({
            url:url+"/user/xiaoxi/chaxunxiaoxicount",
            data: { "userid": userInfo.id},
            type: "get",
            dateType: "json",
            async: false,
            success: function success(response, status, xhr) {
                if(response==0){
                    $("#not-read").hide();
                }else if(response>99){
                    $("#not-read").html("99+");
                    $("#not-read").show();
                }else{
                    $("#not-read").html(response);
                    $("#not-read").show();
                }
            },
            error: function error(e) {
                layer.msg("系统错误,请联系客服!", { icon: 5 });
                console.log("查询报价条数ajax错误");
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }else{
        $("#not-read").hide();
    }
}

function countMes() {
    $.ajax({
        url:url+"/user/xiaoxict/selectxiaoxictzhuangtaicount",
        data:{"reserveid":userInfo.id},
        type: "post",
        dateType: "json",
        async: false,
        success: function (response, status, xhr) {
            $("#mess1").html("<a href='message.html' target='_blank'>未读消息【"+response+"】</a>");
        },
        error:function (e) {
            layer.msg("系统错误,请联系客服!", { icon: 5 });
            console.log("countMes");
            console.log(e.status);
            console.log(e.responseText);
        }
    });
}



function release() {
    var name = $("#name").val();
    var price = $("#jg").val();
    var hits = $("#sl").val();
    var pin = $("#pin").val();
    var lxr = $("#lxr").val();
    var tel = $("#tel").val();
    var add = $("#add").val();
    var company = $("#company").val();
    var mobile = $("#mobile").val();
    var yxrq = $("#yxrq").val();
    var sf = $("#sf option:selected").text();
    var cs = $("#cs option:selected").text();
    var dq = $("#dq option:selected").text();
    var mr = document.getElementById("mr").checked;
    var my = document.getElementById("my").checked;
    var reg1 = /(1[3-9][\d]{9})|(\d{4}-\d{8})/;
    var reg2 = /1[3-9][\d]{9}/;
    var reg3 = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
    var gd1="";
    var gd2="";
    var gj1="";
    var gj2="";
    var gf1="";
    var gf2="";
    var bz="";
    var dw = "æ ª";
    var fz1=$("#fz1").val();
    var fz2=$("#fz2").val();
    var zt1=$("#zt1").val();
    var zt2=$("#zt2").val();
    if(pdType == "绿化乔木"){
        gj1 = $("#gj1").val();
        gj2 = $("#gj2").val();
        gd1=$("#gd11").val();
        gd2=$("#gd22").val();
        gf1=$("#gf11").val();
        gf2=$("#gf22").val();
        bz = $("#bz2").val().split("<").join("&lt;").split(">").join("&gt;");
    }else if(pdType == "绿化灌木"||pdType == "花草种苗"||pdType == "绿植盆景"){
        gj1 = $("#gj11").val();
        gj2 = $("#gj22").val();
        gd1=$("#gd1").val();
        gd2=$("#gd2").val();
        gf1=$("#gf11").val();
        gf2=$("#gf22").val();
        bz = $("#bz2").val().split("<").join("&lt;").split(">").join("&gt;");
    }else if(pdType == "球类苗木"){
        gj1 = $("#gj11").val();
        gj2 = $("#gj22").val();
        gd1=$("#gd11").val();
        gd2=$("#gd22").val();
        gf1=$("#gf1").val();
        gf2=$("#gf2").val();
        bz = $("#bz2").val().split("<").join("&lt;").split(">").join("&gt;");
    }else if(pdType == "地被草坪"){
        bz = $("#bz1").val().split("<").join("&lt;").split(">").join("&gt;");
        dw = "平米";
    }else if(pdType == "苗木种子"){
        bz = $("#bz1").val().split("<").join("&lt;").split(">").join("&gt;");
        dw = "æ–¤";
    }else if(pdType == "苗木资材"){
        bz = $("#bz1").val().split("<").join("&lt;").split(">").join("&gt;");
        dw = "个";
    }
    if(my){
        price = -1;
    }
    if(name==null||name==""){
        layer.msg("请输入产品名",{icon:2});
    }else if(!checkInfo()){

    }else if(!my&&(price==null||price=="")){
        layer.msg("请输入价格",{icon:2});
    }else if(!my&&(price<=0||!reg3.test(price))){
        layer.msg("请输入合理的价格",{icon:2});
    }else if(hits==null||hits==""){
        layer.msg("请输入数量",{icon:2});
    }else if(hits<=0||hits%1!=0){
        layer.msg("请输入合理的数量",{icon:2});
    }else if(yxrq==null||yxrq==""){
        layer.msg("请选择有效时间",{icon:2});
    }else if(pin==null||pin==""){
        layer.msg("请输入验证码",{icon:2});
    }else if(!checkPin()){
        layer.msg("验证码错误",{icon:2});
    }else if(mr&&(userInfo==null||UserID==null)){
        layer.msg("您尚未登录,请手动输入联系信息!", { icon: 2 });
    }else if(mr&&(userInfo.ownaddress==null||userInfo.ownaddress==""||userInfo.name==null||userInfo.name==""||userInfo.phone==null||userInfo.phone==""||userInfo.sf==null||userInfo.sf==""||userInfo.city==null||userInfo.city=="")){
        layer.msg("您的个人资料中联系方式不完善,请手动输入联系信息!", { icon: 2 });
    }else if(!mr&&(lxr==null||lxr=="")){
        layer.msg("请输入联系人",{icon:2});
    }else if(!mr&&(tel==null||tel=="")){
        layer.msg("请输入联系电话",{icon:2});
    }else if(!mr&&(sf==null||sf=="")){
        layer.msg("请选择地区",{icon:2});
    }else if(!mr&&(add==null||add=="")){
        layer.msg("请输入联系地址",{icon:2});
    }else if(!mr&&!reg1.test(tel)){
        layer.msg("请输入正确的联系电话,若输入座机,请加四位区号及“-”!", { icon: 2 });
    }else if(mobile!=null&&mobile!=""&&!reg2.test(mobile)){
        layer.msg("请输入正确的11位手机号!", { icon: 2 });
    }else{
        if (mr) {
            company = userInfo.qymc;
            var address = userInfo.ownaddress;
            tel = userInfo.phone;
            sf = userInfo.sf;
            cs = userInfo.city;
            mobile = userInfo.mobile;
            lxr = userInfo.name;
        } else {
            var address = sf + cs + dq + add;
        }
        var gg = GG1("杆径", gj1, gj2, "cm") + GG1("高度", gd1, gd2, "cm") + GG1("冠幅", gf1, gf2, "cm") + GG1("分枝点", fz1, fz2, "cm") + GG1("枝条数", zt1, zt2, "条");
        if (gg == "") {
            gg = "无详细信息";
        }
        var bh = "";
        if(userInfo==null||userInfo==""){
            bh = tel.substring(tel.length-7);
        }else{
            bh = createNum(userInfo.id);
        }
        if (bh != null && bh != "") {
            if(userInfo==null||UserID==null){
                var data = {
                    "showname": name,
                    "ganjing": gj1,
                    "ganjing1": gj2,
                    "gaodu1": gd1,
                    "gaodu2": gd2,
                    "guanfu1": gf1,
                    "guanfu2": gf2,
                    "fenzhidian": fz1,
                    "fenzhidian1": fz2,
                    "hits": hits,
                    "price": price,
                    "linkman": lxr,
                    "company": company,
                    "address": address,
                    "phone": tel,
                    "country":sf,
                    "city":cs,
                    "dateandtime": new Date(),
                    "dingdanbianhao":bh,
                    "zhitiaoshu1": zt1,
                    "zhitiaoshu2": zt2,
                    "pdType": pdType,
                    "danwei": dw,
                    "fax":mobile,
                    "chanpinguige":bz,
                    "content":gg,
                    "period":yxrq,
                    "picture":upImg("tp1")
                };
            }else{
                var data = {
                    "hyjb":userInfo.hyjb,
                    "showname": name,
                    "ganjing": gj1,
                    "ganjing1": gj2,
                    "gaodu1": gd1,
                    "gaodu2": gd2,
                    "guanfu1": gf1,
                    "guanfu2": gf2,
                    "fenzhidian": fz1,
                    "fenzhidian1": fz2,
                    "hits": hits,
                    "price": price,
                    "linkman": lxr,
                    "company": company,
                    "address": address,
                    "phone": tel,
                    "country":sf,
                    "city":cs,
                    "dateandtime": new Date(),
                    "dingdanbianhao":bh,
                    "zhitiaoshu1": zt1,
                    "zhitiaoshu2": zt2,
                    "pdType": pdType,
                    "danwei": dw,
                    "fax":mobile,
                    "chanpinguige":bz,
                    "gsid":userInfo.id,
                    "content":gg,
                    "period":yxrq,
                    "picture":upImg("tp1")
                };
            }
            $.ajax({
                url:url+"/mysj/info/fbqg",
                data: data,
                type: "post",
                dateType: "json",
                async: false,
                success: function success(response, status, xhr) {
                    if (response == 1) {
                        layer.msg("发布成功,即将跳转!", { icon: 1 });
                        setTimeout(function () {
                            if(UserID==null||UserID==""){
                                window.location.href = "../";
                            }else{
                                window.location.href = "../manage/";
                            }
                        }, 2000);
                    } else {
                        layer.msg("系统错误,请联系客服!", { icon: 5 });
                        console.log("插入求购数不等于1");
                    }
                },
                error: function error(e) {
                    layer.msg("系统错误,请联系客服!", { icon: 5 });
                    console.log("插入求购ajax错误");
                    console.log(e.status);
                    console.log(e.responseText);
                }
            });
        }
    }
}

function GG1(str, num1, num2,dw) {
    if((num1==null||num1=="")&&(num2==null||num2=="")){
        return "";
    }else{
        return str+":"+num1+"~"+num2+dw+" ";
    }
}
function GG2(str, text) {
    if(text==null||text==""){
        return "";
    }else{
        return str+":"+text;
    }
}

function checkInfo() {
    var flag = false;
    if(pdType==""){
        layer.msg("请选择产品类别",{icon:2});
    }else if(pdType == "绿化乔木"){
        var gj1 = $("#gj1").val();
        var gj2 = $("#gj2").val();
        if(gj1==null||gj1==""||gj2==null||gj2==""){
            layer.msg("请输入杆径",{icon:2});
        }else{
            flag = true;
        }
    }else if(pdType == "绿化灌木"||pdType == "花草种苗"||pdType == "绿植盆景"){
        var gd1 = $("#gd1").val();
        var gd2 = $("#gd2").val();
        if(gd1==null||gd1==""||gd2==null||gd2==""){
            layer.msg("请输入高度",{icon:2});
        }else{
            flag = true;
        }
    }else if(pdType == "球类苗木"){
        var gf1 = $("#gf1").val();
        var gf2 = $("#gf2").val();
        if(gf1==null||gf1==""||gf2==null||gf2==""){
            layer.msg("请输入冠幅",{icon:2});
        }else{
            flag = true;
        }
    }else if(pdType == "地被草坪"||pdType == "苗木种子"||pdType == "苗木资材"){
        var bz1 = $("#bz1").val();
        if(bz1==null||bz1==""){
            layer.msg("请输入备注",{icon:2});
        }else{
            flag = true;
        }
    }
    return flag;
}


function upImg(id) {
    var result = "";
    var fileInput = document.getElementById(id);
    if (fileInput != null) {
        var inputValue = fileInput.value;
        if (inputValue != null && inputValue != "") {
            var file = document.getElementById(id).files[0];
            var formDate = new FormData();
            formDate.append("fileName", file);
            $.ajax({
                url:url+"/file/uploadFile",
                data: formDate,
                type: "post",
                dateType: "json",
                async: false,
                processData: false,
                contentType: false,
                success: function success(response, status, xhr) {
                    result = response[0];
                    if(result.length<3){
                        console.log("图片未上传原因:"+result);
                    }
                },
                error: function error(e) {
                    layer.msg("系统错误,请联系客服!", { icon: 5 });
                    console.log("上传图片ajax错误");
                    console.log(e.status);
                    console.log(e.responseText);
                }
            });
        }
    }
    return result;
}