import "antd-mobile/es/search-bar/style";
import _SearchBar from "antd-mobile/es/search-bar";
import "antd-mobile/es/toast/style";
import _Toast from "antd-mobile/es/toast";
import "antd-mobile/es/list-view/style";
import _ListView from "antd-mobile/es/list-view";

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/* eslint-disable react/no-access-state-in-setstate */

/* eslint-disable no-underscore-dangle */
import React, { Component } from 'react';
import { StickyContainer, Sticky } from 'react-sticky';
import PropTypes from 'prop-types';
import SearchRegionCode from './components/SearchRegionCode';
import callApi from '../_util/ajax';
var IndexedList = _ListView.IndexedList;

var RegionCode =
/*#__PURE__*/
function (_Component) {
  _inherits(RegionCode, _Component);

  function RegionCode(props) {
    var _this;

    _classCallCheck(this, RegionCode);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(RegionCode).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "listRegionCodes", function () {
      _Toast.loading('', 0);

      callApi({
        api: '/region/listRegionCodes',
        success: function success() {
          var res = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

          _this.setState({
            rawRegionCodeList: res
          });

          var regionClassify = _this.splitRegionCodes(res);

          _this.setState({
            dataSource: _this.listViewData(_this.state.dataSource, regionClassify)
          });

          _Toast.hide();
        },
        error: function error(_ref) {
          var _ref$errorDescription = _ref.errorDescription,
              errorDescription = _ref$errorDescription === void 0 ? '' : _ref$errorDescription;

          _Toast.fail(errorDescription);
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "splitRegionCodes", function (list) {
      var regionCodeList = {};
      var hotRegionCodes = [];
      var firstLetters = [];
      list.forEach(function (value) {
        var firstLetter = value.firstLetter,
            _value$hotFlag = value.hotFlag,
            hotFlag = _value$hotFlag === void 0 ? 0 : _value$hotFlag;

        if (hotFlag === 1) {
          hotRegionCodes.push(value);
        }

        regionCodeList[firstLetter] = regionCodeList[firstLetter] || [];
        regionCodeList[firstLetter].push(value);

        if (firstLetters.indexOf(firstLetter) === -1) {
          firstLetters.push(firstLetter);
        }
      }); // 是否支持展示 ‘热门’，需同产品讨论
      // if (this.props.hotFlag === 1 && hotRegionCodes.length) {
      //   regionCodeList = {
      //     '热门': hotRegionCodes,
      //     ...regionCodeList
      //   };
      // }
      // eslint-disable-next-line react/no-unused-state

      _this.setState({
        hotRegionCodes: hotRegionCodes,
        firstLetters: firstLetters
      });

      return regionCodeList;
    });

    _defineProperty(_assertThisInitialized(_this), "onChange", function (searchText) {
      _this.setState({
        searchText: searchText
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onSelect", function (info, e) {
      var onChange = _this.props.onChange; // eslint-disable-next-line no-unused-expressions

      onChange && onChange(info.regionCode, info);
      e.preventDefault();
    });

    var getSectionData = function getSectionData(dataBlob, sectionID) {
      return dataBlob[sectionID];
    };

    var getRowData = function getRowData(dataBlob, sectionID, rowID) {
      return dataBlob[rowID];
    };

    var dataSource = new _ListView.DataSource({
      getRowData: getRowData,
      getSectionHeaderData: getSectionData,
      rowHasChanged: function rowHasChanged(row1, row2) {
        return row1 !== row2;
      },
      sectionHeaderHasChanged: function sectionHeaderHasChanged(s1, s2) {
        return s1 !== s2;
      }
    });
    _this.state = {
      // ListView需要的数据结构
      dataSource: dataSource,
      // 初始区域列表
      rawRegionCodeList: [],
      // 热门地区区号
      // hotRegionCodes: [],
      // 搜索关键字
      searchText: '',
      // 有数据的首字母列表
      firstLetters: [],
      // 输入框是否聚焦中
      focus: false
    };
    return _this;
  }

  _createClass(RegionCode, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.listRegionCodes();
    } // 获取区号列表

  }, {
    key: "listViewData",
    // ListView 需要的 dataSource
    value: function listViewData(ds) {
      var regionClassify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var dataBlob = {};
      var sectionIDs = [];
      var rowIDs = [];
      Object.keys(regionClassify).forEach(function (item, index) {
        sectionIDs.push(item);
        dataBlob[item] = item;
        rowIDs[index] = [];
        regionClassify[item].forEach(function (region) {
          var id = region.id;
          rowIDs[index].push(id);
          dataBlob[id] = region;
        });
      });
      return ds.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs);
    } // 搜索框输入内容变化

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var prefixCls = 'eh-region-code';
      var _this$state = this.state,
          searchText = _this$state.searchText,
          firstLetters = _this$state.firstLetters,
          focus = _this$state.focus,
          rawRegionCodeList = _this$state.rawRegionCodeList,
          dataSource = _this$state.dataSource; // const { hotFlag } = this.props;

      var row = function row(rowData, sectionID, rowID) {
        return React.createElement("div", {
          className: "".concat(prefixCls, "-item"),
          key: rowID,
          onClick: function onClick(e) {
            return _this2.onSelect(rowData, e);
          }
        }, React.createElement("div", {
          className: "".concat(prefixCls, "-item-name")
        }, rowData.name), React.createElement("div", {
          className: "".concat(prefixCls, "-item-region-code")
        }, rowData.regionCode));
      };

      return React.createElement("div", {
        className: prefixCls
      }, React.createElement(_SearchBar, {
        ref: function ref(node) {
          return _this2.searchBar = node;
        },
        value: searchText,
        placeholder: "\u641C\u7D22",
        onChange: this.onChange,
        onFocus: function onFocus() {
          return _this2.setState({
            focus: true
          });
        },
        onBlur: function onBlur() {
          return _this2.setState({
            focus: false
          });
        }
      }), searchText || focus ? React.createElement(SearchRegionCode, {
        searchText: searchText,
        regionCodeList: rawRegionCodeList,
        onSelect: this.onSelect
      }) : React.createElement(IndexedList, {
        useBodyScroll: true,
        className: "sticky-list",
        initialListSize: 100,
        dataSource: dataSource,
        quickSearchBarTop: {},
        quickSearchBarStyle: {
          // 设置右侧导航栏的marginTop，其值应为导航栏高度一半
          marginTop: "".concat(-(firstLetters.length + 1) * 0.3 / 2, "rem")
        },
        renderSectionWrapper: function renderSectionWrapper(sectionID) {
          return React.createElement(StickyContainer, {
            key: "s_".concat(sectionID, "_c"),
            className: "sticky-container"
          });
        },
        renderSectionHeader: function renderSectionHeader(sectionData) {
          return React.createElement(Sticky, null, function (_ref2) {
            var style = _ref2.style;
            return React.createElement("div", {
              className: "sticky",
              style: _objectSpread({}, style)
            }, sectionData);
          });
        },
        renderRow: row,
        delayTime: 50
      }));
    }
  }]);

  return RegionCode;
}(Component);

_defineProperty(RegionCode, "propTypes", {
  // 是否开启热门标记。0：不开启；1：开启
  // hotFlag: PropTypes.number,
  // 选择区号后的回调
  onChange: PropTypes.func.isRequired
});

_defineProperty(RegionCode, "defaultProps", {// hotFlag: 0,
});

export default RegionCode;