var brandUpdate = (function () {
    'use strict';
    var BrandUpdate= function (params) {
        var p = this;
        p.params = {
            appid: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            dataApi:G.baseUri()+'/mobile/brandApply/getDetail',
            submitApi: G.baseUri() + '/mobile/brandApply/updateData',
            departmentApi:G.baseUri()+'/mobile/brandApply/departmentData',
            categoryApi:G.baseUri()+'/mobile/brandApply/categoryData',
            materialApi:G.baseUri()+'/mobile/brandApply/materialData',
            vt: '',
            depDatas:[],
            depNameDatas:[],
            categoryDatas:[],
            categoryNameDatas:[],
            materialDatas:[],
            materialNameDatas:[],
            departmentId:'',
            categoryId:'',
            isInit:true
        };

        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;
            p.id = cfApp.getQueryString('id');
            return validAppField();
        };

        /**
         * 初始化组件
         * @returns {boolean}
         */
        p.init = function () {

            if (initBaseFields()) {
                initForm();
                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 initForm=function () {
            G.ajax("GET",p.params.dataApi,{id:p.id,openId:p.empInfo.openId},function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    if(data.status!='1'){
                        return;
                    }
                    data.deliveryDateStr=dataUtils.dateFormat(new Date(data.deliveryDate), 'yyyy-MM-dd');
                    p.deliveryDate=data.deliveryDateStr;
                    if(data.isMaterialObject=='0'){
                        data.msg='请先勾选左侧需求项 please select a Service from below (see left side options)';
                        data.isMake=false;
                    }else{
                        data.isMake=true
                        data.msg='请勾选左侧需求项，如需制作请在右方输入数量。' +
                            'Click left to select a Service, then click right to select a quantity ';
                    }
                    data.costCenter0=data.costCenter.split('-')[0];
                    data.costCenter1=data.costCenter.split('-')[1];
                    p.params.departmentId=data.departmentId;
                    p.params.categoryId=data.categoryId;
                    var tpl = $("#form-cell").html();
                    //预编译模板
                    var template = Handlebars.compile(tpl);
                    //传入需要填充的数据匹配
                    var html = template(data);
                    //插入模板到ul中
                    $("#formData").html(html);
                    /**********end**********/
                    initDatePlugin()
                    depPicker()
                    submit();

                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
        }

        //提交相关问询
        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 = {
                    id:p.id,
                    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') {
                                    //注册成功
                                    $.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"
                                        }]
                                    });
                                }
                            })
                        }
                    }]
                });


            })
        }
        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('-');
                }
            });
            /*$('#delivery').datePicker({
                beginyear:2020,
                endyear:2030,
                theme: 'date',
            });*/
        }

        // 初始化选择框
        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())]
                            p.params.isInit=false;
                            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=[];
            if(!p.params.isInit){
                $("#materialDiv").html('') ;
                $('#category').val('');
                $("#category").prop("outerHTML", "<input class=\"weui-input f14\" readonly id=\"category\" name=\"category\" placeholder=\"请选择\"/> ");
            }

            if(!p.params.departmentId){
                return;
            }
            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;
                    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 = $('#formData').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 BrandUpdate;
})();
