'use strict';

exports.__esModule = true;

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _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; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

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

var _instance2 = _interopRequireDefault(_instance);

var _instanceData = require('./instance.data.js');

var _instanceData2 = _interopRequireDefault(_instanceData);

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

// 数据
var currentData = null; // 省市区
var streets = []; // 街道临时存储

var PickerDistrict = (0, _react.forwardRef)(function (_ref, ref) {
  // eslint-disable-line
  // 初始化数据
  var initCurrentData = function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
      var dataStr, initList;
      return _regenerator2.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              // 初始化数据
              currentData = null;

              if (!(typeof getData === 'function')) {
                _context.next = 7;
                break;
              }

              _context.next = 4;
              return getData();

            case 4:
              currentData = _context.sent;
              _context.next = 8;
              break;

            case 7:
              if (Array.isArray(data)) {
                currentData = data;
              }

            case 8:
              if (currentData && currentData.length) {
                if (dataFormat && (dataFormat.parentPropertyName || dataFormat.namePropertyName || dataFormat.idPropertyName || dataFormat.childPropertyName)) {
                  try {
                    dataStr = JSON.stringify(currentData);

                    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');
                    }
                    currentData = JSON.parse(dataStr);
                  } catch (error) {
                    currentData = null;
                  }
                } else {
                  currentData = data;
                }
              }

              // 初始化tabs
              if (selected && selected.length) {
                initTabs = getTabs(selected.map(function (item) {
                  // eslint-disable-line
                  return item.id;
                }), 'id');
              } else if (value) {
                initTabs = getTabs(value.split(split || '-'), 'name');
              }
              if (initTabs && initTabs.length) {
                initTabs[initTabs.length - 1].name = '请选择';
              } else {
                initTabs[0] = {
                  parentid: '',
                  id: '',
                  name: '请选择'
                };
              }
              // 初始化列表
              initList = getParentChildren(initTabs[initTabs.length - 1].parentid || '');

              setTabs(initTabs);
              setTabIndex(initTabs.length - 1);
              setList(initList);

            case 15:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

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

  // 如果列表发生变化, 则查找选中项


  // 点击选项
  var onClickOption = function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee2(e, option) {
      var tabLen, spliceTabs;
      return _regenerator2.default.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              // 截取tabs
              tabLen = tabIndex + 1;
              spliceTabs = Object.clone(tabs).splice(0, tabLen);

              // 修改当前选中项

              spliceTabs[tabIndex] = option;

              // 因为useState是异步的, 直接提交会提交上一次的值
              tabs = spliceTabs;

              // 如果设置类型为省市区, 则直接提交

              if (!isLeaf()) {
                _context2.next = 8;
                break;
              }

              setTabs(spliceTabs);
              onSubmit(e, option);
              return _context2.abrupt('return');

            case 8:
              if (!(!option.children || !option.children.length)) {
                _context2.next = 28;
                break;
              }

              if (!(!option.isStreet && getStreet)) {
                _context2.next = 25;
                break;
              }

              _context2.next = 12;
              return getStreet(option.id);

            case 12:
              streets = _context2.sent;

              if (!(streets instanceof Array === false)) {
                _context2.next = 15;
                break;
              }

              return _context2.abrupt('return');

            case 15:
              if (!(!streets || !streets.length)) {
                _context2.next = 19;
                break;
              }

              setTabs(spliceTabs);
              onSubmit(e, option);
              return _context2.abrupt('return');

            case 19:
              // 增加街道标识
              streets = (streets || []).map(function (street) {
                street.isStreet = true;
                return street;
              });
              setList(streets);
              // 设置tabs
              // spliceTabs[spliceTabs.length - 1].name = option.name
              spliceTabs.push({
                parentid: option.id,
                id: '',
                name: '请选择'
              });
              setTabs(spliceTabs);
              setTabIndex(spliceTabs.length - 1);
              return _context2.abrupt('return');

            case 25:
              // 街道直接提交
              setTabs(spliceTabs);
              onSubmit(e, option);
              return _context2.abrupt('return');

            case 28:

              // 补充请选择的空项
              spliceTabs.push({
                parentid: '',
                id: '',
                name: '请选择'
              });

              setTabs(spliceTabs);
              setTabIndex(tabLen);

              // 设置下级list
              setList(option.children);

            case 32:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, this);
    }));

    return function onClickOption(_x, _x2) {
      return _ref5.apply(this, arguments);
    };
  }();

  var portal = _ref.portal,
      _ref$data = _ref.data,
      data = _ref$data === undefined ? _instanceData2.default : _ref$data,
      dataFormat = _ref.dataFormat,
      getData = _ref.getData,
      _ref$split = _ref.split,
      split = _ref$split === undefined ? '-' : _ref$split,
      _ref$type = _ref.type,
      type = _ref$type === undefined ? '' : _ref$type,
      show = _ref.show,
      value = _ref.value,
      selected = _ref.selected,
      _ref$maskAttribute = _ref.maskAttribute,
      maskAttribute = _ref$maskAttribute === undefined ? {} : _ref$maskAttribute,
      _ref$submitAttribute = _ref.submitAttribute,
      submitAttribute = _ref$submitAttribute === undefined ? {} : _ref$submitAttribute,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === undefined ? {} : _ref$cancelAttribute,
      getStreet = _ref.getStreet,
      others = _objectWithoutProperties(_ref, ['portal', 'data', 'dataFormat', 'getData', 'split', 'type', 'show', 'value', 'selected', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'getStreet']);

  // 声明ref
  var refElBody = (0, _react.useRef)(null);
  // context
  var context = (0, _react.useContext)(_instance2.default) || {};

  // 页签和列表

  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];

  // 设置列表, 如果类型为省时, 则不显示直辖市, 类型为市时, 则不显示直辖市的区


  function isLeaf() {
    // 判断点击的是否是底层
    if (type === 'province') {
      if (tabIndex === 0) return true;
    } else if (type === 'city') {
      if (tabIndex === 1) return true;
    } else if (type === 'district') {
      if (tabIndex === 2) return true;
    }
    return false;
  }

  // 获取父节点下所有的子节点
  function getParentChildren(parentid) {
    if (!parentid || parentid === '-1') {
      return currentData;
    }
    var parent = currentData.getDeepTreeNode(parentid);
    return parent.children;
  }

  // 根据key或者name获取tabs, property用于区分是key还是value比较
  var initTabs = [];
  function getTabs(values, property) {
    if (!values || !values.length) return null;
    if (property !== 'id' || property !== 'name') property = 'name';
    initTabs = [];
    var levels = 0; // 层级
    function getRow(parentid, list, value) {
      for (var _iterator = list, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
        var _ref2;

        if (_isArray) {
          if (_i >= _iterator.length) break;
          _ref2 = _iterator[_i++];
        } else {
          _i = _iterator.next();
          if (_i.done) break;
          _ref2 = _i.value;
        }

        var item = _ref2;

        // 模糊匹配
        if (item[property].indexOf(value) > -1 || value.indexOf(item[property]) > -1) {
          initTabs.push(_extends({
            parentid: parentid
          }, item));
          var children = item.children;
          // 下一层级
          levels++;
          if (values[levels] && children) {
            getRow(item.id, children, values[levels]);
          }
        }
      }
    }
    getRow('', currentData, values[0]);
    // 如果省市区不对,则返回空
    return initTabs;
  }

  // 数据初始化
  (0, _react.useEffect)(function () {
    initCurrentData();
  }, [data]);(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;
    }
  }, [list]);

  // 点击面板
  function onClickPanel(e) {
    e.stopPropagation();
  }
  // 点击tab
  function onClickTab(tab, index) {
    // 点击街道
    if (tab.isStreet && streets && streets.length) {
      setTabIndex(index);
      setList(streets);
      return;
    }
    // 点击非街道
    var children = getParentChildren(tab.parentid);
    if (children) {
      setTabIndex(index);
      setList(children);
    }
  }
  // 构建选中项
  function getOptions(lastOption) {
    var options = Object.clone(tabs);
    options[options.length - 1] = lastOption;
    return options;
  }
  function getOptionsStr(options) {
    var val = [];
    for (var _iterator2 = options, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
      var _ref4;

      if (_isArray2) {
        if (_i2 >= _iterator2.length) break;
        _ref4 = _iterator2[_i2++];
      } else {
        _i2 = _iterator2.next();
        if (_i2.done) break;
        _ref4 = _i2.value;
      }

      var option = _ref4;

      val.push(option.name);
    }
    return val.join(split);
  }
  // 提交
  function onSubmit(e, option) {
    var options = getOptions(option);
    var optionsStr = getOptionsStr(options);
    if (submitAttribute && submitAttribute.onClick) {
      submitAttribute.onClick(e, optionsStr, options);
    }
  }
  return (0, _reactDom.createPortal)(_react2.default.createElement(
    'div',
    _extends({
      ref: ref
    }, maskAttribute, {
      className: 'mask picker-district-mask' + (maskAttribute.className ? ' ' + maskAttribute.className : '') + (show ? ' active' : '')
    }),
    _react2.default.createElement(
      'div',
      _extends({
        'data-animation': 'slideUp'
      }, others, {
        className: 'picker-district' + (others.className ? ' ' + others.className : ' popup-animation bottom-center') + (show ? ' active' : ''),
        onClick: onClickPanel
      }),
      _react2.default.createElement(
        'div',
        { className: 'picker-district-header' },
        '\u8BF7\u9009\u62E9\u6240\u5728\u5730\u533A'
      ),
      _react2.default.createElement(
        'div',
        { className: 'picker-district-tabbar' },
        tabs.map(function (tab, index) {
          return _react2.default.createElement(
            'div',
            { onClick: function onClick() {
                return onClickTab(tab, index);
              }, className: 'picker-district-tab' + (index === tabIndex ? ' active' : ''), key: index },
            tab.name
          );
        })
      ),
      _react2.default.createElement(
        'div',
        { className: 'picker-district-body', ref: refElBody },
        list && list.map(function (item, index) {
          return _react2.default.createElement(
            'div',
            { key: index, onClick: function onClick(e) {
                return onClickOption(e, item);
              }, className: 'picker-district-option' + (tabs[tabIndex].id === item.id ? ' active' : '') },
            _react2.default.createElement('div', { className: 'picker-district-option-icon' }),
            _react2.default.createElement(
              'div',
              { className: 'picker-district-option-caption' },
              item.name
            )
          );
        })
      )
    )
  ), portal || context.portal || document.getElementById('root') || document.body);
});

exports.default = PickerDistrict;
module.exports = exports['default'];