import _regeneratorRuntime from 'babel-runtime/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; };

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

import React, { useContext, useState, useEffect, useRef, forwardRef } from 'react';
import { createPortal } from 'react-dom';
import Context from '../Context/instance.js';
import treeData from './instance.data.js';
var streets = []; // 街道临时存储

var PickerDistrict = forwardRef(function (_ref, ref) {
  // 点击选项
  var onClickOption = function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(e, option) {
      var _spliceTabs$push2;

      var tabLen, spliceTabs, _spliceTabs$push;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              // 截取tabs
              tabLen = tabIndex + 1;
              spliceTabs = Object.clone(tabs).splice(0, tabLen);

              // 修改当前选中项

              spliceTabs[tabIndex] = option;

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

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

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

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

            case 8:
              if (!(!option[childProperty] || !option[childProperty].length)) {
                _context.next = 28;
                break;
              }

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

              _context.next = 12;
              return getStreet(option[idProperty]);

            case 12:
              streets = _context.sent;

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

              return _context.abrupt('return');

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

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

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

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

            case 28:

              // 补充请选择的空项
              spliceTabs.push((_spliceTabs$push2 = {}, _spliceTabs$push2[parentProperty] = '', _spliceTabs$push2[idProperty] = '', _spliceTabs$push2[nameProperty] = '请选择', _spliceTabs$push2));

              setTabs(spliceTabs);
              setTabIndex(tabLen);

              // 设置下级list
              setList(option[childProperty]);

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

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

  var portal = _ref.portal,
      _ref$data = _ref.data,
      data = _ref$data === undefined ? treeData : _ref$data,
      _ref$dataFormat = _ref.dataFormat,
      dataFormat = _ref$dataFormat === undefined ? {
    parentName: 'parentid',
    idPropertyName: 'id',
    namePropertyName: 'name',
    childPropertyName: 'children'
  } : _ref$dataFormat,
      _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', 'split', 'type', 'show', 'value', 'selected', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'getStreet']);

  // 声明ref
  var refElBody = useRef(null);
  // context
  var context = useContext(Context) || {};
  var parentProperty = dataFormat.parentName || 'parentid';
  var idProperty = dataFormat.idPropertyName || 'id';
  var nameProperty = dataFormat.namePropertyName || 'name';
  var childProperty = dataFormat.childPropertyName || 'children';

  // 页签和列表

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

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

  var _useState3 = 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 data;
    }
    var parent = data.getDeepTreeNode(parentid, parentProperty, idProperty);
    return parent[childProperty];
  }
  // 根据key或者name获取tabs, property用于区分是key还是value比较
  var initTabs = [];
  function getTabs(values, property) {
    if (!values || !values.length) return null;
    if (property !== idProperty || property !== nameProperty) property = nameProperty;
    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) {
          var _extends2;

          initTabs.push(_extends((_extends2 = {}, _extends2[parentProperty] = parentid, _extends2), item));
          var children = item[childProperty];
          // 下一层级
          levels++;
          if (values[levels] && children) {
            getRow(item[idProperty], children, values[levels]);
          }
        }
      }
    }
    getRow('', data, values[0]);
    // 如果省市区不对,则返回空
    return initTabs;
  }

  // 数据初始化
  useEffect(function () {
    console.log('地区初始化');
    // 初始化tabs
    if (selected && selected.length) {
      initTabs = getTabs(selected.map(function (item) {
        return item.id;
      }), idProperty);
    } else if (value) {
      initTabs = getTabs(value.split(split || '-'), nameProperty);
    }
    if (initTabs && initTabs.length) {
      initTabs[initTabs.length - 1][nameProperty] = '请选择';
    } else {
      var _initTabs$;

      initTabs[0] = (_initTabs$ = {}, _initTabs$[parentProperty] = '', _initTabs$[idProperty] = '', _initTabs$[nameProperty] = '请选择', _initTabs$);
    }
    // 初始化列表
    var initList = getParentChildren(initTabs[initTabs.length - 1][parentProperty] || '');
    setTabs(initTabs);
    setTabIndex(initTabs.length - 1);
    setList(initList);
  }, [data]);

  // 如果列表发生变化, 则查找选中项
  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[parentProperty]);
    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 _ref3;

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

      var option = _ref3;

      val.push(option[nameProperty]);
    }
    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 createPortal(React.createElement(
    'div',
    _extends({
      ref: ref
    }, maskAttribute, {
      className: 'mask picker-district-mask' + (maskAttribute.className ? ' ' + maskAttribute.className : '') + (show ? ' active' : '')
    }),
    React.createElement(
      'div',
      _extends({
        'data-animation': 'slideUp'
      }, others, {
        className: 'picker-district' + (others.className ? ' ' + others.className : ' popup-animation bottom-center') + (show ? ' active' : ''),
        onClick: onClickPanel
      }),
      React.createElement(
        'div',
        { className: 'picker-district-header' },
        '\u8BF7\u9009\u62E9\u6240\u5728\u5730\u533A'
      ),
      React.createElement(
        'div',
        { className: 'picker-district-tabbar' },
        tabs.map(function (tab, index) {
          return React.createElement(
            'div',
            { onClick: function onClick() {
                return onClickTab(tab, index);
              }, className: 'picker-district-tab' + (index === tabIndex ? ' active' : ''), key: index },
            tab[nameProperty]
          );
        })
      ),
      React.createElement(
        'div',
        { className: 'picker-district-body', ref: refElBody },
        list && list.map(function (item, index) {
          return React.createElement(
            'div',
            { key: index, onClick: function onClick(e) {
                return onClickOption(e, item);
              }, className: 'picker-district-option' + (tabs[tabIndex][idProperty] === item[idProperty] ? ' active' : '') },
            React.createElement('div', { className: 'picker-district-option-icon' }),
            React.createElement(
              'div',
              { className: 'picker-district-option-caption' },
              item[nameProperty]
            )
          );
        })
      )
    )
  ), portal || context.portal || document.getElementById('root') || document.body);
});

export default PickerDistrict;