regionbox.js 19.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
/**
 * @author zzf
 *
 * @tpl
 * <div class="m-region" url="{urlPath}" {custom-attr}="{attribute}"></div>
 *
 * @javascript
 * region.start();
 *
 * Parameter document
 * Here parameter only use on dom, we can call it as custom attribute, like
 * data-filter or data-something or isSomething and so on.
 *
 * Filter specific id when you don't want show its children data.
 * @param data-filter string {$1,$2$,$3,...,$n}
 *
 * Limit data show as data level or not.
 * @param isLimit number {0 or 1}
 * As data level you want limit level.
 * @param level number {0,1,2,3}
 *
 * Request url, it will return first city data.
 * @param url string {http://manweb.nong12.com/city/getCountryJsonpList.do, ...}
 */

var region = (function(){
    var regions = [],sorts = [];//对象管理池
    var param = {
        floor : 0 //只允许选择多少层
    };
    var _func = [];
    var _funcsure = function(){};

    var MultiLevel = function(){
        var _this = this;

        var config = {
            data : {},
            view : "",
            parameter : {
                url : "",
                setUrl : "",
                id : 0,
                field : {
                    pid : "parentId",
                    did : "regionId",
                    name : "regionName"
                },
                param : "parentId",
                setNmae : "city"
            },
            heads : [],
            sub : 0,
            constraintTier : 0,
            page : 0,
            isEvents : true,
            isinternation : 0,
            forcePage : 1
        };

        var methods = {
            foundView : function(verify, sub){
              var place = config.view.attr('data-place');
              var ensure = config.view.attr('isEnsure');
              place ? 0 : place = "请选择";
              var _v = verify;

                var view =  '<div class="title">'+
                            '<span><input type="text" readonly="readonly" '+ 
                            (!!_v ? 'class="required"' : "")+
                            'name='+ 'region'+sub +
                            ' placeholder="'+ place +'"/></span>'+
                            '<span class="s-live"></span>'+
                            '<p class="region-data" style="display: none;"></p></div>'+
                            '<div class="region-view">'+
                            '<div class="head"><ul></ul>'+
                            (!ensure ? '' : '<span class="ensure">确定</span>')+
                            '<span class="reset">重置</span></div>'+
                            '<div class="cont clearfix"><ul></ul></div></div>';
                config.view.html(view);
                this.parseParam();
                methods.events();
                
                return config.view;
            },
            parseParam : function(){
                var param = null;
                try{
                    param = config.view.attr("data");
                    //if(!param){methods.http();return false;}
                    param = param.split(",");
                    config.parameter.setNmae = param[0];//上传参数name
                    config.parameter.field.pid = param[1];//父节点id
                    config.parameter.field.did = param[2];//子节点id
                    config.parameter.field.name = param[3];//文字对应名称
                    config.parameter.param = param[4];//请求参数key
                    config.constraintTier = parseInt(param[5]);//操作显示page
                    config.forcePage =  param[6] ? parseInt(param[6]) : 1;
                }catch (error){
                    methods.error("朋友参数传递错误了,请仔细检查下", error);
                };
                if(config.view.attr("setUrl")){
                    config.parameter.setUrl = config.view.attr("setUrl");
                    methods.setValue();
                    return false;
                }
                methods.http();
            },
            setUrl : function(){
                if(config.view.attr("url")){
                    config.parameter.url = config.view.attr("url");
                }else{
                    methods.error("朋友参数url没有设置,请仔细检查下");
                };
                config.parameter.url = config.parameter.url+'?'+config.parameter.param+'='+config.parameter.id;
            },
            http : function(){
                if(param.floor && config.heads.length >=  param.floor){
                    methods.setData();
                    return false;
                };
                if(methods.getStorage(config.parameter.id)){
                    methods.setView(methods.getStorage(config.parameter.id));
                    return true;
                };
                if (config._filter) {
                  var id = config.parameter.id;
                  for (var i = 0, l = config._filter.length; i < l; i++) {
                    if (id > 0 && config._filter[i] == id) {
                      methods.setData();
                      config.view.find(".region-view").hide();
                      return true;
                    };
                  };
                };

                methods.setUrl();
                $.ajax({
                    type : 'GET',
                    url : config.parameter.url,
                    dataType : 'jsonp',
                    success : function(data){
                        methods.setStorage(data);
                    },
                    error : function(e, s, c){
                        methods.error("请求数据异常~~~", {"e":e, "s":s, "c":c});
                    }
                });
            },
            setStorage : function(data){
                data = methods.tidiesData(data);
                if(data && data.length > 0){
                    config.data[config.parameter.id] = data;
                    methods.setView(data);
                }else{
                    methods.setData();
                    config.view.find(".region-view").hide();
                };
            },
            tidiesData : function(data){
                var list = [];
                for(var i = 0, l = data.length; i < l; i++){
                    if(data[i][config.parameter.field.pid] == -9999){
                        data[i][config.parameter.field.pid] = 0;
                        list.push(data[i]);
                        config.isinternation = 1;
                    }else if(data[i][config.parameter.field.pid] == 0 && config.isinternation){
                        data[i][config.parameter.field.pid] = -10;
                        list.push(data[i]);
                    }else{
                        return data;
                    }
                };
                return list;
            },
            getStorage : function(id){
                if(config.data[id]){
                    return config.data[id];
                }else{
                    return false;
                }
            },
            setView : function(data){
                methods.setHead(data);
                methods.setCont(data);
            },
            setHead : function(data){
                config.view.find(".head ul").html('');
                var view = "";
                if (config.heads.length) {

                for(var i = 0, l = config.heads.length; i < l; i++){
                    view += '<li class="" zindex="'+config.page+'" did="'+config.heads[i].id+'" pid="'+config.heads[i].pid+'">'
                        +config.heads[i].name+'</li>';
                }

                };
                view += '<li class="act" zindex="'+config.page+'" pid="">请选择</li>';
                config.view.find(".head ul").html(view);
            },
            setCont : function(data){
                config.view.find(".cont ul").html('');
                var others = config.view.attr("hasOthers");
                var view = "";
                for(var i = 0, l = data.length; i < l; i++){
                  if (data[i]['regionName'] == '其他城市' || data[i]['regionName'] == '其他省份' || data[i]['regionName'] == '其他区县'){
                    continue;
                  }
                    view += '<li class="" zindex="'+ config.page +'"'
                          + 'pid="'+ data[i][config.parameter.field.pid] +'"'
                          + 'did="'+ data[i][config.parameter.field.did]+ '"'
                          + 'level="'+ (data[i]["level"] ? data[i]["level"] : 0) + '">'
                          + data[i][config.parameter.field.name] +'</li>'
                }
                config.view.find(".cont ul").html(view);
            },
            setData : function(data){
                var list = [];
                var id = 0;
                var str = "";
                if(data){
                    list = data;
                }else{
                    list = config.heads;
                };
                for(var i = 0, l = list.length; i < l; i++){
                    str += "  "+list[i].name;
                    if(parseInt(i) == (list.length - 1)){
                        id = list[i].id;
                    };
                }
                var isInput = config.view.prevAll(".region-hide");
                if(isInput.attr("type") && (isInput.attr("type") == "hidden" || isInput.attr("type") == "text")){
                    isInput.val(str+"/"+id);
                }else{
                    var view = '<input type="hidden" class="region-hide" name="'+config.parameter.setNmae+'" value="'+(str+"/"+id)+'" />';
                    config.view.before($(view));
                    isInput.val(str+"/"+id);
                }
                isInput.trigger("change");
                if(!config.forcePage){
                    $("body").trigger("click");
                }
                config.view.find(".title input").val(str);
                config.view.find(".region-data").html(JSON.stringify(config.heads));
                //config.view.find(".title div").html(str);
                var leng = config.heads.length - 1;

                // 隐藏错误提示
                var _name = isInput.attr( 'name' ) , _errorTips = config.view.parent().siblings( 'label[for="'+_name+'"]' );
                if( _errorTips.length > 0 ){
                    _errorTips.hide();
                }

            },
            headDel : function(id){
                var page = 0;
                for(var i = 0, l = config.heads.length; i < l; i++){
                    if(config.heads[i].pid == id){
                        page = parseInt(i);
                    }
                }
                config.heads.splice(page, (config.heads.length - page));
                methods.http();
            },
            headIsNmae : function(view){
                var text = view.html();
                var pid =  view.attr("pid");
                var did =  view.attr("did");
                for(var i = 0, l = config.heads.length; i < l; i++){
                    if(config.heads[i].pid == pid){
                        config.heads[i] = {
                            id : did,
                            name : text,
                            pid : pid
                        }
                        return false;
                    }
                }
                /*
                if(text != "其他区县" && text != "其他城市"){
                    return true;
                }
                */
                return true;
            },
            isConstraintTier : function(){
                var leng = config.heads.length - 1;
                if(config.constraintTier && leng >= config.constraintTier){
                    return true;
                }
                return false;
            },
            events : function(){
              var that = this;

                config.view.find(".head").on("click", 'li', function(){
                    config.parameter.id = $(this).attr("pid");
                    methods.headDel(config.parameter.id);
                });
                config.view.find(".cont").on("click", 'li', function(){
                  var _t = this;
                    config.parameter.id = $(this).attr("did");
                    if(methods.headIsNmae($(this))){
                        config.heads.push({id : $(this).attr("did"),
                            name : $(this).html(),
                            pid : $(this).attr("pid")
                        });
                    }

                    that.checkLimit($(this).attr("level"), function(){ 
                      methods.setData(); 
                      if (_func.length){
                        for ( var i = 0, l = _func.length; i < l; i++ ){
                          _func[i]['function'](_func[i]['target'])
                        }
                      };
                    });

                    if(methods.isConstraintTier()){
                        methods.setData();
                        if(config.forcePage)
                            methods.http();
                    }else{
                      if (config.view.attr('level')) {
                        if (config.view.attr('level') >= $(this).attr('level')) {
                          methods.http();
                        } else {
                          config.view.find('.region-view').hide();
                        };
                      } else {
                        methods.http();
                      };
                    }
                });
                config.view.find(".title").click(function () {
                    var rg = $("body").find(".m-region .region-view");
                    for ( var i=0,l=rg.length; i<l; i++ ){
                        if ( config.view.attr('sub') == rg.eq(i).attr('sub') ){
                            continue;
                        };
                        rg.eq(i).hide();
                    }
                    $(this).next().show();
                    return false;
                });
                config.view.find(".reset").click(function(){
                    _this.reset();
                    return false;
                });
                config.view.click(function(){
                    return false;
                });
                config.view.find(".ensure").on({
                  click: function(){
                    _funcsure(config.view);
                  }
                })
                $(document).click(function(e) {
                    if($(e.target).hasClass("m-region")){
                        return false;
                    }
                    config.view.find(".region-view").hide();
                });
            },
            error : function(txt, error){
               // alert(txt+", 详情请查看控制台log");
               // if(error){console.log(error)};
            },
            setValue : function(){
                $.ajax({
                    type : 'GET',
                    url : config.parameter.setUrl,
                    dataType : 'jsonp',
                    success : function(data){
                        try{
                            data = data.reverse();
                            var list = [];
                            for(var i = 0, l = data.length; i < l; i++){
                                list.push({
                                    id : data[i][config.parameter.field.did],
                                    name : data[i][config.parameter.field.name],
                                    pid : data[i][config.parameter.field.pid]
                                });
                            };
                            methods.setData(list);
                            config.parameter.id = 0;
                            config.heads = [];
                        }catch (error){};
                        methods.http();
                    },
                    error : function(error){
                        methods.error("请求数据异常~~~", error);
                    }
                });
            },
            checkLimit: function(limit, fns){
              limit >= config.view.attr("isLimit") ? fns(limit) : 0;
            },
            listenChange: function(fn){
              var cacheInput = $('<input type="hidden" class="region_cache_'+ config.view.attr("sub") +'" />');

              config.view.before(cacheInput);

              config.view.find(".cont").on("click", "li", function(){
                var _cityNames = [], _cityIds = [];

                $.each(config.heads, function(i, elem){
                  $.each(elem, function(k, v){
                    if (k == 'name'){
                      _cityNames.push(v)
                    }else if (k == 'id'){
                      _cityIds.push(v);
                    }
                  });
                });
                
                cacheInput.val(
                  _cityNames.join(',') + '/' + _cityIds.join(',')
                );
                typeof fn == 'function' ? fn() : 0;
              });
            },
            getFilterArray: function(string) {
              return !string ? [] : string.split(/[\,\_]/);
            }
        };

        this.start = function(view, sub, verify){
            config.sub = sub;
            config.view = $(view);
            config.view.attr("sub", sub);
            config._filter = methods.getFilterArray(config.view.attr('data-filter'));

            this.target = methods.foundView(verify, sub);
        };
        this.getData = function(){
            methods.getData();
        };
        this.update = function(){
            if(config.view.attr("setUrl")){
                config.parameter.setUrl = config.view.attr("setUrl");
                methods.setValue();
            }
        };
        this.reset = function(){
            config.heads = [];
            config.parameter.id = 0;
            methods.http();
            //config.view.find(".title div").html('');
            config.view.find(".title input").val('');
            config.view.find(".s-live").html('');
			      config.view.prev().attr('value','');
            config.view.find(".region-data").html('[]');
        };
        this.listenChange = function(){
          methods.listenChange();
        }

        return this;
    };

	return {
        start : function(verify){
            this.allregion(verify);
        },
        allregion : function(verify){
            $(".m-region").each(function(){
                if(!$(this).attr("sub")){
                    var ml = new MultiLevel();
                    regions.push(ml);
                    ml.start(this, (regions.length - 1), verify);
                };
            });
        },
        aRegion : function(view){
            var ml = new MultiLevel();
            regions.push(ml);
            ml.start(view, (regions.length - 1));
            return ml;
        },
        del : function(page){
            if(!page){return false};
            $(".m-region").each(function(i){
                if(i == page){
                    regions.splice(i, 1);
                    return true;
                };
            });
            return false;
        },
        setParam : function(obj){
            $.extend(param, obj);
        },
        run: function(subNums, fns){
          var len = subNums.length;
          try {
            for (var i = 0; i < len; i++){
              _func.push({
                'target': regions[subNums[i]].target,
                'function': fns[i]
              })
            };
          }catch(e){
            throw new Error(e.message + ", Maybe cause the param out of region length.");
          }
        },
        clicksure: function(fn){
          _funcsure = fn;
        }
    };
})();