cascading-address.js 14.2 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
/**
 * 区域城市级联选择
 * @author: dongjinhu(jinhu.dong@yoho.cn)
 * @date: 2016/06/30
 * @desc:
 *     1. 为了减少库的复杂度,应用层的地址接口应该统一并且固定
 * @examle:
 *     CascadingAddress({
 *         el: '#address',
 *         resources: 'areas',
 *         url: '',                       // 初始化数据请求
 *         onCreated: function () {}      // 初始化完成回调
 *     })
 */

var $ = require('yoho-jquery');

// 默认配置
var settings = {
    url: '/me/address/areas/0',
    containerClass: 'cascading-address',
    levels: 3,
    resources: 'areas',
    names: ['province', 'city', 'district'],
    indicators: ['请选择省份', '请选择城市', '请选择区/县'],
    defaultDes: '',
    ajaxSettings: {
        type: 'GET',
        url: '',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }
};

// 显示或隐藏下拉区域
function toggleDistItem() {
    var $this = $(this),
        resetHeight = $this.css('height'),
        openHeight = (parseInt(resetHeight.match(/\d*/)[0], 10) + 5) + 'px',
        openAndResetHeight = (parseInt(resetHeight.match(/\d*/)[0], 10) - 5) + 'px';

    if ($this.hasClass('closed')) {
        // 如果有其他开着,先关掉
        $('.items-indicator .open').each(function() {
            $(this).find('.iconfont').replaceWith('<span class="iconfont up">&#xe60a;</span>')
             .end()
             .removeClass('open')
             .addClass('closed')
             .css({
                 height: resetHeight
             }).next().hide();
        });

        // open
        $this.find('.iconfont').replaceWith('<span class="iconfont up">&#xe609;</span>')
             .end()
             .removeClass('closed')
             .addClass('open')
             .css({
                 height: openHeight
             })
             .next()
             .show();

        // 有视觉差
        // setTimeout(function(){
        //     $('.items-panel').slideDown('fast');
        // }, 300)
    } else {
        // close
        $this.find('.iconfont').replaceWith('<span class="iconfont up">&#xe60a;</span>')
             .end()
             .removeClass('open')
             .addClass('closed')
             .css({
                 height: openAndResetHeight
             }).next().hide();
    }
}

// 设置请求URL
function setRequestUrl(config, areaId) {
    var urlArr = config.url.split(config.resources + '/');

    urlArr[1] = areaId;
    return urlArr.join(config.resources + '/');
}

// 重置下一级文本显示和值
function resetNextLevel(level, config) {
    $('#level_' + level + '_panel').empty()
        .addClass('empty')
        .text(config.defaultDes)
        .prev().find('.indicator-name')
            .text(config.indicators[config.levels - level - 1])
            .next().val('');
}

// 选择特定省份,城市,或区县
function selectDistItem(options) {
    var level = options.level,                              // 当前级别
        distElement = options.target,                       // 选择特定项
        currAreaId = distElement.attr('id').split('_')[1],  // 当前选择areaId
        distItem = $('#level_' + level + '_panel').prev(),  // 请选择...
        currPanel = options.panel,                          // 当前区域列表项
        distItemAreaId = options.distItemAreaId,            // 当前选中areaId
        config = options.config;

    var nextDistItem;

    var from;

    if (distElement.hasClass('checked')) {
        // TODO
        // distElement.removeClass('checked');
    } else {
        currPanel.find('span.checked').removeClass('checked').prev().hide();
        distElement.addClass('checked').prev().show();
        distItem.find('.indicator-name')
                .html(distElement.text())
                .next()
                .val(currAreaId);

        // 填充下一级
        if (level < 0) {
            level = distElement.parents('.items-panel').attr('id').split('_')[1];
        }

        config.url = setRequestUrl(config, currAreaId);

        // 选择之后关闭当前panel
        distItem.trigger('click');

        // 展开下一级
        nextDistItem = distItem.parent().next().find('.dist-item');
        if (nextDistItem) {
            nextDistItem.trigger('click');
        }

        // console.log('current level:', level)
        // console.log('distItemAreaId:', distItemAreaId)
        // console.log('currAreaId:', currAreaId)
        // 当前点击的和已选择的不同,再渲染下一级目录
        if (level && distItemAreaId !== currAreaId) {
            from = level;
            while (from >= 1) {
                resetNextLevel(from - 1, config);
                from--;
            }

            $(config.el).trigger('ca.afterInit', [config, level - 1]);
        }
    }
}

