var checkForm = (function () {
    'use strict';
    var CheckForm = function (params) {
        var p = this;
        p.params = {
            appid: '',
            id: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            localStorage: [],
            getDeptApi: G.baseUri() + '/mobile/auth/appform/getdept',
            getUseApi: G.baseUri() + '/mobile/auth/appform/getuse',
            getformApi: G.baseUri() + '/mobile/auth/appform/getTypeAppform',
            getapproverApi: G.baseUri() + '/mobile/auth/appform/getApprover',
            vt: ''
        };
        for (var param in params) {
            p.params[param] = params[param];
        }
        var cfApp = p.params.cfApp;

        if (p.params.devMode) {

        }
        p.pageSize = 10;
        p.pageNo = 0;
        p.channelData = [];
        p.deptNames = [];
        p.deptIds = [];
        p.useNames = [];
        p.useIds = [];
        p.approverNames = [];
        p.approverIds = [];
        p.typeformId = "";
        /**
         * 判断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');
                p.typeformId = cfApp.getQueryString('typeformId');
            }


            //如果获取不到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 != "") {
                    fillData();
                    log("促销品申请详情");
                    $(".mark").hide();
                } else {
                    modalText();
                    initDate();
                    loadData();
                    log("促销品申请");
                }
                Handlebars.registerHelper('multiplication', function (num, price) {
                    return (parseInt(num) * parseFloat(price)).toFixed(2);
                });
                return true;
            } else {
                return false;
            }
        };


        var cacheFullData = function(){
            var formDataStr = localStorage.getItem("common-order"+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.getformApi, formData, function (retdata) {
                    if (retdata.errorNo == '0') {
                        var data = retdata.data;
                        if(data && data!=null){
                            cacheFull(data);
                        }
                    }
                })
            }
        }

        var cacheFull = function(data){
            $("#name").val(data.name);
            $("#org").val(data.org);
            $("#costCenter1").val(data.costCenter.split("-")[0]);
            $("#costCenter2").val(data.costCenter.split("-")[1]);
            if(p.deptNames.indexOf(data.dname)>=0){
                $("#come_type").val(data.dname);
            }
            //初始化审批人
            initApprover($("#come_type").val(),data.aname);
            if(p.useNames.indexOf(data.uname)>=0){
                $("#use").val(data.uname);
            }
            $("#address").val(data.address);
            $("#remarks").text(data.remarks);

        }

        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 modalText = function () {
            $('body').on('click', '.mark', function () {
                $.modal({
                    title: "",
                    text: '若您有关于促销品品类的建议、申领流程疑问以及质量问题反馈，欢迎联系企业传播与市场部：<br/>' +
                        '电话：Chen Meiju OZ/SAM-C, 021 6065 5377；<br/>' +
                        '邮件：MarketingComGC@schaeffler.com。<br/>' +
                        '<br/>' +
                        'Should you have any comments or suggestions regarding item categories, application process or quality, please contact Mrs. Chen Meiju from Communications and Branding Schaeffler Greater China.<br/>' +
                        'Chen Meiju OZ/SAM-C<br/>' +
                        'Tel: 021-6065 5377<br/>' +
                        'Email: MarketingComGC@schaeffler.com' ,
                    buttons: [{
                        text: "确定"
                    }]
                });
                //$(".weui-dialog").prepend("<img src='../image/process/close.png' id='close' style='width: 30px;position: absolute;right: -10px;top:-10px;'>");
                $(".weui-dialog").addClass("tempTextdoc")
                $(".weui-dialog").show();
            })

            $("body").on('click', '#close', function () {
                $(".weui-dialog__ft a").click();
            })
            //$(".mark").click();
        }

        var fillData = function () {
            var formData = {
                id: p.params.id
            }
            G.ajax('post', p.params.getformApi, formData, function (retdata) {

                if (retdata.errorNo == '0') {
                    var status = retdata.data.status;
                    if (status == '0' || status == '3') {
                        retdata.data.statusName = "待审批Waiting for approval";
                    }else if(status == '2'){
                        retdata.data.statusName = "已被拒绝Has been rejected";
                    } else if (retdata.data.issuingState !='3') {
                        retdata.data.statusName = "待发放To be delivered";
                    } else if (retdata.data.issuingState =='3') {
                        retdata.data.statusName = "已发放Delivered";
                    } else {
                        retdata.data.statusName = "";
                    }
                    retdata.data.costCenter1 = retdata.data.costCenter.split("-")[0];
                    retdata.data.costCenter2 = retdata.data.costCenter.split("-")[1];
                    var content = $('#detail-template').html();
                    p.template = Handlebars.compile(content);
                    var htmlStr = p.template(retdata);
                    $('#content').html(htmlStr);
                    //显示申请清单
                    $(".goods-list").show();
                    //显示状态
                    $("#status").text(retdata.data.statusName);
                    //状态显示
                    $("#auditStatus").show();
                    //隐藏下一步
                    $("#next_step").hide();
                    $("#bg").hide();
                    //所有input变为只读状态
                    $("input,textarea").attr("readonly", true)
                }
            })
        }


        var initApprover = function (departmentId,defaultName) {
            $("#approver").prop("outerHTML", "<input type=\"text\" readonly class=\"fs12 mgb2  bg-transparent w-100 lh25\" placeholder=\"\" id=\"approver\"/>");
            var formApproverData = {
                departmentId: p.deptIds[p.deptNames.indexOf(departmentId)]
            }
            G.ajax('post', p.params.getapproverApi, formApproverData, function (retdata) {
                if (retdata.datas && retdata.datas != null && retdata.datas.length > 0) {
                    for (var i = 0; i < retdata.datas.length; i++) {
                        p.approverNames.push(retdata.datas[i].name);
                        p.approverIds.push(retdata.datas[i].id);
                    }
                    if(defaultName!=null && p.approverNames.indexOf(defaultName)>=0){
                        $("#approver").val(defaultName);
                    }
                    $("#approver").picker({
                        title: "",
                        cols: [
                            {
                                textAlign: 'center',
                                displayValues: p.approverNames,
                                values: p.approverNames
                            }
                        ],
                        onClose: function (data) {

                        }
                    });
                }
            })
        }


        var initDate = function () {
            var formData = {};
            G.ajax('post', p.params.getDeptApi, formData, function (retdata) {
                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);
                    }
                    $("#come_type").picker({
                        title: "",
                        cols: [
                            {
                                textAlign: 'center',
                                displayValues: p.deptNames,
                                values: p.deptNames
                            }
                        ],
                        onClose: function (data) {
                            p.approverNames = [];
                            p.approverIds = [];
                            var dept = $("#come_type").val();
                            initApprover(dept,null);
                        }
                    });
                }
                G.ajax('post', p.params.getUseApi, formData, function (retdata) {
                    if (retdata.datas && retdata.datas != null && retdata.datas.length > 0) {
                        for (var i = 0; i < retdata.datas.length; i++) {
                            p.useNames.push(retdata.datas[i].name);
                            p.useIds.push(retdata.datas[i].id);
                        }
                        //填充缓存数据，必须等到部门初始化完成后才可填充，不然审批人项无法填充。
                        // 审批人是根据部门来的
                        cacheFullData();
                        $("#use").picker({
                            title: "",
                            cols: [
                                {
                                    textAlign: 'center',
                                    displayValues: p.useNames,
                                    values: p.useNames
                                }
                            ],
                            onClose: function (data) {

                            }
                        });
                    }
                })
            })
            $(".clock").click(function () {
                $(this).siblings("input").click();
            })

        }

        var alert = function (data) {
            $.modal({
                title: "",
                text: data,
                buttons: [
                    {
                        text: "确定OK", onClick: function () {
                        console.log(1)
                    }
                    }
                ]
            });
        }
        var loadData = function () {
            $("#costCenter1").on("input", function () {
                var value = $("#costCenter1").val();
                if (value && value != null && value != '' && value.length == 4) {
                    $("#costCenter2").focus()
                }
            })
            $("#next_step").click(function () {
                var name = $("#name").val();
                if (StringValidateUtils.isEmpty(name)) {
                    alert("请输入您的姓名. Please input your name.");
                    return false;
                }
                var org = $("#org").val();
                if (StringValidateUtils.isEmpty(org)) {
                    alert("请输入您的ORG Code.  Please input your org code.");
                    return false;
                }
                var dept = $("#come_type").val();
                if (StringValidateUtils.isEmpty(dept)) {
                    alert("请选择所在部门. Please choose Division/Department.");
                    return false;
                }
                var costCenter1 = $("#costCenter1").val();
                var costCenter2 = $("#costCenter2").val();
                var costCenter = costCenter1 + "-" + costCenter2;
                if (StringValidateUtils.isEmpty(costCenter)) {
                    alert("请输入您的成本中心.Please input your cost center.");
                    return false;
                }
                var test = /^[A-Za-z0-9]{4,4}-[A-Za-z0-9]{4,4}$/;
                if (!test.test(costCenter)) {
                    alert("提示！成本中心共8位。Hint! Cost center should be 8 characters.");
                    return false;
                }
                var use = $("#use").val();
                if (StringValidateUtils.isEmpty(use)) {
                    alert("请选择促销品用途Please choose your promotional items intender for");
                    return false;
                }
                var approver = $("#approver").val();
                if (StringValidateUtils.isEmpty(approver)) {
                    alert("请选择审批人.Please choose your approver.");
                    return false;
                }
                var address = $("#address").val();
                if (StringValidateUtils.isEmpty(address)) {
                    alert("请输入收货地址. Please input delivery address.");
                    return false;
                }
                var remarks = $("#remarks").val();
                var use = $("#use").val();
                var formdata = {
                    "name": name,
                    "org": org,
                    "approver": p.approverIds[p.approverNames.indexOf(approver)],
                    "aname": approver,
                    "openid": p.empInfo.openId,
                    "department": p.deptIds[p.deptNames.indexOf(dept)],
                    "dname": dept,
                    "costCenter": costCenter,
                    "address": address,
                    "accountsId": p.empInfo.accountsId,
                    "typeform": p.typeformId,
                    "remarks": remarks,
                    "useId": p.useIds[p.useNames.indexOf(use)],
                    "uname": use
                }
                localStorage.setItem("common-order" + p.params.appid, JSON.stringify(formdata));
                if (!p.typeformId || p.typeformId == null || p.typeformId == '') {
                    $.modal({
                        title: "",
                        text: "参数错误",
                        buttons: [
                            {
                                text: "确定OK", onClick: function () {
                                return false;
                            }
                            }
                        ]
                    });
                } else {
                    location.href = "check_list.html?appid=" + p.params.appid + "&typeformId=" + p.typeformId + "&useId=" + formdata.useId;
                }

            })
        }


    };

    return CheckForm;
})();
