/**
 * Created by Jerold Chen on 2018/4/17.
 */
$(function () {

    var wrapHeight = $(document).height();
    var checkType = null;
    $('body').css("height", wrapHeight - 20);
    var phonereg = /^[1][3,4,5,7,8][0-9]{9}$/;
    var reChina = /^[\u4e00-\u9fa5]+$/;
    var myEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    // 验证空格
    var regSpace = /(^\s+)|(\s+$)|\s+/g;
    laydate.render({
        elem: '#startDate',
        format: 'yyyy-MM-dd',
        min: getNowFormatDate(),
        showBottom: false,
        done: function (value, date, endDate) {
            //  console.log(value); //得到日期生成的值，如：2017-08-18
            $("#endDate").html(dateAddDays(value, 1));
        }
    });
    // 判断localStorage 是否有token
    if (localStorage.getItem('token')) {
        var objParams = {
            token: localStorage.getItem('token')
        };
        $.ajax({
            type: "post",
            contentType: 'application/json;charset=UTF-8',
            url: "https://mdev.zuihuibi.cn/api/authorize/checkToken",
            dataType: "json",
            async: false,
            data: JSON.stringify(objParams),
            beforeSend: function(request) {
                request.setRequestHeader("X-Authorization", localStorage.getItem('token'));
            },
            success: function (data) {
                if (data.success) {

                } else {
                    getToken();
                }
            },
            error: function (xhr, status, error) {

            }
        })
    } else {
        getToken();
    }


    // 判断本次活动是否到期并且是否上架
    var cmpaignData = {
        campaignId: 6
    };
    $.ajax({
        type: 'POST',
        contentType: 'application/json;charset=UTF-8',
        dataType: 'json',
        url: "https://mdev.zuihuibi.cn/api/promotion/campaignQry",
        data: JSON.stringify(cmpaignData),
        beforeSend: function(request) {
            request.setRequestHeader("X-Authorization", localStorage.getItem('token'));
        },
        success: function (d) {
            if (d.success) {
                if (d.data.isActive != 1 || d.data.isEffective != 1) {
                    // 此活动下架 并且在过期
                    $('.endBg').show();
                    $('.endContent').show();
                    // $('body').css('overflow', 'hidden');
                    // $('html').css('overflow', 'hidden');
                }
            } else {

            }
        }
    });
    // 设置初始日期
    $("#startDate").val(getNowFormatDate());
    $("#endDate").html(getThreeFormatDate());
    var flag = true;
    // 保存
    $("#btnSave").click(function () {
        if (flag) {
            var arrSports = [];
            var travelFamily = '';
            $(".subject input[type=checkbox]").each(function () {
                if ($(this).get(0).checked) {
                    arrSports.push($(this).val());
                }
            });
            var checkedVal = $(".answerSecond input[name='cPeople']:checked").val();
            if (checkedVal == '1') {
                travelFamily = 'S';
            } else if (checkedVal == '2') {
                travelFamily = 'F';
            } else {
                travelFamily = '';
            }
            var isDriveOut = $(".answerThird input[name='trvalCar']:checked").val();

            if (arrSports.length == 0) {
                $.alert('请选择本次旅行参与的运动！');
                return;
            }
            if (travelFamily == '') {
                $.alert('请选择本次旅行是自己还是家人！');
                return;
            }
            if (isDriveOut == '' || isDriveOut == undefined) {
                $.alert('请选择是否自驾出行！');
                return;
            }
            var startDate = $("#startDate").val();
            var endDate = $("#endDate").html();
            var ownerName = $("#ownerName").val();
            var phone = $("#phone").val();
            var idCard = $("#idCard").val();
            var insureeEmail = $("#insureeEmail").val();
            if (startDate == '') {
                $.alert('出行日期不能为空！');
                return;
            }
            if (ownerName != '') {
                if (ownerName.length > 6 || ownerName.length <= 1) {
                    $.alert('被保人姓名只能为2~6个字符！');
                    return;
                } else {
                    // 先判断空格
                    if (ownerName.indexOf(" ") >= 0) {
                        $.alert('被保人姓名中不能包含空格！');
                        return;
                    } else {
                        if (!reChina.test(ownerName)) {
                            $.alert('请正确输入被保人姓名！');
                            return;
                        }
                    }
                }
            } else {
                $.alert('被保人姓名不能为空！');
                return;
            }
            if (phone != '') {
                if (!phonereg.test(phone)) {
                    $.alert("请正确输入被保人手机号码！");
                    return;
                }
            } else {
                $.alert('被保人手机号不能为空！');
                return;
            }
            if (idCard != '') {
                if (!IdCodeValid(idCard).pass) {
                    $.alert("请正确输入被保人身份证号码！");
                    return;
                }
            } else {
                $.alert('被保人身份证不能为空！');
                return;
            }
            if (insureeEmail != '') {
                if (insureeEmail.length < 101) {
                    if (!myEmail.test(insureeEmail)) {
                        $.alert("请正确输入被保人邮箱！");
                        return;
                    }
                } else {
                    $.alert("被保人邮箱最长为100个字符！");
                    return;
                }
            } else {
                $.alert('被保人邮箱不能为空！');
                return;
            }
            var isBike = '';
            var isDive = '';
            var isMarathon = '';
            var isClimb = '';
            var isHike = '';
            var isSki = '';
            var isSail = '';
            var isBall = '';
            if ($("#isBike").is(':checked')) {
                isBike = '1';
            } else {
                isBike = '0';
            }
            if ($("#isDive").is(':checked')) {
                isDive = '1';
            } else {
                isDive = '0';
            }
            if ($("#isMarathon").is(':checked')) {
                isMarathon = '1';
            } else {
                isMarathon = '0';
            }
            if ($("#isClimb").is(':checked')) {
                isClimb = '1';
            } else {
                isClimb = '0';
            }
            if ($("#isHike").is(':checked')) {
                isHike = '1';
            } else {
                isHike = '0';
            }
            if ($("#isSki").is(':checked')) {
                isSki = '1';
            } else {
                isSki = '0';
            }
            if ($("#isSail").is(':checked')) {
                isSail = '1';
            } else {
                isSail = '0';
            }
            if ($("#isBall").is(':checked')) {
                isBall = '1';
            } else {
                isBall = '0';
            }
            //判断来源
            var dataSource = '';
            var source = getUrlParam("source");
            if (source == '1') {
                dataSource = '今日头条';
            } else if (source == '2') {
                dataSource = '微博';
            } else if (source == '0') {
                dataSource = '微信';
            }
            // 保存参数
            var saveData = {
                visitorNo: '2day-campaign',
                isBike: isBike,
                isDive: isDive,
                isMarathon: isMarathon,
                isClimb: isClimb,
                isHike: isHike,
                isSki: isSki,
                isSail: isSail,
                isBall: isBall,
                travelFamily: travelFamily,
                isDriveOut: isDriveOut,
                travelDateFrom: startDate,
                travelDateTo: endDate,
                insureeName: ownerName,
                insureeMobile: phone,
                insureeIdNo: idCard,
                dataSource: dataSource,
                campaignId: 6,
                insureeEmail: insureeEmail
            };
            $(".loadBg").show();
            $(".loadings").show();
            $.ajax({
                type: 'POST',
                contentType: 'application/json;charset=UTF-8',
                dataType: 'json',
                url: "https://mdev.zuihuibi.cn/api/promotion/questionnaireSave",
                data: JSON.stringify(saveData),
                beforeSend: function(request) {
                    request.setRequestHeader("X-Authorization", localStorage.getItem('token'));
                },
                success: function (data) {
                    // console.log(data)
                    if (data.success) {
                        // 关闭加载中 (提交成功)
                        $(".loadBg").hide();
                        $(".loadings").hide();

                        $(".bgColor").show();
                        $(".bgContent").show();
                        // 提交按钮disabled
                        $("#btnSave").prop('src', 'layer/images/btn-disabled.png');
                        // $('body').css('overflow', 'hidden');
                        // $('html').css('overflow', 'hidden');
                    } else {
                        $(".loadBg").hide();
                        $(".loadings").hide();
                        $.alert(data.message);
                    }
                }
            })
        } else {
            $.alert('你已提交成功，不能重复提交！');
        }
    });
    // 点击分享
    $("#shareOther").click(function () {
        // 判断pc 还是mobile
        var iSMobile = goPAGE();
        // console.log(iSMobile)
        if (iSMobile == '1') {
            // mobile
            $(".bgColor").hide();
            $(".bgContent").hide();
            $(".guideImg").show();
        } else {
            // pc 端

        }
    })
    // 分享完成之后 关闭分享导向 不能再编辑提交
    $('.guideImg').click(function () {
        $(".guideImg").hide();
        // $('body').css('overflow-x', 'hidden');
        // $('body').css('overflow-y', 'auto');
        // $('html').css('overflow-x', 'hidden');
        // $('html').css('overflow-y', 'auto');
        flag = false;
    });

    // 微信分享接口 （首先去调用后台接口去注册所需要的参数）
    var Currenturl = location.href.split('#')[0];//url不能写死
    var objDate = {
        url: Currenturl
    };
    $.ajax({
        type: "post",
        contentType: 'application/json;charset=UTF-8',
        url: "https://mdev.zuihuibi.cn/api/wxConfig",
        dataType: "json",
        async: false,
        data: JSON.stringify(objDate),
        beforeSend: function(request) {
            request.setRequestHeader("X-Authorization", localStorage.getItem('token'));
        },
        success: function (res) {
            // console.log(data);
            setTimeout(function () {
                wx.config({
                    debug: false,////生产环境需要关闭debug模式
                    appId: res.data.appId,//appId通过微信服务号后台查看
                    timestamp: res.data.timestamp,//生成签名的时间戳
                    nonceStr: res.data.nonceStr,//生成签名的随机字符串
                    signature: res.data.signature,//签名
                    jsApiList: [//需要调用的JS接口列表
                        'checkJsApi',//判断当前客户端版本是否支持指定JS接口
                        'onMenuShareTimeline',//分享给好友
                        'onMenuShareAppMessage',//分享到朋友圈
                        'onMenuShareQQ'       // 分享到QQ接口
                    ]
                });
            }, 500)
        },
        error: function (xhr, status, error) {
            //alert(status);
            //alert(xhr.responseText);
        }
    })

    wx.ready(function () {
        var link = window.location.href;
        var protocol = window.location.protocol;
        console.log(protocol);
        var host = window.location.host;
        //分享朋友圈
        wx.onMenuShareTimeline({
            title: '免费获取户外旅行保险',
            link: link,
            imgUrl: protocol + '//mdev.zuihuibi.cn/2days-campaign/layer/images/share.jpg',// 自定义图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                //alert('click shared');
            },
            success: function (res) {
                //alert('shared success');
                //some thing you should do
                $(".guideImg").hide();
                flag = false;
            },
            cancel: function (res) {
                //alert('shared cancle');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
        //分享给好友
        wx.onMenuShareAppMessage({
            title: '免费获取户外旅行保险', // 分享标题
            desc: '爱生活，爱运动，春夏出行，户外旅行保险免费送。', // 分享描述
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: protocol + '//mdev.zuihuibi.cn/2days-campaign/layer/images/share.jpg', // 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
                $(".guideImg").hide();
                flag = false;
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        // 分享qq
        wx.onMenuShareQQ({
            title: '免费获取户外旅行保险',
            desc: '爱生活，爱运动，春夏出行，户外旅行保险免费送。', // 分享描述
            link: link,
            imgUrl: protocol + '//mdev.zuihuibi.cn/2days-campaign/layer/images/share.jpg',// 自定义图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                //alert('click shared');
            },
            success: function (res) {
                //alert('shared success');
                //some thing you should do
                $(".guideImg").hide();
                flag = false;
            },
            cancel: function (res) {
                //alert('shared cancle');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
        wx.error(function (res) {
            alert(res.errMsg);
        });
    });


    //得到传来的参数
    function getUrlParam(name) {
        var url = location.search;
        var value = "";
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                if (strs[i].split("=")[0] == name) {
                    value = unescape(strs[i].split("=")[1]);
                }
            }
        }
        return value;
    }

    // 获取当前日期+2天
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate() + 2;
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }

    // 获取当前日期+3天
    function getThreeFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate() + 3;
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }

    // 获取日期追加一天
    function dateAddDays(dataStr, dayCount) {
        var strdate = dataStr; //日期字符串
        var isdate = new Date(strdate.replace(/-/g, "/"));  //把日期字符串转换成日期格式
        isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000);  //日期加1天
        var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());   //把日期格式转换成字符串

        return pdate;
    }

    function goPAGE() {
        var isPc = '';
        if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
            /*window.location.href="你的手机版地址";*/
            // alert("mobile");
            isPc = '1';
        }
        else {
            /*window.location.href="你的电脑版地址";    */
            // alert("pc")
            isPc = '2';
        }
        return isPc;
    }

    // 获取token
    function getToken() {
        var objParam = {
            ticket: 'twoCampain'
        };
        $.ajax({
            type: "post",
            contentType: 'application/json;charset=UTF-8',
            url: "https://mdev.zuihuibi.cn/api/authorize/obtainToken",
            dataType: "json",
            async: false,
            data: JSON.stringify(objParam),
            beforeSend: function(request) {
                request.setRequestHeader("X-Authorization", localStorage.getItem('token'));
            },
            success: function (res) {
                console.log(res);
                localStorage.setItem('token', res.data.token);
            },
            error: function (xhr, status, error) {

            }
        })
    }




    // 身份证号码正则
    function IdCodeValid(code) {
        // 身份证号合法性验证
        // 支持15位和18位身份证号
        // 支持地址编码、出生日期、校验位验证
        var city = {
            11: '北京',
            12: '天津',
            13: '河北',
            14: '山西',
            15: '内蒙古',
            21: '辽宁',
            22: '吉林',
            23: '黑龙江 ',
            31: '上海',
            32: '江苏',
            33: '浙江',
            34: '安徽',
            35: '福建',
            36: '江西',
            37: '山东',
            41: '河南',
            42: '湖北 ',
            43: '湖南',
            44: '广东',
            45: '广西',
            46: '海南',
            50: '重庆',
            51: '四川',
            52: '贵州',
            53: '云南',
            54: '西藏 ',
            61: '陕西',
            62: '甘肃',
            63: '青海',
            64: '宁夏',
            65: '新疆',
            71: '台湾',
            81: '香港',
            82: '澳门',
            91: '国外 '
        };
        var row = {
            'pass': true,
            'msg': '验证成功'
        };
        // 出生年月日校验   前正则限制起始年份为1900;
        var year = code.substr(6, 4);// 身份证年
        var month = code.substr(10, 2);// 身份证月
        var date = code.substr(12, 2);// 身份证日
        var time = Date.parse(month + '-' + date + '-' + year);// 身份证日期时间戳date
        var now_time = Date.parse(new Date().toDateString());
        var dates = (new Date(year, month, 0)).getDate();// 身份证当月天数
        if (!code || !/^\d{6}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
            row = {
                'pass': false,
                'msg': '身份证号格式错误'
            };
        } else if (!city[code.substr(0, 2)]) {
            row = {
                'pass': false,
                'msg': '身份证号地址编码错误'
            };
        } else if (time > now_time || date > dates) {
            row = {
                'pass': false,
                'msg': '出生日期不合规'
            }
        } else {
            // 18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                // ∑(ai×Wi)(mod 11)
                // 加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                // 校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                if (parity[sum % 11] != code[17].toUpperCase()) {
                    row = {
                        'pass': false,
                        'msg': '身份证号校验位错误'
                    };
                }
            }
        }
        return row;
    }

})