<template>
	<div>
		<el-dialog title="添加方案" v-model="show" @closed="reset" width="730px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="减免金额" prop="amount">
					<el-input v-model="form.amount" placeholder="请输入减免金额" style="width: 270px" :maxlength="8"
						@input="amountInput">
						<template #append>元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="概率" prop="probability">
					<div class="column">
						<div class="item">
							<el-input v-model="form.probability" placeholder="请输入概率" style="width: 270px" @input="probabilityInput">
								<template #append>%</template>
							</el-input>
						</div>
						<div class="item">
							<span class="tips">所有概率相加必须等于100%</span>
						</div>
					</div>
				</el-form-item>
			</el-form>
			<div style="text-align: right; margin-top: 20px">
				<el-button @click="close">取消</el-button>
				<el-button type="primary" @click="submit">{{ isedit ? "更新" : "提交" }}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
import _ from "lodash";
import { ref, toRaw } from "vue";
import { ElMessage } from "element-plus";

// 控制主弹窗显示
const show = ref(false);

// 表单数据
const formRef = ref(null);
const form = ref({
	amount: "",
	probability: "",
});
const rules = ref({
	amount: [{ required: true, message: "请输入减免金额", trigger: "blur" }],
	probability: [{ required: true, message: "请输入概率", trigger: "blur" }],
});

const time = 500;
const amountInput = _.debounce(function (value) {
	form.value.amount = filterNumberInput(value);
}, time);
const probabilityInput = _.debounce(function (value) {
	form.value.probability = filterNumberInput(value, 1);
	if (form.value.probability >= 100) {
		form.value.probability = 100;
	}
}, time);

// 重置表单
function reset() {
	form.value = {
		amount: "",
		probability: "",
	};
}

// 提交表单
const emits = defineEmits(["submitSuccess"]);
function submit() {
	formRef.value.validate(async (valid) => {
		try {
			if (valid) {
				emits("submitSuccess", form.value, dataIndex);
				close();
			}
		} catch (err) {
			console.log(err);
		}
	});
}

let isedit = ref(false);
let dataIndex = null;
function open(data = null, index = 0) {
	if (data) {
		form.value = { ...data };
		dataIndex = index;
		isedit.value = true;
	} else {
		dataIndex = null;
		isedit.value = false;
	}
	console.log(data);
	show.value = true;
}
function close() {
	show.value = false;
	reset();
}
defineExpose({ open });

/**
 * 过滤输入，只允许数字和最多两位小数
 * @param {string} value - 输入框当前值
 * @param {boolean} isIntegerOnly - 是否只允许正整数（无小数点），开启时最小值为1
 * @returns {string} 过滤后的合法值
 */
function filterNumberInput(value, isIntegerOnly = false) {
	// 第一步就过滤所有非数字和非小数点的字符（包括字母）
	let filtered = value.replace(/[^\d.]/g, "");

	// 整数模式处理
	if (isIntegerOnly) {
		// 移除所有小数点
		filtered = filtered.replace(/\./g, "");

		// 处理前导零
		filtered = filtered.replace(/^0+(\d)/, "$1") || filtered;

		// 空值处理（允许临时删除）
		if (filtered === "") {
			return "";
		}

		// 最小值限制
		if (filtered === "0" || parseInt(filtered, 10) < 1) {
			return "1";
		}

		return filtered;
	}

	// 小数模式处理
	const parts = filtered.split(".");
	if (parts.length > 1) {
		filtered = parts[0] + "." + (parts[1].substring(0, 2) || "");
	}

	// 处理前导零
	if (filtered.startsWith("0") && filtered.length > 1 && !filtered.startsWith("0.")) {
		filtered = filtered.replace(/^0+(\d)/, "$1");
	}

	return filtered;
}
</script>

<style scoped lang="scss">
.column {
	display: flex;
	flex-direction: column;

	.item {
		flex: 1;
	}
}
</style>
