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 useEngineContext from "../../../../hooks/useEngineContext.js";
import useRightItems from "../../hooks/rightItems.js";
import useKeyActions from "../../hooks/keyActions.js";
import { setKeyboardTheme } from "../../utils.js";
import locales_default from "./locales.js";
import React, { useCallback, useEffect, useId, useMemo, useState } from "react";
import { InputNumber, Popover, Segmented } from "antd";
import { locales } from "@pisell/utils";
import Decimal from "decimal.js";
import { Keyboard, PisellModal, PisellText, VirtualInput } from "@pisell/materials";
import { useControllableValue } from "ahooks";
import "./index.less";
//#region src/pro/priceKeyboard/components/discountKeyboard/index.tsx
const _excluded = ["containerProps", "children"], _excluded2 = ["renderType", "open"], _excluded3 = [
	"originalValue",
	"value",
	"onChange",
	"keyboardProps"
];
const TIP_COLORS = {
	positive: "#CA8504",
	negative: "#1570EF",
	overflow: "#D92D20"
};
/**
* originalValue: 当前订单原始值
* defaultValue: 折扣后金额
* onEnter: 折扣金额回调
*/
const DiscountKeyboardBase = (props) => {
	var _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _context$appHelper$ut4;
	const { defaultValue, originalValue, selectType = "light", tips, resetText, doneText, onEnter, onReset, enableExceedMaxAmount = false } = props;
	const context = useEngineContext();
	const [isFirstInput, setIsFirstInput] = useState(true);
	locales.init(locales_default, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut.getApp) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.locales) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut3 = _context$appHelper$ut2.getLocale) === null || _context$appHelper$ut3 === void 0 ? void 0 : _context$appHelper$ut3.call(_context$appHelper$ut2)) || ((_context$appHelper$ut4 = context.appHelper.utils) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut4 = _context$appHelper$ut4.storage) === null || _context$appHelper$ut4 === void 0 ? void 0 : _context$appHelper$ut4.get("umi_locale")) || "en");
	const { getData } = context.appHelper.utils;
	const amountSymbol = props.amountSymbol || (getData === null || getData === void 0 ? void 0 : getData("shop_symbol")) || "$";
	const uniqueKeyboardId = `virtual-keyboard-${((useId === null || useId === void 0 ? void 0 : useId()) || "").replace(/:/g, "-")}`;
	const [updateMode, setUpdateMode] = useState("priceOverride");
	const [discountMode, setDiscountMode] = useState("amount");
	const [internalValue, setInternalValue] = useState(defaultValue ? String(defaultValue) : "");
	const [discountValue, setDiscountValue] = useState("");
	useEffect(() => {
		document.body.id = "body";
	}, []);
	useEffect(() => {
		setKeyboardTheme(selectType);
	}, [selectType]);
	const _onReset = useCallback(() => {
		if (updateMode === "priceOverride") {
			setInternalValue(originalValue ? String(originalValue) : "");
			setIsFirstInput(true);
		} else setDiscountValue("");
		onReset === null || onReset === void 0 || onReset();
	}, [
		originalValue,
		onReset,
		updateMode
	]);
	const _handleChange = useCallback((val) => {
		if (updateMode === "priceOverride") {
			setIsFirstInput(false);
			setInternalValue(val);
		} else setDiscountValue(val);
	}, [updateMode]);
	const discountAmount = useMemo(() => {
		const originalPrice = new Decimal(originalValue || 0);
		let discountAmount = new Decimal(0);
		if (updateMode === "priceOverride") discountAmount = originalPrice.minus(new Decimal(internalValue || 0));
		else if (discountMode === "amount") discountAmount = new Decimal(discountValue || 0);
		else {
			const percentage = new Decimal(discountValue || 0);
			discountAmount = originalPrice.times(percentage.dividedBy(100));
		}
		return discountAmount.toNumber();
	}, [
		updateMode,
		discountMode,
		internalValue,
		discountValue,
		originalValue
	]);
	const isDiscountOverflow = useMemo(() => {
		const _original = new Decimal(originalValue || 0);
		if (updateMode === "priceOverride") return new Decimal(internalValue || 0).greaterThan(_original);
		if (discountMode === "amount") return new Decimal(discountValue || 0).greaterThan(_original);
		return false;
	}, [
		updateMode,
		discountMode,
		internalValue,
		discountValue,
		originalValue
	]);
	const payableAmount = useMemo(() => {
		return new Decimal(originalValue || 0).minus(discountAmount).toNumber();
	}, [originalValue, discountAmount]);
	const handleEnter = () => {
		if (updateMode === "priceOverride" && enableExceedMaxAmount) {
			onEnter === null || onEnter === void 0 || onEnter(String(discountAmount));
			return;
		}
		if (isDiscountOverflow) return;
		onEnter === null || onEnter === void 0 || onEnter(String(discountAmount));
	};
	const _max = useMemo(() => {
		return updateMode === "discount" && discountMode === "percentage" ? 100 : void 0;
	}, [updateMode, discountMode]);
	const { handleChange } = useKeyActions({
		onEnter: handleEnter,
		onReset: _onReset,
		onChange: _handleChange,
		value: updateMode === "priceOverride" ? internalValue : discountValue,
		max: _max,
		mode: isFirstInput && updateMode === "priceOverride" ? "replace" : "append",
		scale: 2
	});
	const rightItems = useRightItems({
		rightItemsStyle: { doneButtonStyle: {
			boxShadow: "0px 0px 1px #898A8D",
			cursor: updateMode !== "priceOverride" && isDiscountOverflow ? "not-allowed" : void 0,
			backgroundColor: updateMode !== "priceOverride" && isDiscountOverflow ? "#D0D5DD" : void 0
		} },
		doneText: doneText || locales.getText("discount-keyboard-done"),
		resetText: resetText || locales.getText("discount-keyboard-reset")
	});
	const formattedVal = useMemo(() => {
		if (updateMode === "priceOverride") return internalValue ? `${amountSymbol}${internalValue}` : "";
		if (discountMode === "amount") return discountValue ? `${amountSymbol}${discountValue}` : "";
		else return discountValue ? `${discountValue}%` : "";
	}, [
		updateMode,
		discountMode,
		internalValue,
		discountValue,
		amountSymbol
	]);
	const placeholder = useMemo(() => {
		if (updateMode === "priceOverride") return `${amountSymbol}0`;
		else {
			if (discountMode === "amount") return "0";
			return "%";
		}
	}, [
		amountSymbol,
		updateMode,
		discountMode
	]);
	const renderBottomContent = () => {
		if (new Decimal(discountAmount).equals(0)) return /* @__PURE__ */ React.createElement("div", null, "\xA0");
		if (updateMode === "priceOverride" || discountMode === "percentage") {
			let color;
			let sign = "";
			if (new Decimal(discountAmount).greaterThan(0)) {
				color = TIP_COLORS.negative;
				sign = "-";
			} else {
				sign = "+";
				color = TIP_COLORS.positive;
			}
			const style = { color };
			return /* @__PURE__ */ React.createElement("div", {
				style,
				className: "ellipsis"
			}, /* @__PURE__ */ React.createElement("span", null, sign, /* @__PURE__ */ React.createElement(PisellText.Amount, {
				hideDecimalForWholeNumbers: false,
				precision: 2,
				value: Math.abs(discountAmount)
			})));
		}
		return /* @__PURE__ */ React.createElement("div", {
			style: { color: isDiscountOverflow ? TIP_COLORS.overflow : "" },
			className: "ellipsis"
		}, locales.getText("discount-keyboard-max-discount"), ":", " ", /* @__PURE__ */ React.createElement(PisellText.Amount, {
			hideDecimalForWholeNumbers: false,
			precision: 2,
			value: originalValue
		}));
	};
	const customDisplay = () => {
		const _color = updateMode === "discount" && discountMode === "amount" && isDiscountOverflow ? TIP_COLORS.overflow : void 0;
		return /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			gap: 8
		} }, /* @__PURE__ */ React.createElement(VirtualInput, {
			focused: true,
			value: formattedVal,
			wrapperStyle: {
				padding: "12px 20px",
				borderRadius: "8px",
				backgroundColor: "white",
				boxShadow: "0px 1px 2px rgba(16, 24, 40, 0.06)",
				flex: "2",
				overflow: "hidden"
			},
			style: { color: _color },
			placeholder,
			bottomContent: renderBottomContent(),
			selected: isFirstInput && updateMode === "priceOverride" && !!internalValue
		}), /* @__PURE__ */ React.createElement("div", { style: {
			flex: "1",
			display: "flex",
			flexDirection: "column",
			borderRadius: "8px",
			backgroundColor: "#ffffff",
			padding: 8,
			boxShadow: "0px 1px 2px rgba(16, 24, 40, 0.06)",
			overflow: "hidden"
		} }, /* @__PURE__ */ React.createElement("div", { style: { flex: 1 } }, /* @__PURE__ */ React.createElement("div", { style: {
			color: "#667085",
			fontSize: 12,
			fontWeight: 500,
			wordWrap: "break-word"
		} }, locales.getText("discount-keyboard-total")), /* @__PURE__ */ React.createElement("div", { style: {
			color: "#475467",
			fontSize: 14,
			fontWeight: 700,
			wordWrap: "break-word"
		} }, /* @__PURE__ */ React.createElement(PisellText.Amount, { value: originalValue }))), /* @__PURE__ */ React.createElement("div", { style: { flex: 1 } }, /* @__PURE__ */ React.createElement("div", { style: {
			color: "#667085",
			fontSize: 12,
			fontWeight: 500,
			wordWrap: "break-word"
		} }, locales.getText("discount-keyboard-payable")), /* @__PURE__ */ React.createElement("div", { style: {
			color: "#475467",
			fontSize: 14,
			fontWeight: 700,
			wordWrap: "break-word"
		} }, /* @__PURE__ */ React.createElement(PisellText.Amount, { value: payableAmount })))));
	};
	const renderTipsContent = () => {
		if (tips) return /* @__PURE__ */ React.createElement("div", { className: "pisell-pro-price-keyboard-tips" }, tips);
		return null;
	};
	return /* @__PURE__ */ React.createElement("div", { className: "pisell-pro-price-keyboard-discount" }, renderTipsContent(), /* @__PURE__ */ React.createElement(Segmented, {
		size: "large",
		style: { padding: 6 },
		options: [{
			label: locales.getText("discount-keyboard-price-override"),
			value: "priceOverride"
		}, {
			label: locales.getText("discount-keyboard-discount"),
			value: "discount"
		}],
		value: updateMode,
		onChange: (val) => setUpdateMode(val),
		block: true
	}), updateMode === "discount" && /* @__PURE__ */ React.createElement(Segmented, {
		size: "large",
		style: { padding: 6 },
		options: [{
			label: locales.getText("discount-keyboard-amount") + ` (${amountSymbol})`,
			value: "amount"
		}, {
			label: locales.getText("discount-keyboard-percentage") + " (%)",
			value: "percentage"
		}],
		value: discountMode,
		onChange: (val) => {
			setDiscountMode(val);
			setDiscountValue("");
		},
		block: true
	}), /* @__PURE__ */ React.createElement("div", { className: "pisell-pro-price-keyboard-content" }, customDisplay(), /* @__PURE__ */ React.createElement(Keyboard, {
		rightItems,
		onChange: handleChange,
		id: uniqueKeyboardId
	})));
};
const DiscountKeyboard = (props) => {
	const { containerProps, children } = props, keyboardProps = _objectWithoutProperties(props, _excluded);
	if (!containerProps) return /* @__PURE__ */ React.createElement(DiscountKeyboardBase, keyboardProps);
	const _ref = containerProps || {}, { renderType, open } = _ref, restProps = _objectWithoutProperties(_ref, _excluded2);
	if (renderType === "popover") return /* @__PURE__ */ React.createElement(Popover, _objectSpread2(_objectSpread2({
		key: `${open}`,
		open,
		trigger: "click",
		className: "pisell-discount-keyboard-popover"
	}, restProps), {}, { content: /* @__PURE__ */ React.createElement(DiscountKeyboardBase, keyboardProps) }), children);
	if (renderType === "modal") return open ? /* @__PURE__ */ React.createElement(PisellModal, _objectSpread2({
		platform: "pc",
		open: true,
		width: "unset",
		header: null,
		footer: false,
		mask: false,
		maskClosable: true,
		bodyStyle: {
			padding: "0px",
			backgroundColor: "transparent"
		},
		closeIcon: null,
		className: "pisell-discount-keyboard-modal",
		destroyOnHidden: true
	}, restProps), /* @__PURE__ */ React.createElement(DiscountKeyboardBase, keyboardProps)) : null;
	return /* @__PURE__ */ React.createElement(DiscountKeyboardBase, keyboardProps);
};
const DiscountKeyboardInputNumber = (props) => {
	var _keyboardProps$contai;
	const { originalValue, value, onChange, keyboardProps } = props, rest = _objectWithoutProperties(props, _excluded3);
	const [internalValue, setInternalValue] = useControllableValue(props);
	const [isOpen, setIsOpen] = useState(false);
	if (((keyboardProps === null || keyboardProps === void 0 || (_keyboardProps$contai = keyboardProps.containerProps) === null || _keyboardProps$contai === void 0 ? void 0 : _keyboardProps$contai.renderType) || "popover") === "modal") return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputNumber, _objectSpread2(_objectSpread2({
		value,
		readOnly: true
	}, rest), {}, { onClick: () => setIsOpen(true) })), /* @__PURE__ */ React.createElement(DiscountKeyboard, _objectSpread2(_objectSpread2({}, keyboardProps || {}), {}, {
		containerProps: _objectSpread2(_objectSpread2({}, keyboardProps === null || keyboardProps === void 0 ? void 0 : keyboardProps.containerProps), {}, {
			open: isOpen,
			onCancel: () => setIsOpen(false),
			renderType: "modal"
		}),
		enableExceedMaxAmount: true,
		defaultValue: internalValue,
		onEnter: (val) => {
			setInternalValue(new Decimal(originalValue).minus(Number(val)).toNumber());
			setIsOpen(false);
		},
		originalValue
	})));
	return /* @__PURE__ */ React.createElement(DiscountKeyboard, _objectSpread2(_objectSpread2({}, keyboardProps || {}), {}, {
		containerProps: _objectSpread2(_objectSpread2({}, keyboardProps === null || keyboardProps === void 0 ? void 0 : keyboardProps.containerProps), {}, {
			open: isOpen,
			onOpenChange: (val) => setIsOpen(val),
			renderType: "popover"
		}),
		enableExceedMaxAmount: true,
		defaultValue: internalValue,
		onEnter: (val) => {
			setInternalValue(new Decimal(originalValue).minus(Number(val)).toNumber());
			setIsOpen(false);
		},
		originalValue
	}), /* @__PURE__ */ React.createElement(InputNumber, _objectSpread2({
		value,
		readOnly: true
	}, rest)));
};
DiscountKeyboard.InputNumber = DiscountKeyboardInputNumber;
//#endregion
export { DiscountKeyboard as default };
