var brandDetail = (function () {
    'use strict';
    var BrandDetail = function (params) {
        var p = this;
        p.params = {
            appid: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            dataApi:G.baseUri()+'/mobile/brandApply/getDetail',
            confirmApi:G.baseUri()+'/mobile/brandApply/confirmData',
            vt: ''
        };

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

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


            if (initBaseFields()) {
                initForm();
                confirm();
                update();
                cancel();
                log();
                $('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();
                })
                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},function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    var detailPanelFlag=true;
                    if(data.status=='0'){
                        data.statusStr='待接单 Application in process';
                    }else if(data.status=='1'){
                        data.statusStr='待申请人确认 Waiting for your confirmation';
                        if(data.openId==p.empInfo.openId){
                            detailPanelFlag=true;
                            $("#tips").show();
                            $("#operate").show();
                        }
                    }else if(data.status=='2'){
                        data.statusStr='待审批  Approval in process';
                    }else if(data.status=='3'){
                        if(data.openId==p.empInfo.openId) {
                            data.statusStr = '审批通过 Application approved （联系人 Contact person:' + data.contactEmpName + ' ' + data.contactInformation + '）';
                        }else{
                            data.statusStr = '审批通过 Application approved';
                        }
                    }else if(data.status=='4'){
                        data.statusStr='已关闭  Application closed';
                    }else if(data.status=='5'){
                        data.statusStr='已完成 Service completed';
                    }else if(data.status=='6'){
                        data.statusStr='已取消 Application Cancelled';
                    }

                    data.estimateInternalCosts=data.estimateInternalCosts||'0';
                    data.estimateExternalCosts=data.estimateExternalCosts||'0';
                    data.quotedPrice=data.quotedPrice||"0";
                    data.deliveryDateStr=dataUtils.dateFormat(new Date(data.deliveryDate), 'yyyy-MM-dd');
                    data.intendedDeliveryDateStr=dataUtils.dateFormat(new Date(data.intendedDeliveryDate), 'yyyy-MM-dd');
                    if(data.isMaterialObject=='0'){
                        data.isMake=false;
                    }else{
                        data.isMake=true
                    }
                    data.costCenter0=data.costCenter.split('-')[0];
                    data.costCenter1=data.costCenter.split('-')[1]; /**模板编译**/
                    Handlebars.registerHelper('if_not_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(data);
                    //插入模板到ul中
                    $("#formData").html(html);
                    if(detailPanelFlag){
                        var $obj = $('.detail-panel')
                        var $contentBox = $obj.find('.fold-panel-content-box')
                        if ($obj.hasClass('folded')) {
                            $obj.removeClass('folded')
                            $contentBox.css('display','')
                        } else {
                            $obj.addClass('folded')
                            $contentBox.css('display','none')
                        }
                    }
                    /**********end**********/
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
        }
        //确认
        var confirm = function () {
            $('#confirm').click(function () {
                $.modal({
                    title: "",
                    text: '是否确认？<br />Are you sure about the amendment application?',
                    buttons: [{
                        text: "确定OK",onClick: function () {
                            $.showLoading("提交中...")
                            G.ajax("POST",p.params.confirmApi,{id:p.id,openId:p.empInfo.openId,status:'1'},function(retdata){
                                if(retdata.errorNo=='0'){
                                    $.modal({
                                        title: "",
                                        text: '<span class="color-green">成功</span></br>Success',
                                        buttons: [{
                                            text: "确定",onClick:function () {
                                                location.href=location.href;
                                            }
                                        }]
                                    });
                                }
                            })
                        }
                    }]
                });
            })
        }
        var update = function () {
            $('#update').click(function () {
                // 跳转到编辑页
                window.location.href = 'wx-brand-update.html?appid='+p.params.appid+'&id='+p.id
            })
        }
        var cancel = function () {
            $('#cancel').click(function () {
                $.prompt({
                    title: "",
                    input:'',
                    text: '请输入取消理由',
                    empty:false,
                    onOK: function (val) {
                        //点击确认
                        $.showLoading("提交中...")
                        G.ajax("POST",p.params.confirmApi,{id:p.id,openId:p.empInfo.openId,status:'0',closeReason:val},function(retdata){
                            if(retdata.errorNo=='0'){
                                $.modal({
                                    title: "",
                                    text: '<span class="color-green">成功</span></br>Success',
                                    buttons: [{
                                        text: "确定",onClick:function () {
                                            location.href=location.href;
                                        }
                                    }]
                                });
                            }
                        })
                    },
                });
            })
        }



    };

    return BrandDetail;
})();


/**表单组件调用方法**/
function onSwitch(that) {
    var arr = $('#form-wrap').find(".weui-count")
    if ($(that).is(':checked')) {
        $(that).val(true)
        if (arr && arr.length) {
            for (var i = 0; i < arr.length; i++) {
                $(arr[i]).css('display','')
            }
        }
    } else {
        $(that).val(false)
        if (arr && arr.length) {
            for (var i = 0; i < arr.length; i++) {
                $(arr[i]).css('display','none')
            }
        }
    }
}
function checked(that) {
    if ($(that).parent().hasClass('checked')) {
        $(that).parent().removeClass('checked')
        var $input = $(that).parent().find('.weui-count__number')
        $input.val(0)
    } else {
        $(that).parent().addClass('checked')
    }
}
function decrease(that) {
    var $input = $(that).parent().find('.weui-count__number')
    var number = parseInt($input.val() || "0") - 1
    if (number < 0) number = 0;
    $input.val(number)
}
function increase(that) {
    var $input = $(that).parent().find('.weui-count__number');
    var number = parseInt($input.val() || "0") + 1
    $input.val(number)
}

// 折叠面板
function foldPanel(that) {
    var $parent = $(that).parent()
    var $contentBox = $parent.find('.fold-panel-content-box')
    if ($parent.hasClass('folded')) {
        $parent.removeClass('folded')
        $contentBox.css('display','')
    } else {
        $parent.addClass('folded')
        $contentBox.css('display','none')
    }
}
/******end******/