// 获取初始化数据
function fetchInitialData(evt, config, level) {
    // var distItemAreaId = $('.items-indicator .open input').val(),
    var ajaxSettings = $.extend({}, config.ajaxSettings, {
        url: config.url
    });

    var ulElement = $('<ul/>'),
        liElement;

    // 当前选中区域列表
    var currPanel;

    $.ajax(ajaxSettings).done(function(res) {
        // 渲染后台区域信息列表
        $(res.data).each(function(index, item) {
            liElement = $('<li/>');

            $('<span class="check-icon iconfont">&#xe60b;</span>').appendTo(liElement);
            $('<span/>', {
                'class': 'dist-name', // eslint-disable-line
                title: item.text,
                text: item.text,
                id: 'area_' + item.value
            }).appendTo(liElement);

            liElement.appendTo(ulElement);
        });

        // 填充下拉
        if (level >= 0) {
            currPanel = $('#level_' + level + '_panel');
            ulElement.appendTo($(config.el).find('#level_' + level + '_panel').empty().removeClass('empty'));
        }

        // 选择区域
        currPanel.off('click', '.dist-name').on('click', '.dist-name', function() {
            selectDistItem({
                level: level,
                target: $(this),
                panel: currPanel,
                distItemAreaId: currPanel.prev().find('input').val(),
                config: config
            });
        });
    }).fail(function() {
        // 如果出错,将下级所有都重置
        var from = level;

        while (from >= 0) {
            resetNextLevel(from, config);
            from--;
        }
    });
}

// 设置地址: 省,市,区县
function renderDistrict(distIds, currentLevels, config) {
    // 标识需要渲染几级
    var distLen = distIds.sort().length,
        cursor = distLen, // 游标
        areaId,           // 请求areaId
        defaultId,        // 设置areaId
        $el = $(config.el);

    // 最后一个level是0
    while (distLen > 1) {
        // 请求从array[0], 判断值从array[1]
        areaId = distIds[cursor - distLen];
        defaultId = distIds[cursor - distLen + 1];
        config.url = setRequestUrl(config, areaId);
        $el.trigger('ca.setAddr', [config, currentLevels - 1, defaultId]);
        distLen--;
        currentLevels--;
    }
}

// 设置地址
function setAddress(evt, config, level, areaId) {
    var ajaxSettings = $.extend({}, config.ajaxSettings, {
            url: config.url
        }),
        liElement,
        ulElement = $('<ul/>'),
        currPanel,
        label,
        distVal,
        distItemAreaId = $('.items-indicator .open input').val();


    $.ajax(ajaxSettings).done(function(res) {
        $(res.data).each(function(index, item) {
            liElement = $('<li/>');

            // 设置目标区域check状态
            if (item.value === areaId) {
                label = item.text;
                distVal = item.value;

                $('<span class="check-icon iconfont" style="display: inline;">&#xe60b;</span>').appendTo(liElement);
                $('<span/>', {
                    'class': 'dist-name checked', // eslint-disable-line
                    title: label,
                    text: label,
                    id: 'area_' + item.value
                }).appendTo(liElement);
            } else {
                $('<span class="check-icon iconfont">&#xe60b;</span>').appendTo(liElement);
                $('<span/>', {
                    'class': 'dist-name', // eslint-disable-line
                    title: item.text,
                    text: item.text,
                    id: 'area_' + item.value
                }).appendTo(liElement);
            }

            liElement.appendTo(ulElement);

            ulElement.appendTo($(config.el).find('#level_' + level + '_panel').empty().removeClass('empty'));
        });

        // 设置label文本 和 设置areaId
        currPanel = $('#level_' + level + '_panel');
        currPanel.prev().find('.indicator-name').text(label)
                                               .next().val(distVal);

        // 侦听选择
        currPanel.off('click', '.dist-name').on('click', '.dist-name', function() {
            selectDistItem({
                level: level,
                target: $(this),
                panel: currPanel,
                distItemAreaId: distItemAreaId,
                config: config
            });
        });

    }).fail(function() {
        // 如果出错,将下级所有都重置
        var from = level;

        while (from >= 0) {
            resetNextLevel(from, config);
            from--;
        }
    });
}

