var _excluded = ["value", "onChange", "disabled", "returnFormat"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useState, useEffect, useMemo } from 'react';
import { Input, Space } from 'antd';
import { isNumber, isString } from '@pisell/utils';
import Select from "../../../select";
import { useCountries } from "./../Input.Phone/serve";
import ReadPretty from "./ReadPretty";
import { withMode } from "../../dataSourceForm/utils";
import useTranslationOriginal from "../../../../hooks/useTranslationOriginal";
import useSetRequest from "../../../../hooks/useSetRequest";
var Option = Select.Option;
/**
 * 手机号码输入组件
 *
 * 校验规则：
 * 1. AU(+61) 验证规则：
 *    - 10位或9位数字
 *    - 前两位是04或者第一位是4
 *    - 格式示例：0412345678 或 412345678
 *
 * 2. CN(+86) 验证规则：
 *    - 11位数字
 *    - 第一位必须是1
 *    - 格式示例：13812345678
 *
 * 3. 其他国家验证规则：
 *    - 15位以内数字
 *    - 格式示例：123456789
 *
 * 使用方式：
 * <Mobile
 *   name="mobile"
 *   label="手机号"
 *   typeobj={{
 *     type: 'mobile',
 *     enabled: true
 *   }}
 * />
 */

var MobileNumberInput = function MobileNumberInput(_ref) {
  var propsValue = _ref.value,
    onChange = _ref.onChange,
    disabled = _ref.disabled,
    _ref$returnFormat = _ref.returnFormat,
    returnFormat = _ref$returnFormat === void 0 ? 'string' : _ref$returnFormat,
    props = _objectWithoutProperties(_ref, _excluded);
  useSetRequest();
  var _useCountries = useCountries(),
    _useCountries$data = _useCountries.data,
    countries = _useCountries$data === void 0 ? [] : _useCountries$data;
  var translationOriginal = useTranslationOriginal();
  var value = useMemo(function () {
    if (isNumber(propsValue)) {
      return "".concat(propsValue);
    }
    return propsValue;
  }, [propsValue]);
  var handleChange = function handleChange(prefix, phoneNumber, countryCode) {
    if (returnFormat === 'string') {
      // 只有当实际输入的号码部分不为空时，才包含区号
      var newValue = phoneNumber ? "".concat(prefix).concat(phoneNumber) : '';
      onChange === null || onChange === void 0 || onChange(newValue);
    } else {
      onChange === null || onChange === void 0 || onChange({
        phone: phoneNumber,
        countryCallingCode: prefix,
        countryCode: countryCode
      });
    }
  };

  // 解析外部传入的value
  var parseExternalValue = function parseExternalValue(val) {
    if (!val) return {
      countryCode: 'AU',
      phoneNumber: ''
    };
    var srtValue = '';
    if (isString(val)) {
      srtValue = val;
    } else if ('phone' in val) {
      srtValue = "".concat(val.countryCallingCode || '').concat(val.phone || '');
    }
    var matchedContry = null;
    // 如果外部传入了countryCode，则以countryCode为准进行countryCode匹配
    if (!isString(val) && val !== null && val !== void 0 && val.countryCode) {
      matchedContry = countries.find(function (country) {
        return (country === null || country === void 0 ? void 0 : country.code) === (val === null || val === void 0 ? void 0 : val.countryCode);
      });
    }
    // 如果外部没有传入countryCode或者匹配不到，则以srtValue为准进行prefix匹配
    if (!matchedContry) {
      matchedContry = countries.find(function (country) {
        return srtValue.startsWith(country.prefix);
      });
    }
    if (matchedContry) {
      return {
        countryCode: matchedContry.code,
        phoneNumber: srtValue.slice(matchedContry.prefix.length)
      };
    }
    return {
      countryCode: 'AU',
      phoneNumber: srtValue.replace(/\D/g, '')
    };
  };
  var _useState = useState(function () {
      return parseExternalValue(value).countryCode;
    }),
    _useState2 = _slicedToArray(_useState, 2),
    countryCode = _useState2[0],
    setCountryCode = _useState2[1];
  var _useState3 = useState(function () {
      return parseExternalValue(value).phoneNumber;
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    phoneNumber = _useState4[0],
    setPhoneNumber = _useState4[1];

  // 监听外部value变化
  useEffect(function () {
    // 只有当 value 不是空字符串时才更新状态
    if (value) {
      var _parseExternalValue = parseExternalValue(value),
        newCountryCode = _parseExternalValue.countryCode,
        newPhoneNumber = _parseExternalValue.phoneNumber;
      setCountryCode(newCountryCode);
      setPhoneNumber(newPhoneNumber);
    } else {
      // 当 value 为空时，只清空号码，保持国家代码不变
      setPhoneNumber('');
    }
  }, [value, countries]);
  var handleCountryChange = function handleCountryChange(value) {
    setCountryCode(value);

    // 在选择国家时也触发 onChange
    var selectedCountry = countries.find(function (c) {
      return c.code === value;
    });
    var prefix = (selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || '';
    // 先更新值
    handleChange(prefix, phoneNumber, selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.code);

    // 使用 setTimeout 确保值更新后再触发验证
    setTimeout(function () {
      // 手动触发表单验证
      var formInstance = props.form;
      var fieldName = props.fieldKey;
      if (formInstance && fieldName) {
        formInstance.validateFields([fieldName]);
      }
    });
  };
  var handlePhoneNumberChange = function handlePhoneNumberChange(e) {
    var cleanNumber = e.target.value.replace(/\D/g, '');
    setPhoneNumber(cleanNumber);

    // 在输入时就触发 onChange
    var selectedCountry = countries.find(function (c) {
      return c.code === countryCode;
    });
    var prefix = (selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || '';
    handleChange(prefix, cleanNumber, selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.code);

    // 如果号码为空，只清除校验信息，不重置国家代码
    if (!cleanNumber) {
      var formInstance = props.form;
      var fieldName = props.fieldKey;
      if (formInstance && fieldName) {
        formInstance.setFields([{
          name: fieldName,
          errors: [],
          // 清除错误信息
          validating: false // 停止验证状态
        }]);
      }
    }
  };
  var concatenatedNumber = useMemo(function () {
    var selectedCountry = countries.find(function (c) {
      return c.code === countryCode;
    });
    if (phoneNumber.length === 0) {
      return '';
    }
    var prefix = (selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || '';
    return "".concat(prefix).concat(phoneNumber);
  }, [countryCode, phoneNumber, countries]);
  var objValue = useMemo(function () {
    var selectedCountry = countries.find(function (c) {
      return c.code === countryCode;
    });
    var prefix = (selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || '';
    return {
      phone: phoneNumber || '',
      countryCallingCode: prefix,
      countryCode: countryCode
    };
  }, [countryCode, phoneNumber, countries]);
  var handleBlur = function handleBlur() {
    var finalValue = concatenatedNumber;
    if (returnFormat === 'string') {
      onChange === null || onChange === void 0 || onChange(finalValue);
    } else {
      onChange === null || onChange === void 0 || onChange(objValue);
    }
  };
  return /*#__PURE__*/React.createElement(Space.Compact, {
    block: true
  }, /*#__PURE__*/React.createElement(Select, {
    disabled: disabled,
    value: countryCode,
    onChange: handleCountryChange,
    style: {
      width: '90px'
    },
    popupMatchSelectWidth: false,
    optionLabelProp: "inputValue",
    optionFilterProp: "label",
    showSearch: true,
    options: countries.map(function (country) {
      return {
        value: country.code,
        label: "".concat(translationOriginal(country.name), " (").concat(country.prefix, ")"),
        inputValue: country.prefix
      };
    })
  }), /*#__PURE__*/React.createElement(Input, _extends({}, props, {
    ref: props === null || props === void 0 ? void 0 : props.inputRef,
    disabled: disabled,
    type: "tel",
    value: phoneNumber,
    onChange: handlePhoneNumberChange,
    onBlur: handleBlur,
    style: {
      flex: 1
    }
  })));
};
var MobileNumberInputWithMode = withMode(MobileNumberInput, ReadPretty);
export default MobileNumberInputWithMode;