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 _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, { forwardRef, useRef, useImperativeHandle, useContext, useEffect } from 'react';
import { createPortal } from 'react-dom';
import treeData from './../PickerDistrict/instance.data.js';
import Instance from './instance.js';
import Context from '../Context/instance.js';

var PickerCity = forwardRef(function (_ref, ref) {
  var portal = _ref.portal,
      data = _ref.data,
      _ref$dataFormat = _ref.dataFormat,
      dataFormat = _ref$dataFormat === undefined ? { // {idPropertyName: 'id', namePropertyName: 'name', childPropertyName: 'children'}
    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 ? 'district' : _ref$type,
      _ref$show = _ref.show,
      show = _ref$show === undefined ? false : _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,
      onScrollEnd = _ref.onScrollEnd,
      others = _objectWithoutProperties(_ref, ['portal', 'data', 'dataFormat', 'split', 'type', 'show', 'value', 'selected', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'onScrollEnd']);

  var refEl = useRef(null);
  useImperativeHandle(ref, function () {
    return refEl.current;
  });
  var instance = useRef(null);
  // context
  var context = useContext(Context) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };

  useEffect(function () {
    initInstance();
  }, []); // eslint-disable-line

  useEffect(function () {
    if (!instance.current) return;
    if (show) {
      if (data) {
        instance.current.setData(data, {
          childPropertyName: dataFormat.childPropertyName,
          idPropertyName: dataFormat.idPropertyName,
          namePropertyName: dataFormat.namePropertyName
        });
      }
      setDefault();
      instance.current.show();
    } else {
      instance.current.hide();
    }
  }, [show]);

  // 更新句柄, 防止synchronization模式, 每次组件在render的时候都生成上次render的state、function、effects
  if (instance.current) {
    instance.current.params.onClickSubmit = clickSubmit;
    instance.current.params.onClickCancel = clickCancel;
    instance.current.params.onClickMask = clickMask;
  }
  function clickSubmit(e) {
    // 获取选中项
    e.activeText = e.getActiveText(e.activeOptions);
    e.setActiveKeys(e.activeOptions);
    // Callback
    var value = e.activeText;
    var options = e.activeOptions;
    if (submitAttribute.onClick) submitAttribute.onClick(e, value, options);
  }
  function clickCancel(e) {
    if (cancelAttribute.onClick) cancelAttribute.onClick(e);
  }
  function clickMask(e) {
    if (maskAttribute.onClick) maskAttribute.onClick(e);
  }
  function scrollEnd(e) {
    // var activeOption = e.activeSlot.values[e.activeSlot.activeIndex]
    var activeOption = e.activeOptions[e.activeSlot.index];
    if (e.activeSlot.index === 0) {
      // 滚动省
      var city = e.replaceCity(activeOption[e.params.idPropertyName]); // 修改第二项
      e.replaceDistrict(city[0][e.params.idPropertyName]); // 修改第三项
    } else if (e.activeSlot.index === 1) {
      // 滚动市
      e.replaceDistrict(activeOption[e.params.idPropertyName]); // 修改第三项
    }
    // Callback
    if (onScrollEnd) onScrollEnd(e);
  }

  function setDefault() {
    if (selected && selected.length) {
      instance.current.setDefaultKeys(selected.map(function (item) {
        return item.id;
      }));
    } else {
      var defaultValues = getDefaultValues();
      instance.current.setDefaultValues(defaultValues);
    }
    instance.current.update();
  }
  function getDefaultValues() {
    // 默认值
    var defaultValue = value;
    var defaultValues = [];
    if (defaultValue) {
      defaultValues = defaultValue.split(split).map(function (item) {
        return item.trim();
      });
    }
    return defaultValues;
  }
  function getDefaultKeys() {
    if (selected && selected.length > 1) {
      return selected.map(function (item) {
        return item.id;
      });
    }
    return ['', '', ''];
  }
  function initInstance() {
    var defaultValues = getDefaultValues();
    var defaultKeys = getDefaultKeys();
    // render数据
    instance.current = new Instance({
      data: data || treeData,
      idPropertyName: dataFormat.idPropertyName,
      namePropertyName: dataFormat.namePropertyName,
      childPropertyName: dataFormat.childPropertyName,

      mask: refEl.current,
      split: split,
      viewType: type,
      defaultProvinceKey: defaultKeys[0] || '',
      defaultCityKey: defaultKeys[1] || '',
      defaultDistrictKey: defaultKeys[2] || '',
      defaultProvince: defaultValues[0] || '',
      defaultCity: defaultValues[1] || '',
      defaultDistrict: defaultValues[2] || '',
      onClickMask: clickMask,
      onClickCancel: clickCancel,
      onClickSubmit: clickSubmit,
      onScrollEnd: scrollEnd,
      onHid: function onHid(e) {}
    });
    if (show && instance.current) {
      setTimeout(function () {
        instance.current.show();
      }, 10);
    }
  }
  // 过滤已经回调的属性
  function filterProps(props) {
    if (!props) return {};

    var onClick = props.onClick,
        otherProps = _objectWithoutProperties(props, ['onClick']);

    return _extends({}, otherProps);
  }
  // 剔除掉onClick事件, 因为在instance时已经回调了
  var otherMaskAttribute = filterProps(maskAttribute);
  var otherSubmitAttribute = filterProps(submitAttribute);
  var otherCancelAttribute = filterProps(cancelAttribute);
  return createPortal(React.createElement(
    'div',
    _extends({ ref: refEl }, otherMaskAttribute, { className: 'mask picker-mask' + (otherMaskAttribute.className ? ' ' + otherMaskAttribute.className : '') }),
    React.createElement(
      'div',
      _extends({}, others, { className: 'picker' + (others.className ? ' ' + others.className : '') }),
      React.createElement(
        'div',
        { className: 'picker-header' },
        React.createElement(
          'a',
          _extends({}, otherCancelAttribute, { className: 'picker-cancel' + (otherCancelAttribute.className ? ' ' + otherCancelAttribute.className : '') }),
          otherCancelAttribute.caption || locale('取消', 'cancel')
        ),
        React.createElement(
          'a',
          _extends({}, otherSubmitAttribute, { className: 'picker-submit' + (otherSubmitAttribute.className ? ' ' + otherSubmitAttribute.className : '') }),
          otherSubmitAttribute.caption || locale('完成', 'finish')
        )
      ),
      React.createElement(
        'div',
        { className: 'picker-wrapper' },
        React.createElement(
          'div',
          { className: 'picker-layer' },
          React.createElement('div', { className: 'picker-layer-frame' })
        ),
        React.createElement('div', { className: 'picker-slotbox' })
      )
    )
  ), portal || context.portal || document.getElementById('root') || document.body);
});

export default React.memo(PickerCity, function (prevProps, nextProps) {
  if (nextProps.show === prevProps.show) return true;
  return false;
});