// 构造器
function CascadingAddress(options) {
    var widget = this,
        element;

    widget.config = $.extend(true, {}, settings, options); // Object.assign({}, settings, options);
    element = widget.element = $(widget.config.el);

    element.on('ca.afterInit', fetchInitialData);
    element.on('click', '.dist-item', toggleDistItem);
    element.on('ca.setAddr', setAddress);

    // 绑定自定义事件处理
    $.each(widget.config, function(key, value) {
        if ($.isFunction(value)) {
            element.on('ca.' + key, function(evt, params) {
                // 处理自定义事件
                return value(evt, element, params);
            });
        }
    });

    // 初始化
    this.init();
}

// 初始化
CascadingAddress.prototype.init = function() {
    // 配置
    var config = this.config,
        el = this.element,
        target = el.addClass(config.containerClass),
        levels = config.levels;

    // DOM相关
    var names = config.names,
        indicators = config.indicators,
        distItem,
        inputName,
        indicatorName;

    // 省份,城市,区县容器
    var distItemContainer = $('<ul class="items-indicator"/>'),
        liElement,
        distPanel;

    // ======生成DOM结构======
    while (levels--) {
        indicatorName = indicators[config.levels - levels - 1];

        // li element
        liElement = $('<li/>');

        // div element
        distItem = $('<div></div>', {
            'class': 'dist-item closed' // eslint-disable-line
        });

        // 标签
        $('<span/>', {
            'class': 'indicator-name', // eslint-disable-line
            text: indicatorName
        }).appendTo(distItem);

        // input element
        inputName = names[config.levels - levels - 1];
        $('<input/>', {
            type: 'hidden',
            name: inputName,
            id: inputName,
            value: ''
        }).appendTo(distItem);

        // icon element
        $('<span class="iconfont">&#xe60a;</span>').appendTo(distItem);

        distItem.appendTo(liElement);

        // 省份城市区县选择panel
        distPanel = $('<div/>', {
            'class': 'items-panel empty', // eslint-disable-line
            id: 'level_' + levels + '_panel',
            text: config.defaultDes
        });
        distPanel.appendTo(liElement);

        liElement.appendTo(distItemContainer);
    }

    distItemContainer.appendTo(target);

    // ======生成DOM结构======

    // 获取初始化数据
    el.trigger('ca.afterInit', [config, config.levels - 1]);

    // 初始化完成,提供回调执行
    el.trigger('ca.onCreated');
};

// 获取地址文本
CascadingAddress.prototype.getAreaLabels = function() {
    var el = $(this.config.el),
        result = [];

    el.find('.indicator-name').each(function() {
        if ($(this).next().val() !== '') {
            result.push($(this).text());
        }
    });

    return result.join(',');
};

// 判断是否选择了完整的区域
CascadingAddress.prototype.hasFullAera = function() {
    return this.getAreaLabels().split(',').length === 3;
};

// 获取地址ID
CascadingAddress.prototype.getAreaIds = function() {
    var el = $(this.config.el),
        result = [],
        target;

    el.find('input').each(function() {
        target = $(this);
        if (target.val() !== '') {
            result.push($(this).val());
        }
    });

    if (result.length) {
        return result.join(',');
    } else {
        return '';
    }
};

// 设置区域
// {
//     "province": "32",
//     "city": "3201",
//     "dist": "320102"
// }
CascadingAddress.prototype.setAddress = function(targetAddr) {
    var key,
        distIds = ['0'],  // 省份请求areaId=0
        currentLevels = $('.items-indicator>li').length,  // 目前存在几级
        config = this.config;

    if (typeof targetAddr === 'object') {
        for (key in targetAddr) {
            if (targetAddr.hasOwnProperty(key)) {
                distIds.push(targetAddr[key]);
            }
        }
        renderDistrict(distIds, currentLevels, config);
    } else if (typeof targetAddr === 'string' && targetAddr.length === 6) {
        distIds = [0, targetAddr.substr(0, 2), targetAddr.substr(0, 4), targetAddr.substr(0, 6)];
        renderDistrict(distIds, currentLevels, config);
    } else {
        console.error('target address must be a json object or areaId string');
    }
};

// 重置地址
CascadingAddress.prototype.reset = function() {
    var items = $(this.config.el).find('.items-indicator'),
        labels = this.config.indicators;

    items.each(function(index, item) {
        $(item).find('span.indicator-name').text(labels[index])
               .next().val('')
               .parent().next()
               .find('span.checked').removeClass('checked').prev().hide();
    });
};

module.exports = function(options) {
    return new CascadingAddress(options);
};