"use strict";

exports.__esModule = true;
exports["default"] = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _react = _interopRequireWildcard(require("react"));

var _reactDom = require("react-dom");

var _instance = _interopRequireDefault(require("../Context/instance.js"));

var _china = _interopRequireDefault(require("./china.js"));

var _excluded = ["portal", "countries", "getCountries", "data", "dataFormat", "getData", "firstStageCitys", "split", "type", "isLeaf", "show", "value", "selected", "maskAttribute", "submitAttribute", "cancelAttribute", "getStreets"],
    _excluded2 = ["show", "caption", "onClick"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

// 数据
var initTabs = []; // 根据key或者name获取tabs, property用于区分是key还是value比较
// 选中项[{id: '', name: ''}]

var currentSelected = null; // 国家

var currentCountries = null; // 省市区

var currentData = null; // 街道临时存储

var currentStreets = [];
var PickerDistrict = (0, _react.forwardRef)(function (_ref, ref) {
  var portal = _ref.portal,
      countries = _ref.countries,
      getCountries = _ref.getCountries,
      _ref$data = _ref.data,
      data = _ref$data === void 0 ? _china["default"] : _ref$data,
      dataFormat = _ref.dataFormat,
      getData = _ref.getData,
      _ref$firstStageCitys = _ref.firstStageCitys,
      firstStageCitys = _ref$firstStageCitys === void 0 ? ['北京', '天津', '上海', '重庆'] : _ref$firstStageCitys,
      _ref$split = _ref.split,
      split = _ref$split === void 0 ? '-' : _ref$split,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? '' : _ref$type,
      isLeaf = _ref.isLeaf,
      show = _ref.show,
      value = _ref.value,
      selected = _ref.selected,
      _ref$maskAttribute = _ref.maskAttribute,
      maskAttribute = _ref$maskAttribute === void 0 ? {} : _ref$maskAttribute,
      _ref$submitAttribute = _ref.submitAttribute,
      submitAttribute = _ref$submitAttribute === void 0 ? {} : _ref$submitAttribute,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === void 0 ? {} : _ref$cancelAttribute,
      getStreets = _ref.getStreets,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  // 声明ref
  var refElBody = (0, _react.useRef)(null); // context

  var context = (0, _react.useContext)(_instance["default"]) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  }; // 页签和列表


  var _useState = (0, _react.useState)([]),
      tabs = _useState[0],
      setTabs = _useState[1];

  var _useState2 = (0, _react.useState)(0),
      tabIndex = _useState2[0],
      setTabIndex = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      list = _useState3[0],
      setList = _useState3[1];

  var _useState4 = (0, _react.useState)(''),
      errMsg = _useState4[0],
      setErrMsg = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      loading = _useState5[0],
      setLoading = _useState5[1]; // 显示时清除错误提示


  (0, _react.useEffect)(function () {
    if (show) {
      setErrMsg('');
    }
  }, [show]); // eslint-disable-line
  // 是否是末级节点: 支持类型country, province, city, district(其中province, city, district只有中国时才生效)

  function isTypeLeaf() {
    // 判断点击的是否是底层
    if (type === 'country') {
      if (tabIndex === 0) return true;
    } // 判断有国家的情况下, 一级选中国家是否是中国


    var isChina = tabs[0] && tabs[0].id === '86'; // 没有国家且为中国行政区划时才生效, 因为只有中国有省市区

    if (!currentCountries || !currentCountries.length || isChina) {
      if (type === 'province') {
        if (tabIndex === (isChina ? 1 : 0)) return true;
      } else if (type === 'city') {
        if (tabIndex === (isChina ? 2 : 1)) return true; // 直辖市特别市没有省, 为0级节点

        if (tabs && tabs[isChina ? 1 : 0] && firstStageCitys.indexOf(tabs[isChina ? 1 : 0].name.replace('市', '')) !== -1) {
          return true;
        }
      } else if (type === 'district') {
        if (tabIndex === (isChina ? 3 : 2)) return true; // 直辖市特别市没有省, 它们的区为1级节点

        if (tabs && tabs[isChina ? 1 : 0] && tabIndex === (isChina ? 2 : 1) && firstStageCitys.indexOf(tabs[isChina ? 1 : 0].name) !== -1) {
          return true;
        }
      }
    }

    return false;
  } // 获取省市区父节点下所有的子节点


  function getParentChildren(parentid) {
    if (!parentid || parentid === '-1') {
      return currentData;
    }

    if (currentData && currentData.length) {
      var parent = currentData.getDeepTreeNode(parentid);
      var children = []; // 如果没有查到此项, 有可能是数组的根元素

      if (!parent || Object.isEmptyObject(parent)) {
        for (var _iterator = _createForOfIteratorHelperLoose(currentData), _step; !(_step = _iterator()).done;) {
          var root = _step.value;

          if (root.parentid === parentid) {
            children.push(root);
          }
        }
      } else {
        children = parent.children;
      }

      return children;
    }

    setErrMsg(locale('暂无数据', 'no_data'));
    return [];
  } // 数据初始化


  (0, _react.useEffect)(function () {
    if (show) {
      loadCurrentData();
    }
  }, [show]); // eslint-disable-line
  // 第一步: 获取国家和省市区

  function loadCurrentData() {
    return _loadCurrentData.apply(this, arguments);
  } // 第二步: 获取选中数据


  function _loadCurrentData() {
    _loadCurrentData = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var countriesSuccess;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(countries || typeof getCountries === 'function')) {
                _context.next = 6;
                break;
              }

              _context.next = 3;
              return loadCountries();

            case 3:
              countriesSuccess = _context.sent;

              if (countriesSuccess) {
                _context.next = 6;
                break;
              }

              return _context.abrupt("return");

            case 6:
              _context.next = 8;
              return loadData();

            case 8:
              // 没有国家, 没有省市区则显示暂无数据
              if ((!Array.isArray(currentCountries) || !currentCountries.length) && (!Array.isArray(currentData) || !currentData.length)) {
                setErrMsg(locale('暂无数据', 'no_data'));
              } // 初始化选中项


              _context.next = 11;
              return loadSelected();

            case 11:
              // 初始化tabbar
              initTabBar(); // 渲染页面

              if (Array.isArray(currentCountries) && currentCountries.length || currentData && currentData.length) {
                initTabList();
              }

            case 13:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _loadCurrentData.apply(this, arguments);
  }

  function loadSelected() {
    return _loadSelected.apply(this, arguments);
  } // 第三步: 初始化tabs


  function _loadSelected() {
    _loadSelected = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              return _context3.abrupt("return", new Promise( /*#__PURE__*/function () {
                var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee2(resolve) {
                  var _iterator4, _step4, item, values, country, districtOption, streetName, _iterator5, _step5, street;

                  return _regenerator["default"].wrap(function _callee2$(_context2) {
                    while (1) {
                      switch (_context2.prev = _context2.next) {
                        case 0:
                          if (!(selected && selected.length)) {
                            _context2.next = 13;
                            break;
                          }

                          _iterator4 = _createForOfIteratorHelperLoose(selected);

                        case 2:
                          if ((_step4 = _iterator4()).done) {
                            _context2.next = 10;
                            break;
                          }

                          item = _step4.value;

                          if (!(!item.id || !item.name)) {
                            _context2.next = 8;
                            break;
                          }

                          currentSelected = null;
                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 8:
                          _context2.next = 2;
                          break;

                        case 10:
                          currentSelected = selected;
                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 13:
                          // 没有选中数据从value中取
                          values = [];

                          if (typeof value === 'string' && value.split(split)) {
                            values = value.split(split);
                          }

                          if (!(!values || !values.length)) {
                            _context2.next = 19;
                            break;
                          }

                          currentSelected = null;
                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 19:
                          currentSelected = null; // 如果有国家

                          // 如果有国家
                          if (Array.isArray(currentCountries) && currentCountries.length) {
                            country = getCountryByName(values.shift());
                            if (country) currentSelected = [country];
                          } // 没有城市数据返回直接返回


                          if (!(!currentData || !currentData.length)) {
                            _context2.next = 24;
                            break;
                          }

                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 24:
                          // 根据values取出选中数据
                          currentSelected = (currentSelected || []).concat(currentData.getDeepTreeNodesByNames(values)); // 如果有街道时长度会不一致, 则需要查询街道

                          if (!(currentSelected && currentSelected.length && currentSelected.length === (currentCountries && currentCountries.length ? values.length : values.length - 1))) {
                            _context2.next = 41;
                            break;
                          }

                          districtOption = currentSelected[currentSelected.length - 1]; // 获取区数据

                          // 获取区数据
                          streetName = values[values.length - 1]; // 获取街道名

                          _context2.next = 30;
                          return loadStreets(districtOption.id);

                        case 30:
                          if (!(!Array.isArray(currentStreets) || !currentStreets || !currentStreets.length)) {
                            _context2.next = 33;
                            break;
                          }

                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 33:
                          _iterator5 = _createForOfIteratorHelperLoose(currentStreets);

                        case 34:
                          if ((_step5 = _iterator5()).done) {
                            _context2.next = 41;
                            break;
                          }

                          street = _step5.value;

                          if (!(street.name === streetName)) {
                            _context2.next = 39;
                            break;
                          }

                          currentSelected.push(street);
                          return _context2.abrupt("break", 41);

                        case 39:
                          _context2.next = 34;
                          break;

                        case 41:
                          resolve(currentSelected);
                          return _context2.abrupt("return", currentSelected);

                        case 43:
                        case "end":
                          return _context2.stop();
                      }
                    }
                  }, _callee2);
                }));

                return function (_x5) {
                  return _ref2.apply(this, arguments);
                };
              }()));

            case 1:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _loadSelected.apply(this, arguments);
  }

  function initTabBar() {
    initTabs = [];

    if (currentSelected && currentSelected.length) {
      initTabs = Object.clone(currentSelected);
    } // 自定义判断当前节点是否是末级节点


    if (typeof isLeaf === 'function' && isLeaf(initTabs)) {
      setTabs(initTabs);
      setTabIndex(initTabs.length - 1);
      return;
    } // tabs末级节点没有选中项则中文变成请选择


    if (initTabs && initTabs.length) {
      if (!initTabs[initTabs.length - 1].name) {
        initTabs[initTabs.length - 1].name = '请选择';
      }
    } // 没有tabs, 默认第一项为请选择
    else {
        initTabs[0] = {
          parentid: '',
          id: '',
          name: '请选择'
        };
      } // 选中国家与选中省市区有些区别, 选中国家需要直接显示省份, 所以要默认增加一项


    console.log(currentSelected);

    if (initTabs.length === 1 && type !== 'country' && initTabs[0].id && currentCountries && currentCountries.length && Array.isArray(currentData) && currentData.length) {
      initTabs.push({
        parentid: '',
        id: '',
        name: '请选择'
      });
    }

    setTabs(initTabs);
    setTabIndex(initTabs.length - 1);
  } // 第四步: 结合选中数据, 初始化列表


  function initTabList() {
    return _initTabList.apply(this, arguments);
  } // 工具方法: 获取国家, 失败返回false, 成功返回true


  function _initTabList() {
    _initTabList = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
      var initList;
      return _regenerator["default"].wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              initList = []; // 选中国家与选中省市区有些区别, 选中国家需要直接显示省份

              if (!(initTabs.length <= 2 && currentCountries && currentCountries.length)) {
                _context4.next = 11;
                break;
              }

              if (!(initTabs.length === 2)) {
                _context4.next = 8;
                break;
              }

              _context4.next = 5;
              return loadData(initTabs[initTabs.length - 2].id);

            case 5:
              if (currentData) initList = currentData;
              _context4.next = 9;
              break;

            case 8:
              if (initTabs.length === 1) {
                // 没有选中国家, 显示国家列表
                initList = currentCountries;
              }

            case 9:
              _context4.next = 16;
              break;

            case 11:
              // 选中省市区街道, 则显示当前选中的层级列表
              initList = getParentChildren(initTabs[initTabs.length - 1].parentid || '');

              if (!(!initList && initTabs[initTabs.length - 2].id)) {
                _context4.next = 16;
                break;
              }

              _context4.next = 15;
              return loadStreets(initTabs[initTabs.length - 2].id);

            case 15:
              if (currentStreets && currentStreets.length) initList = currentStreets;

            case 16:
              setList(initList);

            case 17:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));
    return _initTabList.apply(this, arguments);
  }

  function formatCountries(list) {
    return (list || []).map(function (item) {
      item.isCountry = true;
      return item;
    });
  }

  function getCountryByName(countryName) {
    for (var _iterator2 = _createForOfIteratorHelperLoose(currentCountries), _step2; !(_step2 = _iterator2()).done;) {
      var item = _step2.value;

      if (item.name.indexOf(countryName) !== -1 || countryName.indexOf(item.name) !== -1) {
        return item;
      }
    }

    return null;
  }

  function loadCountries() {
    return _loadCountries.apply(this, arguments);
  } // 工具方法: 获取省市区


  function _loadCountries() {
    _loadCountries = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
      return _regenerator["default"].wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              return _context6.abrupt("return", new Promise( /*#__PURE__*/function () {
                var _ref3 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee5(resolve) {
                  return _regenerator["default"].wrap(function _callee5$(_context5) {
                    while (1) {
                      switch (_context5.prev = _context5.next) {
                        case 0:
                          if (!(Array.isArray(countries) && countries.length)) {
                            _context5.next = 9;
                            break;
                          }

                          if (!(countries[0].id && countries[0].name)) {
                            _context5.next = 5;
                            break;
                          }

                          currentCountries = formatCountries(countries);
                          resolve(currentCountries);
                          return _context5.abrupt("return", currentCountries);

                        case 5:
                          currentCountries = null;
                          resolve(currentCountries);
                          setErrMsg("countries" + locale('参数不正确', 'wrong_parameter'));
                          return _context5.abrupt("return", currentCountries);

                        case 9:
                          if (getCountries) {
                            _context5.next = 13;
                            break;
                          }

                          currentCountries = null;
                          resolve(currentCountries);
                          return _context5.abrupt("return", currentCountries);

                        case 13:
                          // 有获取国家的方法时, 加载国家数据
                          setLoading(true);
                          _context5.prev = 14;
                          _context5.next = 17;
                          return getCountries();

                        case 17:
                          currentCountries = _context5.sent;
                          _context5.next = 27;
                          break;

                        case 20:
                          _context5.prev = 20;
                          _context5.t0 = _context5["catch"](14);
                          setErrMsg(locale('获取数据失败', 'hint_getdata_failed'));
                          setLoading(false);
                          currentCountries = null;
                          resolve(currentCountries);
                          return _context5.abrupt("return");

                        case 27:
                          setLoading(false); // 返回字符串, 说明有错

                          if (!(typeof currentCountries === 'string')) {
                            _context5.next = 33;
                            break;
                          }

                          setErrMsg(currentCountries);
                          currentCountries = null;
                          resolve(currentCountries);
                          return _context5.abrupt("return");

                        case 33:
                          if (!(!currentCountries || currentCountries instanceof Array === false)) {
                            _context5.next = 37;
                            break;
                          }

                          currentCountries = null;
                          resolve(currentCountries);
                          return _context5.abrupt("return");

                        case 37:
                          resolve(formatCountries(currentCountries));

                        case 38:
                        case "end":
                          return _context5.stop();
                      }
                    }
                  }, _callee5, null, [[14, 20]]);
                }));

                return function (_x6) {
                  return _ref3.apply(this, arguments);
                };
              }()));

            case 1:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }));
    return _loadCountries.apply(this, arguments);
  }

  function loadData(_x) {
    return _loadData.apply(this, arguments);
  } // 工具方法: 获取街道, 失败返回false, 成功返回true


  function _loadData() {
    _loadData = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee8(id) {
      return _regenerator["default"].wrap(function _callee8$(_context8) {
        while (1) {
          switch (_context8.prev = _context8.next) {
            case 0:
              return _context8.abrupt("return", new Promise( /*#__PURE__*/function () {
                var _ref4 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee7(resolve) {
                  var countryName, country, newData, dataStr;
                  return _regenerator["default"].wrap(function _callee7$(_context7) {
                    while (1) {
                      switch (_context7.prev = _context7.next) {
                        case 0:
                          if (!(Array.isArray(currentCountries) && currentCountries.length)) {
                            _context7.next = 6;
                            break;
                          }

                          // 构建选中的国家id
                          if (!id) {
                            if (Array.isArray(selected) && selected.length) {
                              id = selected[0].id;
                            } else if (value) {
                              countryName = value.split(split)[0];
                              country = getCountryByName(countryName);
                              if (country && country.id) id = country.id;
                            }
                          } // 没有选中的国家


                          if (id) {
                            _context7.next = 6;
                            break;
                          }

                          currentData = null;
                          resolve(currentData);
                          return _context7.abrupt("return", currentData);

                        case 6:
                          // 获取省市区
                          newData = null;

                          if (!(typeof getData === 'function')) {
                            _context7.next = 17;
                            break;
                          }

                          setLoading(true);
                          _context7.next = 11;
                          return getData(id);

                        case 11:
                          newData = _context7.sent;

                          if (typeof newData === 'string') {
                            setErrMsg(newData);
                          }

                          if (!newData) {
                            setErrMsg(locale('获取数据失败', 'hint_getdata_failed'));
                          }

                          setLoading(false);
                          _context7.next = 18;
                          break;

                        case 17:
                          if (Array.isArray(data)) {
                            newData = data;
                          }

                        case 18:
                          // 格式化数据
                          if (newData && newData.length && dataFormat && (dataFormat.parentPropertyName || dataFormat.namePropertyName || dataFormat.idPropertyName || dataFormat.childPropertyName)) {
                            try {
                              dataStr = JSON.stringify(newData);

                              if (dataFormat.parentPropertyName) {
                                dataStr = dataStr.replace(new RegExp(dataFormat.parentPropertyName, 'igm'), 'parentid');
                              }

                              if (dataFormat.namePropertyName) {
                                dataStr = dataStr.replace(new RegExp(dataFormat.namePropertyName, 'igm'), 'name');
                              }

                              if (dataFormat.idPropertyName) {
                                dataStr = dataStr.replace(new RegExp(dataFormat.idPropertyName, 'igm'), 'id');
                              }

                              if (dataFormat.childPropertyName) {
                                dataStr = dataStr.replace(new RegExp(dataFormat.childPropertyName, 'igm'), 'parentid');
                              }

                              newData = JSON.parse(dataStr);
                            } catch (error) {
                              newData = null;
                            }
                          }

                          if (newData && newData.length) {
                            currentData = newData.deepTree();
                          } else {
                            currentData = null;
                          }

                          resolve(currentData);

                        case 21:
                        case "end":
                          return _context7.stop();
                      }
                    }
                  }, _callee7);
                }));

                return function (_x7) {
                  return _ref4.apply(this, arguments);
                };
              }()));

            case 1:
            case "end":
              return _context8.stop();
          }
        }
      }, _callee8);
    }));
    return _loadData.apply(this, arguments);
  }

  function loadStreets(_x2) {
    return _loadStreets.apply(this, arguments);
  } // 如果列表发生变化, 则查找选中项


  function _loadStreets() {
    _loadStreets = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee10(id) {
      return _regenerator["default"].wrap(function _callee10$(_context10) {
        while (1) {
          switch (_context10.prev = _context10.next) {
            case 0:
              return _context10.abrupt("return", new Promise( /*#__PURE__*/function () {
                var _ref5 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee9(resolve) {
                  var _errMsg, _errMsg2;

                  return _regenerator["default"].wrap(function _callee9$(_context9) {
                    while (1) {
                      switch (_context9.prev = _context9.next) {
                        case 0:
                          setLoading(true);
                          _context9.prev = 1;
                          _context9.next = 4;
                          return getStreets(id);

                        case 4:
                          currentStreets = _context9.sent;
                          _context9.next = 15;
                          break;

                        case 7:
                          _context9.prev = 7;
                          _context9.t0 = _context9["catch"](1);
                          _errMsg = locale('获取数据失败', 'hint_getdata_failed');
                          setErrMsg(_errMsg);
                          setLoading(false);
                          currentStreets = null;
                          resolve(_errMsg);
                          return _context9.abrupt("return");

                        case 15:
                          setLoading(false); // 返回字符串, 说明有错

                          if (!(currentStreets && typeof currentStreets === 'string')) {
                            _context9.next = 22;
                            break;
                          }

                          _errMsg2 = currentStreets;
                          setErrMsg(_errMsg2);
                          currentStreets = null;
                          resolve(_errMsg2);
                          return _context9.abrupt("return");

                        case 22:
                          if (!(!currentStreets || currentStreets instanceof Array === false)) {
                            _context9.next = 26;
                            break;
                          }

                          currentStreets = null;
                          resolve(currentStreets);
                          return _context9.abrupt("return");

                        case 26:
                          // 增加街道标识
                          currentStreets = (currentStreets || []).map(function (street) {
                            street.isStreet = true;
                            return street;
                          });
                          resolve(currentStreets);

                        case 28:
                        case "end":
                          return _context9.stop();
                      }
                    }
                  }, _callee9, null, [[1, 7]]);
                }));

                return function (_x8) {
                  return _ref5.apply(this, arguments);
                };
              }()));

            case 1:
            case "end":
              return _context10.stop();
          }
        }
      }, _callee10);
    }));
    return _loadStreets.apply(this, arguments);
  }

  (0, _react.useEffect)(function () {
    if (!refElBody || !refElBody.current) {
      return;
    }

    var activeEl = refElBody.current.querySelector('.active');

    if (activeEl) {
      refElBody.current.scrollTop = activeEl.offsetTop - activeEl.clientHeight * 2 - 20;
    } else {
      refElBody.current.scrollTop = 0;
    }
  }, [list]); // 点击面板

  function handleClickContainer(e) {
    if (e.target.classList.contains('picker-district-submit')) {
      var options = getOptions();
      var optionsStr = getOptionsStr(options);

      if (submitAttribute && submitAttribute.onClick) {
        submitAttribute.onClick(e, optionsStr, options);
      }
    } else if (e.target.classList.contains('picker-district-cancel')) {
      if (cancelAttribute.onClick) cancelAttribute.onClick(e);
    }

    e.stopPropagation();
  } // 点击tab


  function handleClickTab(tab, index) {
    setErrMsg(''); // 点击街道

    if (tab.isStreet && currentStreets && currentStreets.length) {
      setTabIndex(index);
      setList(currentStreets);
      return;
    } // 点击国家


    if (index === 0 && currentCountries && currentCountries.length) {
      setTabIndex(index);
      setList(currentCountries);
      return;
    } // 点击省(有国家的情况下), 其parentid为国家id, 所以在currentData里找不到数据


    if (index === 1 && currentCountries && currentCountries.length) {
      setTabIndex(index);
      setList(currentData);
      return;
    } // 点击省市区


    var children = getParentChildren(tab.parentid); // 点击末级“请选择”, 直接获取上级的children

    if (index === tabs.length - 1 && !tab.parentid && tabs.length > 1) {
      children = getParentChildren(tabs[index - 1].id);
    }

    if (children) {
      setTabIndex(index);
      setList(children);
    }
  } // 构建选中项


  function getOptions(lastOption) {
    var options = Object.clone(tabs);

    if (options.length) {
      if (lastOption) {
        // 替换掉最后一项请选择
        options[options.length - 1] = lastOption;
      } else if (!options[options.length - 1].parentid) {
        // 删除最后一项请选择
        options.pop();
      }
    }

    return options;
  }

  function getOptionsStr(options) {
    var val = [];

    for (var _iterator3 = _createForOfIteratorHelperLoose(options), _step3; !(_step3 = _iterator3()).done;) {
      var option = _step3.value;
      val.push(option.name);
    }

    return val.join(split);
  } // 提交


  function handleSubmit(e, option) {
    var options = getOptions(option);
    var optionsStr = getOptionsStr(options);

    if (submitAttribute && submitAttribute.onClick) {
      submitAttribute.onClick(e, optionsStr, options);
    }
  } // 点击选项


  function handleClickOption(_x3, _x4) {
    return _handleClickOption.apply(this, arguments);
  } // 过滤已经回调的属性


  function _handleClickOption() {
    _handleClickOption = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee11(e, option) {
      var tabLen, spliceTabs, isLoadStreets;
      return _regenerator["default"].wrap(function _callee11$(_context11) {
        while (1) {
          switch (_context11.prev = _context11.next) {
            case 0:
              // 截取tabs
              tabLen = tabIndex + 1;
              spliceTabs = Object.clone(tabs).splice(0, tabLen); // 修改当前选中项

              spliceTabs[tabIndex] = option;
              tabs = spliceTabs; // 判断点击项是否是类型的末级节点

              if (!isTypeLeaf()) {
                _context11.next = 8;
                break;
              }

              setTabs(spliceTabs);
              handleSubmit(e, option);
              return _context11.abrupt("return");

            case 8:
              if (!(typeof isLeaf === 'function' && isLeaf(Object.clone(tabs)))) {
                _context11.next = 12;
                break;
              }

              setTabs(spliceTabs);
              handleSubmit(e, option);
              return _context11.abrupt("return");

            case 12:
              if (!option.isCountry) {
                _context11.next = 17;
                break;
              }

              _context11.next = 15;
              return loadData(option.id);

            case 15:
              // 有下级, 渲染下级
              if (Array.isArray(currentData) && currentData.length) {
                setList(currentData); // 补充请选择的空项

                spliceTabs.push({
                  parentid: '',
                  id: '',
                  name: '请选择'
                });
                setTabs(spliceTabs);
                setTabIndex(tabLen);
              } // 无下级, 直接提交
              else {
                  setTabs(spliceTabs);
                  handleSubmit(e, option);
                }

              return _context11.abrupt("return");

            case 17:
              if (!(Array.isArray(option.children) && option.children.length)) {
                _context11.next = 23;
                break;
              }

              setList(option.children); // 补充请选择的空项

              spliceTabs.push({
                parentid: '',
                id: '',
                name: '请选择'
              });
              setTabs(spliceTabs);
              setTabIndex(tabLen);
              return _context11.abrupt("return");

            case 23:
              if (!(option.isStreet || !getStreets)) {
                _context11.next = 27;
                break;
              }

              setTabs(spliceTabs);
              handleSubmit(e, option);
              return _context11.abrupt("return");

            case 27:
              _context11.next = 29;
              return loadStreets(option.id);

            case 29:
              isLoadStreets = _context11.sent;

              if (!(typeof isLoadStreets === 'string')) {
                _context11.next = 32;
                break;
              }

              return _context11.abrupt("return");

            case 32:
              if (!(!Array.isArray(currentStreets) || !currentStreets || !currentStreets.length)) {
                _context11.next = 36;
                break;
              }

              setTabs(spliceTabs);
              handleSubmit(e, option);
              return _context11.abrupt("return");

            case 36:
              setList(currentStreets); // 设置tabs
              // spliceTabs[spliceTabs.length - 1].name = option.name

              spliceTabs.push({
                parentid: option.id,
                id: '',
                name: '请选择'
              });
              setTabs(spliceTabs);
              setTabIndex(spliceTabs.length - 1);

            case 40:
            case "end":
              return _context11.stop();
          }
        }
      }, _callee11);
    }));
    return _handleClickOption.apply(this, arguments);
  }

  function filterProps(props) {
    if (!props) return {};

    var show = props.show,
        caption = props.caption,
        onClick = props.onClick,
        otherProps = _objectWithoutPropertiesLoose(props, _excluded2);

    return _extends({}, otherProps);
  } // 剔除掉onClick事件, 因为在instance时已经回调了


  var otherSubmitAttribute = filterProps(submitAttribute);
  var otherCancelAttribute = filterProps(cancelAttribute);
  return (0, _reactDom.createPortal)( /*#__PURE__*/_react["default"].createElement("div", _extends({
    ref: ref
  }, maskAttribute, {
    className: "mask picker-district-mask" + (maskAttribute.className ? ' ' + maskAttribute.className : '') + (show ? ' active' : '')
  }), /*#__PURE__*/_react["default"].createElement("div", _extends({
    "data-animation": "slideUp"
  }, others, {
    className: "picker-district" + (others.className ? ' ' + others.className : ' popup-animation bottom-center') + (show ? ' active' : ''),
    onClick: handleClickContainer
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-header"
  }, cancelAttribute && cancelAttribute.show && /*#__PURE__*/_react["default"].createElement("a", _extends({}, otherCancelAttribute, {
    className: "picker-district-cancel" + (cancelAttribute.className ? ' ' + cancelAttribute.className : '')
  }), cancelAttribute.caption || locale('取消', 'cancel')), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-header-title"
  }, locale('请选择所在地区', 'picker_district_title')), submitAttribute && submitAttribute.show && /*#__PURE__*/_react["default"].createElement("a", _extends({}, otherSubmitAttribute, {
    className: "picker-district-submit" + (submitAttribute.className ? ' ' + submitAttribute.className : '')
  }), submitAttribute.caption || locale('完成', 'finish'))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-tabbar"
  }, tabs.map(function (tab, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      onClick: function onClick() {
        return handleClickTab(tab, index);
      },
      className: "picker-district-tab" + (index === tabIndex ? ' active' : ''),
      key: index
    }, tab.name);
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-body",
    ref: refElBody
  }, list && list.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      onClick: function onClick(e) {
        return handleClickOption(e, item);
      },
      className: "picker-district-option" + (tabs[tabIndex] && tabs[tabIndex].id === item.id ? ' active' : '')
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "picker-district-option-icon"
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: "picker-district-option-caption"
    }, item.name));
  })), errMsg && /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-error"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-error-icon"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-error-label"
  }, errMsg)), loading && /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-load"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-load-icon"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-district-load-label"
  }, locale('加载中...', 'in_loading'))))), portal || context.portal || document.getElementById('root') || document.body);
});
var _default = PickerDistrict;
exports["default"] = _default;
module.exports = exports.default;