import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import Select$1 from "../../../select/index.js";
import useSetRequest from "../../../../hooks/useSetRequest.js";
import useTranslationOriginal from "../../../../hooks/useTranslationOriginal.js";
import { withMode } from "../../dataSourceForm/utils.js";
import { useCountries } from "../Input.Phone/serve.js";
import ReadPretty from "./ReadPretty.js";
import React, { useEffect, useMemo, useState } from "react";
import { isNumber, isString } from "@pisell/utils";
import { Input, Space } from "antd";
//#region src/components/dataSourceComponents/fields/Input.Mobile/WithMode.tsx
const _excluded = [
	"value",
	"onChange",
	"disabled",
	"returnFormat"
];
const { Option } = Select$1;
/**
* 手机号码输入组件
*
* 校验规则：
* 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
*   }}
* />
*/
const MobileNumberInput = (_ref) => {
	let { value: propsValue, onChange, disabled, returnFormat = "string" } = _ref, props = _objectWithoutProperties(_ref, _excluded);
	useSetRequest();
	const { data: countries = [] } = useCountries();
	const translationOriginal = useTranslationOriginal();
	const value = useMemo(() => {
		if (isNumber(propsValue)) return `${propsValue}`;
		return propsValue;
	}, [propsValue]);
	const handleChange = (prefix, phoneNumber, countryCode) => {
		if (returnFormat === "string") {
			const newValue = phoneNumber ? `${prefix}${phoneNumber}` : "";
			onChange === null || onChange === void 0 || onChange(newValue);
		} else onChange === null || onChange === void 0 || onChange({
			phone: phoneNumber,
			countryCallingCode: prefix,
			countryCode
		});
	};
	const parseExternalValue = (val) => {
		if (!val) return {
			countryCode: "AU",
			phoneNumber: ""
		};
		let srtValue = "";
		if (isString(val)) srtValue = val;
		else if ("phone" in val) srtValue = `${val.countryCallingCode || ""}${val.phone || ""}`;
		let matchedContry = null;
		if (!isString(val) && (val === null || val === void 0 ? void 0 : val.countryCode)) matchedContry = countries.find((country) => (country === null || country === void 0 ? void 0 : country.code) === (val === null || val === void 0 ? void 0 : val.countryCode));
		if (!matchedContry) matchedContry = countries.find((country) => srtValue.startsWith(country.prefix));
		if (matchedContry) return {
			countryCode: matchedContry.code,
			phoneNumber: srtValue.slice(matchedContry.prefix.length)
		};
		return {
			countryCode: "AU",
			phoneNumber: srtValue.replace(/\D/g, "")
		};
	};
	const [countryCode, setCountryCode] = useState(() => parseExternalValue(value).countryCode);
	const [phoneNumber, setPhoneNumber] = useState(() => parseExternalValue(value).phoneNumber);
	useEffect(() => {
		if (value) {
			const { countryCode: newCountryCode, phoneNumber: newPhoneNumber } = parseExternalValue(value);
			setCountryCode(newCountryCode);
			setPhoneNumber(newPhoneNumber);
		} else setPhoneNumber("");
	}, [value, countries]);
	const handleCountryChange = (value) => {
		setCountryCode(value);
		const selectedCountry = countries.find((c) => c.code === value);
		handleChange((selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || "", phoneNumber, selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.code);
		setTimeout(() => {
			const formInstance = props.form;
			const fieldName = props.fieldKey;
			if (formInstance && fieldName) formInstance.validateFields([fieldName]);
		});
	};
	const handlePhoneNumberChange = (e) => {
		const cleanNumber = e.target.value.replace(/\D/g, "");
		setPhoneNumber(cleanNumber);
		const selectedCountry = countries.find((c) => c.code === countryCode);
		handleChange((selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || "", cleanNumber, selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.code);
		if (!cleanNumber) {
			const formInstance = props.form;
			const fieldName = props.fieldKey;
			if (formInstance && fieldName) formInstance.setFields([{
				name: fieldName,
				errors: [],
				validating: false
			}]);
		}
	};
	const concatenatedNumber = useMemo(() => {
		const selectedCountry = countries.find((c) => c.code === countryCode);
		if (phoneNumber.length === 0) return "";
		return `${(selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || ""}${phoneNumber}`;
	}, [
		countryCode,
		phoneNumber,
		countries
	]);
	const objValue = useMemo(() => {
		const selectedCountry = countries.find((c) => c.code === countryCode);
		const prefix = (selectedCountry === null || selectedCountry === void 0 ? void 0 : selectedCountry.prefix) || "";
		return {
			phone: phoneNumber || "",
			countryCallingCode: prefix,
			countryCode
		};
	}, [
		countryCode,
		phoneNumber,
		countries
	]);
	const handleBlur = () => {
		const 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$1, {
		disabled,
		value: countryCode,
		onChange: handleCountryChange,
		style: { width: "90px" },
		popupMatchSelectWidth: false,
		optionLabelProp: "inputValue",
		optionFilterProp: "label",
		showSearch: true,
		options: countries.map((country) => ({
			value: country.code,
			label: `${translationOriginal(country.name)} (${country.prefix})`,
			inputValue: country.prefix
		}))
	}), /* @__PURE__ */ React.createElement(Input, _objectSpread2(_objectSpread2({}, props), {}, {
		ref: props === null || props === void 0 ? void 0 : props.inputRef,
		disabled,
		type: "tel",
		value: phoneNumber,
		onChange: handlePhoneNumberChange,
		onBlur: handleBlur,
		style: { flex: 1 }
	})));
};
const MobileNumberInputWithMode = withMode(MobileNumberInput, ReadPretty);
//#endregion
export { MobileNumberInputWithMode as default };
