<template>
	<view>
		<text>{{formProps.placeholder || '计算结果：'}}</text>
		<text>{{_value}}</text>
	</view>
</template>

<script setup>
	import { ref, computed, watch } from 'vue'

	const props = defineProps({
		formProps: {
			type: Object,
			default: () => {
				return {}
			}
		},
		formData: {
			type: Object,
			default: () => {
				return {}
			}
		},
		index: Number,
		modelValue: Number,
		readonly: Boolean
	})

	const _value = computed({
		get() {
			return props.modelValue
		},
		set(val) {
			emits('update:modelValue', val)
		}
	})

	const execute = ref(null)

	const explainStr = computed(() => {
		let explain = ''
		execute.value = null
		props.formProps.explain.forEach(item => {
			const v = String(item.symbol || item)
			if (/[0-9.]$/.test(v)) {
				explain += v
			} else {
				explain += v + ' '
			}
		})
		return explain
	})

	const emits = defineEmits(['update:modelValue'])

	function doExc() {
		try {
			if (!(execute.value instanceof Function)) {
				if (props.formProps.isPlus) {
					const jsExplain = props.formProps.jsCode.replace(/\[\?\]/g, m => '[$_index]')
					execute.value = new Function('formData',
						`let $_index = ${props.index > 0 ? props.index - 1 : 0}; ${jsExplain} return execute(formData)`
						)
				} else {
					execute.value = new Function('formData', `return ${explainStr.value}`)
				}
			}
			let result = execute.value(props.formData)
			_value.value = props.formProps.precision > 0 ? (Number.isNaN(result) ? NaN : parseFloat(result.toFixed(this
				.precision))) : parseInt(result)
		} catch (e) {
			_value.value = NaN
		}
	}

	watch(() => props.formData, () => {
		doExc()
	}, { deep: true })
</script>

<style>
</style>