"use strict";

exports.__esModule = true;
exports.default = void 0;

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

var _clsx = _interopRequireDefault(require("clsx"));

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

var _picker = _interopRequireDefault(require("../picker"));

var _hooks = require("../hooks");

var _deepClone = require("../utils/deep-clone");

var _utils = require("../utils");

var _raf = require("../utils/raf");

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

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

var EMPTY_CODE = '000000';
var INHERIT_PROPS = ['title', 'loading', 'readonly', 'itemHeight', 'swipeDuration', 'visibleItemCount', 'cancelButtonText', 'confirmButtonText', 'toolbar', 'columnsTop', 'columnsBottom', 'optionRender'];
var Area = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('area', prefixCls),
      bem = _createNamespace[0];

  var pickerRef = (0, _react.useRef)();

  var _useSetState = (0, _hooks.useSetState)({
    code: props.value,
    columns: [{
      values: []
    }, {
      values: []
    }, {
      values: []
    }]
  }),
      state = _useSetState[0],
      updateState = _useSetState[1],
      stateRef = _useSetState[2];

  var areaList = (0, _react.useMemo)(function () {
    return {
      province: props.areaList.province_list || {},
      city: props.areaList.city_list || {},
      county: props.areaList.county_list || {}
    };
  }, [JSON.stringify(props.areaList)]);
  var placeholderMap = (0, _react.useMemo)(function () {
    var columnsPlaceholder = props.columnsPlaceholder;
    return {
      province: columnsPlaceholder[0] || '',
      city: columnsPlaceholder[1] || '',
      county: columnsPlaceholder[2] || ''
    };
  }, [props.columnsPlaceholder]);

  var getDefaultCode = function getDefaultCode() {
    if (props.columnsPlaceholder.length) {
      return EMPTY_CODE;
    }

    var county = areaList.county,
        city = areaList.city;
    var countyCodes = Object.keys(county);

    if (countyCodes[0]) {
      return countyCodes[0];
    }

    var cityCodes = Object.keys(city);

    if (cityCodes[0]) {
      return cityCodes[0];
    }

    return '';
  };

  var getColumnValues = function getColumnValues(type, code) {
    var column = [];

    if (type !== 'province' && !code) {
      return column;
    }

    var list = areaList[type];
    column = Object.keys(list).map(function (listCode) {
      return {
        code: listCode,
        name: list[listCode]
      };
    });

    if (code) {
      // oversea code
      if (type === 'city' && props.isOverseaCode(code)) {
        code = '9';
      }

      column = column.filter(function (item) {
        return item.code.indexOf(code) === 0;
      });
    }

    if (placeholderMap[type] && column.length) {
      // set columns placeholder
      var codeFill = '';

      if (type === 'city') {
        codeFill = EMPTY_CODE.slice(2, 4);
      } else if (type === 'county') {
        codeFill = EMPTY_CODE.slice(4, 6);
      }

      column.unshift({
        code: code + codeFill,
        name: placeholderMap[type]
      });
    }

    return column;
  }; // get index by code


  var getIndex = function getIndex(type, code) {
    var compareNum = code.length;

    if (type === 'province') {
      compareNum = props.isOverseaCode(code) ? 1 : 2;
    }

    if (type === 'city') {
      compareNum = 4;
    }

    code = code.slice(0, compareNum);
    var list = getColumnValues(type, compareNum > 2 ? code.slice(0, compareNum - 2) : '');

    for (var i = 0; i < list.length; i++) {
      if (list[i].code.slice(0, compareNum) === code) {
        return i;
      }
    }

    return 0;
  };

  var setValues = function setValues() {
    var code = stateRef.current.code || getDefaultCode();
    var picker = pickerRef.current;
    var province = getColumnValues('province');
    var city = getColumnValues('city', code.slice(0, 2));

    if (!picker) {
      return;
    }

    picker.setColumnValues(0, province);
    picker.setColumnValues(1, city);

    if (city.length && code.slice(2, 4) === '00' && !props.isOverseaCode(code)) {
      code = city[0].code;
    }

    picker.setColumnValues(2, getColumnValues('county', code.slice(0, 4)));
    picker.setIndexes([getIndex('province', code), getIndex('city', code), getIndex('county', code)]);
  }; // parse output columns data


  var parseValues = function parseValues(values) {
    return values.map(function (value, index) {
      if (value) {
        value = (0, _deepClone.deepClone)(value);

        if (!value.code || value.name === props.columnsPlaceholder[index]) {
          value.code = '';
          value.name = '';
        }
      }

      return value;
    });
  };

  var getValues = function getValues() {
    if (pickerRef.current) {
      var _pickerRef$current;

      var values = (_pickerRef$current = pickerRef.current) == null ? void 0 : _pickerRef$current.getValues().filter(Boolean);
      return parseValues(values);
    }

    return [];
  };

  var getArea = function getArea() {
    var values = getValues();
    var area = {
      code: '',
      country: '',
      province: '',
      city: '',
      county: ''
    };

    if (!values.length) {
      return area;
    }

    var names = values.map(function (item) {
      return item.name;
    });
    var validValues = values.filter(function (value) {
      return value.code;
    });
    area.code = validValues.length ? validValues[validValues.length - 1].code : '';

    if (props.isOverseaCode(area.code)) {
      area.country = names[1] || '';
      area.province = names[2] || '';
    } else {
      area.province = names[0] || '';
      area.city = names[1] || '';
      area.county = names[2] || '';
    }

    return area;
  };

  var reset = function reset(newCode) {
    if (newCode === void 0) {
      newCode = '';
    }

    updateState({
      code: newCode
    });
    setValues();
  };

  var onChange = function onChange(values, index) {
    updateState({
      code: values[index].code
    });
    setValues();

    if (pickerRef.current) {
      var _pickerRef$current2;

      var parsedValues = parseValues((_pickerRef$current2 = pickerRef.current) == null ? void 0 : _pickerRef$current2.getValues());
      if (props.onChange) props.onChange(parsedValues, index);
    }
  };

  var onConfirm = function onConfirm(values, index) {
    setValues();
    if (props.onConfirm) props.onConfirm(parseValues(values), index);
  };

  var onCancel = function onCancel() {
    if (props.onCancel) props.onCancel.apply(props, arguments);
  };

  (0, _hooks.useMount)(setValues);
  (0, _hooks.useUpdateEffect)(function () {
    updateState({
      code: props.value
    });
    setValues();
  }, [props.value]);
  (0, _hooks.useUpdateEffect)(function () {
    setValues();
  }, [props.areaList, props.columnsNum]);
  (0, _react.useEffect)(function () {
    (0, _raf.raf)(function () {
      setValues();
    });
  }, [props.columnsNum]);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      reset: reset,
      getArea: getArea,
      getValues: getValues
    };
  });
  var columns = state.columns.slice(0, +props.columnsNum);
  return /*#__PURE__*/_react.default.createElement(_picker.default, _extends({
    ref: pickerRef,
    className: (0, _clsx.default)(bem()),
    columns: columns,
    columnsFieldNames: {
      text: 'name'
    },
    onChange: onChange,
    onCancel: onCancel,
    onConfirm: onConfirm
  }, (0, _utils.pick)(props, INHERIT_PROPS)));
});

function isOverseaCode(code) {
  return code[0] === '9';
}

Area.defaultProps = {
  areaList: {},
  columnsNum: 3,
  columnsPlaceholder: [],
  isOverseaCode: isOverseaCode
};
var _default = Area;
exports.default = _default;