var dealerList = (function () {
    'use strict';
    var DealerList = function (params) {
        var p = this;
        p.params = {
            appid: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            dataApi: G.baseUri() + '/mobile/auth/distributor/showDistributor',
            typename: G.baseUri() + '/mobile/auth/distributor/selectType',
            areaname: G.baseUri() + '/mobile/auth/distributor/selectArea',
            vt: ''
        };

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

        if (p.params.devMode) {
            p.params.dataApi = 'json/exhibi-detail.json';
        }

        p.english = cfApp.getQueryString('english') == 1 ? true : false;
        console.log(p.english);
        /**
         * 判断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()) {
                log();
                loadData();
                typeName();
                areaName();
                $('.language').click(function () {
                    if(!p.english){
                        location.href = 'exhibi-detail-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1'+'&sampleId='+cfApp.getQueryString('sampleId');
                    }else{
                        location.href = 'exhibi-detail.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id')+'&sampleId='+cfApp.getQueryString('sampleId');
                    }

                });
                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 typename = [];
        var typeid = [];
        var areaname = [];
        areaname.push("全部")
        var areaid = [];
        areaid.push("-1")

        var typeName = function(){
            var formdata = {};
            G.ajax(G.devModePost,p.params.typename,formdata,function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    for(var i = 0; i<data.length;i++){
                        typename.push(data[i].type_name);
                        typeid.push(data[i].id);
                    }

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

        $("#type").picker({
            title: "请选择经销商类别",
            cols: [
                {
                    textAlign: 'center',
                    values:typename
                }
            ],
            onClose:function(){
               // alert("a")
                $(".content").removeAttr('style')
                var type = $('#type').val();
                var index = typename.indexOf(type);
                var id = typeid[index];
                $('#typeId').val(id)
                $('.dealer-list').html("");
                loadData();

            }
        });

       $("#typeImg img").click(function(e){
           e.stopPropagation();
           $("#type").picker("open");
       })


        var areaName = function(){
            var formdata = {}
            G.ajax(G.demodePost,p.params.areaname,formdata,function(retdata){
                if(retdata.errorNo == 0){
                    var data = retdata.data;
                    for(var i = 0; i<data.length;i++){
                        areaname.push(data[i].area_name);
                        areaid.push(data[i].id);
                    }
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定"
                        }]
                    });
                }
            })
        }


        $("#address").picker({
            title: "请选择所在地区",
            cols: [
                {
                    textAlign: 'center',
                    values: areaname
                }
            ],
            onClose:function(){
                $(".content").removeAttr('style')
                var area = $('#address').val();
                var index = areaname.indexOf(area);
                var id = areaid[index];
                $('#areaId').val(id);
                $('.dealer-list').html("");
                loadData();
            }
        });

        $("#areaImg img").click(function(e){
            e.stopPropagation();
            $("#address").picker("open");
        })




        //更具经销商公司名称搜索
        $('input').keyup(function(event){
            if(event.keyCode ==13){
                $('.dealer-list').html("");
                loadData();
               // alert("a")
            }
        });

        //经销商页面初始化
        var loadData = function () {
            var typeid = $('#typeId').val();
            var areaid = $('#areaId').val();
            var formdata = {
                company:$('#compnay').val(),
                type_id:typeid,
                area_id:areaid
            };
            G.ajax(G.devModePost, p.params.dataApi, formdata, function (retdata) {

                if (retdata.errorNo == '0') {
                    var content = $('#template').html();
                    p.template = Handlebars.compile(content);
                    var htmlStr = p.template(retdata);
                    $('.dealer-list').append(htmlStr);

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

            });


        }

        //经销商详情页面
        $('body').on('click','.dealer-list li .top',function(){
          var node = $(this);
          var id = $(node).find('p').html();
          location.href = 'dealerDetail.html?appid=' + p.params.appid + '&id=' + id;
        })

        //点击感叹号图标
        $('body').on('click','.mark',function(){
            $.modal({
                title: "",
                text: '所列舍弗勒大中华区工业事业部授权经销商均由舍弗勒集团予以授权。<br/><br/>' +
                    '如您对所收到的舍弗勒工业授权经销商证书有任何疑问，敬请联系经销商业务单元 渠道管理部。邮箱：Sgc_distribution@schaeffler.com<br/><br/>'+
                '如您有任何轴承真伪鉴别问题，敬请联系舍弗勒大中华区知识产权部 邮箱：PiracyCN@schaeffler.com',
                buttons: [{
                    text: "确定"
                }]
            });
        })






    };

    return DealerList;
})();