var form = (function () {
    'use strict';
    var Form = function (params) {
        var p = this;
        p.params = {
            appid: '',
            id: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            localStorage: [],
            getDeptApi: G.baseUri() + '/mobile/auth/appform/getDept',
            getTypeApi: G.baseUri() + '/mobile/auth/appform/getvisitorCategory',
            submitApi: G.baseUri() + '/mobile/auth/appform/appFormSubmit',
            isAppointmentApi: G.baseUri() + '/mobile/auth/appform/isAppointment',
            getData: G.baseUri() + '/mobile/auth/appform/getAppform',
            cancelData: G.baseUri() + '/mobile/auth/appform/cancelAppform',
            vt: ''
        };
        for (var param in params) {
            p.params[param] = params[param];
        }
        var cfApp = p.params.cfApp;

        if (p.params.devMode) {

        }
        p.params.id = "";
        p.pageSize = 10;
        p.pageNo = 0;
        p.channelData = [];
        p.typeNames = [];
        p.typeIds = [];
        p.isPersons = [];
        p.deptNames = [];
        p.deptIds = [];
        p.createDate = null;
        /**
         * 判断app字段
         * @returns 是否app有值
         */
        var validAppField = function () {
            if (!p.params.appid || p.params.appid == '') {
                return false;
            } else {
                return true;
            }
        };

        /**
         * 确认初始化的app 和tokenId 两个值是否都存在
         * 如果不存在则获取一次,获取不到则初始化失败
         * @returns 初始化基础字段是否成功
         */
        var initBaseFields = function () {
            if (!validAppField()) {
                p.params.appid = cfApp.getQueryString('appid');
                p.params.id = cfApp.getQueryString('id');
                p.params.accountsId = cfApp.getQueryString('accountsId');
            }


            //如果获取不到app和tokenId,则直接从传入的CfApp中获取值
            if (!validAppField()) {
                if (p.params.cfApp) {
                    p.params.appid = cfApp.getAppId();
                    //p.params.tokenId = cfApp.getTokenId();
                }
            }
            p.empInfo = cfApp.getMpInfo();
            p.params.accountsId = p.empInfo.accountsId;
            return validAppField();
        };

        /**
         * 初始化组件
         * @returns {boolean}
         */


        p.init = function () {
            var isPageHide = false;
            window.addEventListener('pageshow', function () {
                if (isPageHide) {
                    window.location.reload();
                }
            });
            window.addEventListener('pagehide', function () {
                isPageHide = true;
            });
            if (initBaseFields()) {
                if (!p.params.id || p.params.id == null || p.params.id == '') {
                    $("#next_step").show();
                    initDate();
                    submitData();
                    visitorCategory();
                    getdept();
                    log("展厅预约");
                    cacheFullData();
                } else {//查看，取消预约
                    log("预约详情");
                    loadData();
                    cancelData();
                    $("#TechnicalExpertDiv").show();//显示技术讲解人
                }
                return true;
            } else {
                return false;
            }
        };

        var cacheFullData = function () {
            var formDataStr = localStorage.getItem("form" + p.params.appid);
            if (formDataStr && formDataStr != null && formDataStr != '') {//读取本地缓存信息，若本地缓存信息中没有,则读取最新的一条订单
                var formData = JSON.parse(formDataStr);
                cacheFull(formData);
            } else {
                var formData = {
                    openId: p.empInfo.openId
                }
                G.ajax('post', p.params.getData, formData, function (retdata) {
                    if (retdata.errorNo == '0') {
                        var data = retdata.data;
                        if (data && data != null) {
                            cacheFull(data);
                        }
                    }
                })
            }
        }

        var cacheFull = function (data) {
            $("input[name='name']").val(data.name);
            $("input[name='email']").val(data.email);
            $("input[name='dept']").val(data.dname);
        }

        var log = function (obj) {
            var formdata = {
                openid: p.empInfo.openId,
                module: "展厅申请",
                modulename: obj,
                keyword: obj,
                keywordid: '',
                vt: new Date().getTime(),
                appid: cfApp.getQueryString('appid'),
                url: location.href
            };
            G.ajax(G.devModePost, '/schaeffler/mobile/testAsync/doLOg', formdata, function (retdata) {


            });
        }

        var getNowFormatDate = function () {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            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;
        }


        var getNowFormatDateTime = function () {//获取当前时间 yyyy-MM-dd HH:mm
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes();
            return currentdate;
        }


        //初始化来访者类别
        var visitorCategory = function () {
            var formdata = {};
            G.ajax('get', p.params.getTypeApi, formdata, function (retdata) {
                if (retdata.errorNo == '0') {
                    if (retdata.datas && retdata.datas != null && retdata.datas.length > 0) {
                        for (var i = 0; i < retdata.datas.length; i++) {
                            p.typeNames.push(retdata.datas[i].name);
                            p.typeIds.push(retdata.datas[i].id);
                            p.isPersons.push(retdata.datas[i].isExplainer);
                        }
                    }
                    $("#come_type").picker({
                        title: "来访者类别",
                        cols: [
                            {
                                textAlign: 'center',
                                displayValues: p.typeNames,
                                values: p.typeNames
                            }
                        ],
                        onClose: function (data) {
                            console.log("来访者类别：" + data);
                        }
                    });
                }
            })
        }

        //初始化部门
        var getdept = function () {
            var formdata = {};
            G.ajax('get', p.params.getDeptApi, formdata, function (retdata) {
                if (retdata.errorNo == '0') {
                    if (retdata.datas && retdata.datas != null && retdata.datas.length > 0) {
                        for (var i = 0; i < retdata.datas.length; i++) {
                            p.deptNames.push(retdata.datas[i].name);
                            p.deptIds.push(retdata.datas[i].id);
                        }
                    }
                    $("#dept").picker({
                        title: "所在部门",
                        cols: [
                            {
                                textAlign: 'center',
                                displayValues: p.deptNames,
                                values: p.deptNames
                            }
                        ],
                        onClose: function (data) {
                            console.log("所在部门：" + data);
                        }
                    });
                }
            })
        }


        var validateDateSelect = function () {
            var date = $("input[name='date']").val();
            var begintime = $("input[name='begintime']").val();
            if (StringValidateUtils.isEmpty(date)) {
                alert("提示！请选择预约日期.Error！Please choose Booking date");
                return false;
            }
            var nowTime = getNowFormatDateTime();
            var datetimeSelected = date.replace(/\s*/g, "") + " " + begintime.replace(/\s*/g, "");

            var begin = new Date(nowTime.replace(/-/g, "/"));
            var end = new Date(datetimeSelected.replace(/-/g, "/"));
            //js判断日期
            if (begin - end > 0) {
                alert("提示！开始时间应晚于现在。Error！Please select right start time.");
                $("#time-format1").val('');
                return false;
            }
            return true;
        }


        //初始化日期，时间控件
        var initDate = function () {
            $("#time-format").datetimePicker({
                title: '选择预约日期',
                yearSplit: '-',
                monthSplit: '-',
                dateSplit: ' ',
                min: getNowFormatDate(),
                times: function () {
                    return []
                },
                onClose: function (data) {
                    p.productDate = data.value.join(' ');
                    $("#time-format1").val('');
                    $("#time-format2").val('');
                }
            });

            $("#deptDiv").click(function (e) {
                e.stopPropagation();
                $("#dept").picker("open");
            })
            $("#date").click(function (e) {
                e.stopPropagation();
                $("#time-format").picker("open");
            })
            $("#begintime").click(function (e) {
                e.stopPropagation();
                $("#time-format1").picker("open");
            })
            $("#endtime").click(function (e) {
                e.stopPropagation();
                $("#time-format2").picker("open");
            })
            $("#typeDiv").click(function (e) {
                e.stopPropagation();
                $("#come_type").picker("open");
            })
            $("#time-format1").picker({    //开始时间初始化
                title: "请选择开始时间",
                cols: [
                    {
                        textAlign: 'center',
                        values: ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18']
                        //如果你希望显示文案和实际值不同，可以在这里加一个displayValues: [.....]
                    },
                    {
                        textAlign: 'center',
                        values: [':']
                    },
                    {
                        textAlign: 'center',
                        values: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
                    }
                ],
                onClose: function (data) {
                    validateDateSelect();
                }
            });

            $("#time-format2").picker({    //开始时间初始化
                title: "请选择结束时间",
                cols: [
                    {
                        textAlign: 'center',
                        values: ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18']
                        //如果你希望显示文案和实际值不同，可以在这里加一个displayValues: [.....]
                    },
                    {
                        textAlign: 'center',
                        values: [':']
                    },
                    {
                        textAlign: 'center',
                        values: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
                    }
                ],
                onClose: function (data) {
                    var date = $("input[name='date']").val();
                    if (StringValidateUtils.isEmpty(date)) {
                        alert("提示！请选择预约日期.Error！Please choose Booking date");
                        return false;
                    }
                    var begintime = $("input[name='begintime']").val();
                    if (StringValidateUtils.isEmpty(begintime)) {
                        alert("提示！请选择预约时间段.Error！Please choose Booking time");
                        return false;
                    }
                    var endtime = $("input[name='endtime']").val();
                    var beginDateTimeStr = date.trim() + " " + begintime.replace(/\s*/g, "");
                    var endDateTimeStr = date.trim() + " " + endtime.replace(/\s*/g, "");
                    var begin = new Date(beginDateTimeStr.replace(/-/g, "/"));
                    var end = new Date(endDateTimeStr.replace(/-/g, "/"));
                    //js判断日期
                    if (begin - end > 0) {
                        alert("提示！结束时间早于开始时间.Error！Please select right end time.");
                        $("#time-format2").val('');
                        return false;
                    }
                }
            });
        }


        var alert = function (data) {
            $.modal({
                title: "",
                text: data,
                buttons: [
                    {
                        text: "确定OK", onClick: function () {
                            console.log(1)
                        }
                    }
                ]
            });
        }

        //提交
        var submitData = function () {
            $("#next_step").click(function () {
                var name = $("input[name='name']").val();
                if (StringValidateUtils.isEmpty(name)) {
                    alert("请输入您的姓名. Please input your name.");
                    return false;
                }
                var email = $("input[name='email']").val();
                if (StringValidateUtils.isEmpty(email)) {
                    alert("请输入您的邮箱. Please input your email.");
                    return false;
                }
                var dept = $("input[name='dept']").val();
                if (StringValidateUtils.isEmpty(dept)) {
                    alert("请选择所在部门. Please choose Division/Department.");
                    return false;
                }
                var date = $("input[name='date']").val();
                if (StringValidateUtils.isEmpty(date)) {
                    alert("请选择预约日期. Please choose Booking date.");
                    return false;
                }
                var begintime = $("input[name='begintime']").val();
                if (StringValidateUtils.isEmpty(begintime)) {
                    alert("请选择预约时间段. Please choose Booking time.");
                    return false;
                }
                var endtime = $("input[name='endtime']").val();
                if (StringValidateUtils.isEmpty(endtime)) {
                    alert("请选择预约时间段. Please choose Booking time.");
                    return false;
                }
                var beginDateTimeStr = date.trim() + " " + begintime.replace(/\s*/g, "");
                var endDateTimeStr = date.trim() + " " + endtime.replace(/\s*/g, "");
                var begin = new Date(beginDateTimeStr.replace(/-/g, "/"));
                var end = new Date(endDateTimeStr.replace(/-/g, "/"));
                //js判断日期
                if (begin - end > 0) {
                    alert("结束时间早于开始时间. End time should be later than start time.");
                    return false;
                }

                var type = $("input[name='type']").val();
                if (StringValidateUtils.isEmpty(type)) {
                    alert("请选择来访客人类别. Please choose visitor category.");
                    return false;
                }
                var num = $("input[name='num']").val();
                if (StringValidateUtils.isEmpty(num)) {
                    alert("请输入来访客人总数. Please input visitor number.");
                    return false;
                }
                var content = $("textarea[name='content']").val();
                if (StringValidateUtils.isEmpty(content)) {
                    alert("请输入预约事由。Please input booking reason.");
                    return false;
                }
                var remarks = $("input[name='remarks']").val();
                var formdata = {
                    name: name,
                    email: email,
                    department: p.deptIds[p.deptNames.indexOf(dept)],
                    beginDateTimeStr: beginDateTimeStr,
                    endDateTimeStr: endDateTimeStr,
                    visitorCategory: p.typeIds[p.typeNames.indexOf(type)],
                    visitorNum: num,
                    applyContent: content,
                    description: remarks,
                    accountsId: p.empInfo.accountsId,
                    openid: p.empInfo.openId,
                    dname: dept,
                    vname: type,
                    first: "尊敬的" + name + "，您已成功预约舍弗勒安亭展厅。",
                    remarks: "点击查看预约详情或取消预约。",
                    keyword1: date.trim(),
                    keyword2: begintime + "-" + endtime,
                    keyword3: content,
                    paperUrl: window.location.protocol + "//" + window.location.host + G.baseUri() + "/static/mp/aidea/process/showroom_evaluate.html?appid=" + p.params.appid
                };
                $("#next_step").css("pointer-events", "none");
                G.ajax('post', p.params.isAppointmentApi, formdata, function (retdata) {
                    if (retdata.errorNo == '1') {
                        $.modal({
                            title: "",
                            text: '展厅该时段已被预约，请重新选择预约时间段。The showroom has been booked for this period; please select a new time.',
                            buttons: [
                                {
                                    text: "确定OK", onClick: function () {
                                        $("#next_step").css("pointer-events", "inherit");
                                    }
                                }
                            ]
                        });
                    } else {
                        var isPerson = p.isPersons[p.typeNames.indexOf(type)];
                        if (isPerson == '0') {//需要讲解人
                            localStorage.setItem("form" + p.params.appid, JSON.stringify(formdata));
                            location.href = "./explainer.html?appid=" + p.params.appid;
                        } else {
                            G.ajax('post', p.params.submitApi, formdata, function (retdata) {
                                $("#next_step").css("pointer-events", "inherit");
                                if (retdata.errorNo == '0') {
                                    $.modal({
                                        title: "",
                                        text: '您已成功预约展厅。You have successfully booked the showroom!',
                                        buttons: [
                                            {
                                                text: "确定OK", onClick: function () {
                                                    WeixinJSBridge.call('closeWindow');
                                                }
                                            }
                                        ]
                                    });
                                } else if (retdata.errorNo == '1') {
                                    $.modal({
                                        title: "",
                                        text: '系统错误，请稍后重试System error',
                                        buttons: [
                                            {
                                                text: "确定OK", onClick: function () {
                                                    console.log(1)
                                                }
                                            }
                                        ]
                                    });
                                } else if (retdata.errorNo == '2') {
                                    $.modal({
                                        title: "",
                                        text: '展厅该时段已被预约，请重新选择预约时间段。The showroom has been booked for this period, please select a new time.',
                                        buttons: [
                                            {
                                                text: "确定OK", onClick: function () {
                                                    console.log(1)
                                                }
                                            }
                                        ]
                                    });
                                }
                            })
                        }
                    }
                })
            })
        }

        //查看详情时 加载数据
        var loadData = function () {
            var formdata = {
                id: p.params.id
            }
            //加载数据
            G.ajax('post', p.params.getData, formdata, function (retdata) {
                if (retdata.errorNo == '0') {
                    var data = retdata.data;
                    if (data.status == "0") {
                        $("#cancel_step").show();
                    } else {
                        $("#cancelOK_step").show();
                    }
                    $("input[name='name']").val(data.name);
                    $("input[name='email']").val(data.email);
                    $("input[name='dept']").val(data.dname);
                    $("input[name='date']").val(data.date);
                    var timeStr = data.timeStr;
                    $("input[name='begintime']").val(timeStr.split("-")[0]);
                    $("input[name='endtime']").val(timeStr.split("-")[1]);
                    $("textarea[name='content']").val(data.applyContent);
                    $("input[name='type']").val(data.vname);
                    $("input[name='num']").val(data.visitorNum);
                    if (data.description && data.description != null && data.description != '') {
                        $("input[name='remarks']").val(data.description);
                    } else {
                        $("input[name='remarks']").val("无");
                    }

                    if (data.ename && data.ename != null && data.ename != '') {
                        $("input[name='TechnicalExpert']").val(data.ename);
                    } else {
                        if (data.explainerStatus == '1') {
                            $("input[name='TechnicalExpert']").val("不需要");
                        } else if (data.explainerStatus == '2') {
                            $("input[name='TechnicalExpert']").val("品牌大使时间冲突，无法预约");
                        }
                    }


                    $("input,textarea").attr("readonly", "readonly");
                    p.createDate = dataUtils.dateFormat(new Date(data.createTime), "yyyy-MM-dd hh:mm");
                } else if (retdata.errorNo == '1') {
                    $.modal({
                        title: "",
                        text: '系统错误，请稍后重试System error',
                        buttons: [
                            {
                                text: "确定OK", onClick: function () {
                                    WeixinJSBridge.call('closeWindow');
                                }
                            }
                        ]
                    });
                }
            })
        }

        //取消预约
        var cancelData = function () {

            $("#cancel_step").click(function () {
                $.confirm("您确定要取消预约", function () {
                    var name = $("input[name='name']").val();
                    var nowDate = dataUtils.dateFormat(new Date(), "yyyy-MM-dd hh:mm");
                    var formdata = {
                        id: p.params.id,
                        accountsId: p.empInfo.accountsId,
                        keyword1: "展厅预约",
                        first: "尊敬的" + name + "，您已取消预约舍弗勒安亭展厅。 ",
                        remarks: "",
                        openid: p.empInfo.openId,
                        createDate: p.createDate,
                        nowDate: nowDate
                    }
                    $("#cancel_step").css("pointer-events", "none");
                    G.ajax('post', p.params.cancelData, formdata, function (retdata) {
                        $("#cancel_step").css("pointer-events", "inherit");
                        if (retdata.errorNo == '0') {
                            $.modal({
                                title: "",
                                text: "取消预约成功",
                                buttons: [
                                    {
                                        text: "确定OK", onClick: function () {
                                            $("#cancel_step").hide()
                                        }
                                    }
                                ]
                            });
                        } else if (retdata.errorNo == '1') {
                            alert("系统异常");
                        }
                    })
                }, function () {

                });

            })
        }
    };

    return Form;
})();
