var brandApplication = (function () {
    'use strict';
    var BrandApplication= function (params) {
        var p = this;
        p.params = {
            appid: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            submitApi: G.baseUri() + '/mobile/brandApply/submitData',
            departmentApi:G.baseUri()+'/mobile/brandApply/departmentData',
            categoryApi:G.baseUri()+'/mobile/brandApply/categoryData',
            materialApi:G.baseUri()+'/mobile/brandApply/materialData',
            latestDataApi:G.baseUri()+'/mobile/brandApply/getLatestData',
            vt: '',
            depDatas:[],
            depNameDatas:[],
            categoryDatas:[],
            categoryNameDatas:[],
            materialDatas:[],
            materialNameDatas:[],
            departmentId:'',
            categoryId:'',
        };

        for (var param in params) {
            p.params[param] = params[param];
        }
        var cfApp = p.params.cfApp;

        if (p.params.devMode) {

        }


        /**
         * 判断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.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 () {

            if (initBaseFields()) {
                initFormData();
                submit();
                log();
                return true;
            } else {
                return false;
            }
        };

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


            });
        }

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

        var initForm=function (data) {

            /**表单字段配置项**/
            var formOptions = [
                {
                    label: '您的姓名 Your name',
                    prop: 'name',
                    type: 'input',
                    placeholder:'Zhang Yuan, OZ/SAM-CC'
                },
                {
                    label: '您的邮箱 Your email',
                    prop: 'email',
                    type: 'input'
                },
                {
                    label: '本次需求的入账成本中心<br/>Cost center allocated for your order',
                    prop: 'cost',
                    type: 'input-input',
                    placeholder0:'1234',
                    placeholder1:'1234'
                },
                {
                    label: '所在部门 Division/Department',
                    prop: 'dept',
                    type: 'picker'
                },
                {
                    label: '您的直属领导姓名 Your line manager',
                    prop: 'line',
                    type: 'input'
                },
                {
                    label: '您的直属领导邮箱 Your line manager’s email',
                    prop: 'lineEmail',
                    type: 'input',
                    placeholder:'需求工单将抄送至您的直属领导'
                },

                {
                    label: '是否需要制作 Printing/production required',
                    prop: 'production',
                    type: 'switch',
                },
                {
                    label: '请选择您的需求类别 Please select a service category',
                    prop: 'category',
                    type: 'picker'
                },

                {
                    type:"materialDiv"
                },
                {
                    label: '您期望的交付日期 Expected delivery date',
                    prop: 'delivery',
                    type: 'date',
                },
                {
                    label: '请说明需求用途 Briefly explain the reason for use',
                    prop: 'explain',
                    type: 'textarea',
                    placeholder:'活动名称、产品宣传用途等 Activity name, description, usage of communication material etc.'
                }/*,
                {
                    label: '其他备注 Remarks',
                    prop: 'remarks',
                    type: 'textarea',
                    placeholder:''
                }*/
            ]

            /**模板编译**/
            Handlebars.registerHelper('if_eq', function(v1, v2, opts) {
                if (v1 === v2) {
                    return opts.fn(this)
                }
                return opts.inverse(this);
            });
            var tpl = $("#form-cell").html();
            //预编译模板
            var template = Handlebars.compile(tpl);
            //传入需要填充的数据匹配
            var html = template(formOptions);
            //插入模板到ul中
            $("#form-wrap").html(html);

            if(data!=null){
                p.params.departmentId=data.departmentId;
                $("#name").val(data.name);
                $("#cost0").val(data.costCenter.split('-')[0]);
                $("#cost1").val(data.costCenter.split('-')[1]);
                $("#email").val(data.email);
                $("#dept").val(data.departmentName);
                $("#line").val(data.lineManager);
                $("#lineEmail").val(data.lineManagerEmail);
            }
            /**********end**********/
            depPicker();
            initDatePlugin()
            //点击感叹号图标
            $('body').on('click','.mark',function(){
                $.modal({
                    title: "",
                    text: '关于公司平面设计/视频制作等品牌服务的申请，若您有疑问或建议，欢迎联系企业传播与市场部品牌组：<br/>' +
                        '姓名：Yu, Lan (Ada)  OZ/SAM-CB<br/>'+
                    '电话：<a href="tel: 021 3957 6234">021 3957 6234</a><br/>'+
                    '邮箱：lan.yu@schaeffler.com',
                    buttons: [{
                        text: "确定"
                    }]
                });
                $(".weui-dialog").addClass("tempTextdoc")
                $(".weui-dialog").show();
            })

            $("#cost0").on("input", function () {
                var value = $("#cost0").val();
                if (value && value != null && value != '' && value.length == 4) {
                    $("#cost1").focus()
                }
            })


        }
        //提交相关问询
        var submit = function () {
            $('#submit').click(function () {
                var name = $('#name').val();
                if (StringValidateUtils.isEmpty(name)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入您的姓名！</span><br>Your name.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var email = $('#email').val();
                if (StringValidateUtils.isEmpty(email)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入您的邮箱！</span><br>Your email.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var cost0 = $('#cost0').val();
                var cost1= $('#cost1').val();
                if (StringValidateUtils.isEmpty(cost0)||StringValidateUtils.isEmpty(cost1)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入本次需求的入账成本中心</span><br>Cost center allocated for your order.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var cost=cost0+"-"+cost1;
                if (StringValidateUtils.isEmpty(p.params.departmentId)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入所在部门 </span><br>Your department.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var lineManager = $('#line').val();
                if (StringValidateUtils.isEmpty(lineManager)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入您的直属领导姓名 </span><br>Your line manager’s name.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var lineManagerEmail = $('#lineEmail').val();
                if (StringValidateUtils.isEmpty(lineManagerEmail)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请输入您的直属领导邮箱！</span><br>Your line manager’s email.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var production = $('#production').val();
                if(production=='false'){
                    production=0;
                }else{
                    production=1;
                }

                if (StringValidateUtils.isEmpty(p.params.categoryId)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请选择您的需求类别！</span><br>Please select a service category.',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }

                var deliveryDate = p.deliveryDate;
                if (StringValidateUtils.isEmpty(deliveryDate)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请选择您的期望交付日期 </span><br>Please choose the<br>Expected delivery date',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var explain = $('#explain').val();
                if (StringValidateUtils.isEmpty(explain)) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请说明需求用途！</span><br>Please explain your purpose',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }
                var materialArr=$('.weui-count__number');
                var materialData=[];
                for(var i=0,j=materialArr.length;i<j;i++){
                    var $obj=$(materialArr[i]);
                    if($obj.data('status')){
                        var id=$obj.attr('id');
                        var val=$obj.val();
                        if(production=='0'){
                            val=0;
                        }
                        var dataObj={
                            materialId:id,
                            count:val
                        }
                        materialData.push(dataObj);
                    }
                }
                if (materialData.length==0) {
                    $.modal({
                        title: "",
                        text: '<span class="color-green">请完善您的需求！</span><br>Please improve your requirements',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                    return false;
                }

                var formJson = {
                    openId:p.empInfo.openId,
                    accountsId:p.empInfo.accountsId,
                    name:name,
                    email:email,
                    costCenter:cost,
                    departmentId:p.params.departmentId,
                    lineManager:lineManager,
                    lineManagerEmail:lineManagerEmail,
                    isMaterialObject:production,
                    categoryId:p.params.categoryId,
                    details:JSON.stringify(materialData),
                    requireSpecify:explain,
                    deliveryDate:deliveryDate,
                    remarks:$('#remarks').val()||''
                }
                console.log(formJson)
                $.modal({
                    title: "",
                    text: '<span class="color-green">是否确定要提交申请?</span><br>Are you sure you want to submit this application?<br>',
                    buttons: [{
                        text: "确定OK", onClick: function () {
                            $.showLoading("提交中...")
                            G.ajax("post", p.params.submitApi, formJson, function (retdata) {
                                $.hideLoading()
                                if (retdata.errorNo == '0') {
                                   localStorage.removeItem("brandApply-hisData"+p.params.appid);
                                    //注册成功
                                    $.modal({
                                        title: "",
                                        text: '<span class="color-green">成功</span></br>Success',
                                        buttons: [{
                                            text: "确定OK",
                                            onClick: function () {
                                                WeixinJSBridge.call('closeWindow');
                                            }
                                        }]
                                    });
                                } else {
                                    $.modal({
                                        title: "",
                                        text: '<span class="color-green">请修改申请内容！</span></br>System error',
                                        buttons: [{
                                            text: "确定OK"
                                        }]
                                    });
                                }
                            })
                        }
                    },{
                        text:'取消Cancel'
                    }]
                });


            })
        }
        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 initDatePlugin = function() {
            $("#delivery").datetimePicker({
                title: '选择交付日期',
                min:getNowFormatDate(),
                times: function () { return [] },
                onClose:function(data){
                    p.deliveryDate = data.value.join('-');
                }
            });
        }

        // 初始化选择框
        var depPicker = function() {
            G.ajax("GET",p.params.departmentApi,{},function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    for(var i = 0; i<data.length;i++){
                        p.params.depNameDatas.push(data[i].name  );
                        p.params.depDatas.push(data[i].id);
                    }
                    $('#dept').picker({
                        toolbarTemplate: `
            <div class="toolbar">
                <div class="toolbar-inner">
                    <a href="javascript:;" class="picker-button close-picker" style="color: #000;left: 0;right: auto;">取消</a>
                    <a href="javascript:;" class="picker-button close-picker">完成</a>
                </div>
             </div>`,
                        cols: [
                            {
                                textAlign: 'center',
                                values: p.params.depNameDatas
                            }
                        ],
                        onClose: function () {
                            p.params.departmentId=p.params.depDatas[p.params.depNameDatas.indexOf($("#dept").val())]
                            categoryPicker();
                            $("#maincontent").css({'padding-bottom': ""})
                        }
                    });
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
                categoryPicker()
        }

        var categoryPicker=function () {
            p.params.categoryNameDatas=[];
            p.params.categoryDatas=[];
            $("#materialDiv").html('') ;
            $('#category').val('');
            if(!p.params.departmentId){
                return;
            }
            $("#category").prop("outerHTML", "<input class=\"weui-input f14\" readonly id=\"category\" name=\"category\" placeholder=\"请选择\"/> ");
            G.ajax("GET",p.params.categoryApi,{departmentId:p.params.departmentId},function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    for(var i = 0; i<data.length;i++){
                        p.params.categoryNameDatas.push(data[i].name  );
                        p.params.categoryDatas.push(data[i].id);
                    }
                    $('#category').picker({
                        toolbarTemplate: `
            <div class="toolbar">
                <div class="toolbar-inner">
                    <a href="javascript:;" class="picker-button close-picker" style="color: #000;left: 0;right: auto;">取消</a>
                    <a href="javascript:;" class="picker-button close-picker">完成</a>
                </div>
             </div>`,
                        cols: [
                            {
                                textAlign: 'center',
                                values: p.params.categoryNameDatas
                            }
                        ],
                        onClose: function () {
                            p.params.categoryId=p.params.categoryDatas[p.params.categoryNameDatas.indexOf($("#category").val())];
                            materialPicker();
                            $("#maincontent").css({'padding-bottom': ""})
                        }
                    });
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
        }



        var materialPicker=function () {
            p.params.materialDatas=[];
            p.params.materialNameDatas=[];
            $("#materialDiv").html('') ;
            if(!p.params.categoryId){
                return;
            }
            G.ajax("GET",p.params.materialApi,{categoryId:p.params.categoryId},function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    var production = $('#production').val();
                    if(production=='false'){
                        data.msg='请先勾选左侧需求项 please select a Service from below (see left side options)';
                    }else{
                        data.msg='请勾选左侧需求项，如需制作请在右方输入数量。' +
                            'Click left to select a Service, then click right to select a quantity ';
                    }
                    var tpl = $("#material-cell").html();
                    //预编译模板
                    var template = Handlebars.compile(tpl);
                    //传入需要填充的数据匹配
                    var html = template(data);
                    //插入模板到ul中
                    $("#materialDiv").html(html);
                    handleMaterialDiv();
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
        }

        var handleMaterialDiv=function () {
            var arr = $('#form-wrap').find(".weui-count")
            if ($("#production").is(':checked')) {
                if (arr && arr.length) {
                    for (var i = 0; i < arr.length; i++) {
                        $(arr[i]).css('display','block')
                    }
                }
            } else {
                if (arr && arr.length) {
                    for (var i = 0; i < arr.length; i++) {
                        $(arr[i]).css('display','none')
                    }
                }
            }
        }
    };
    return BrandApplication;
})();
