<template>
	<el-container>
		<el-main>
			<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="formRef" label-width="100px">
				<el-form-item label="分组" prop="group">
					<pi-select v-model="form.group" :api="api.system.dict_data.option"
							   :params="{key: 'sys_langs_group'}"
							   :props="{label: 'dict_label', value: 'dict_value'}"
							   placeholder="请输入分组" clearable/>
				</el-form-item>
				<el-form-item label="key" prop="translation_key">
					<el-input type="text" v-model="form.translation_key" placeholder="请输入key" clearable></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="remark">
					<el-input type="text" v-model="form.remark" placeholder="请输入描述" clearable></el-input>
				</el-form-item>
				<el-form-item v-for="item in langs" :key="item.dict_value" :label="item.dict_label+item.dict_value"
							  prop="item.dict_value">
					<el-input type="text" v-model="values[item.dict_value]" placeholder="请输入译文"
							  clearable></el-input>
				</el-form-item>
			</el-form>
		</el-main>
		<el-footer style="padding:10px;text-align: right;height: auto;">
			<el-button @click="emit('closed')">取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" @click="submit()">保 存</el-button>
		</el-footer>
	</el-container>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import api from "@/api/index"

defineExpose({open, setLangs})
const emit = defineEmits(['success', 'closed'])
const formRef = ref(null)
const {proxy} = getCurrentInstance()

let mode = ref('add')
let form = ref({
	translation_id: null,
	group: null,
	translation_key: null,
	remark: null,
	values: []
})
let langs = ref([])
const rules = ref({
	group: [
		{required: true, message: '请填写分组'}
	],
	translation_key: [
		{required: true, message: '请填写key'}
	],
})
const values = ref({})

function open(m = 'add', data = null) {
	mode.value = m
	Object.assign(form.value, data)
	// 数据回显
	let arr = {}
	form.value.values.forEach(i => {
		if (langs.value.map(j => j.dict_value).includes(i.lang_code)) {
			arr[i.lang_code] = i.lang_value
		}
	})
	values.value = arr
}

function setLangs(data) {
	langs.value = data
	return {open}
}

async function submit() {
	let arr = []
	Object.keys(values.value).forEach(i => {
		arr.push({
			lang_code: i,
			lang_value: values.value[i]
		})
	})
	form.value.values = arr
	// 校验登录
	const validate = await formRef.value.validate().catch(() => {
	});
	if (!validate) {
		return false
	}
	const res = form.value.translation_id ? await api.system.translation.edit(form.value) : await api.system.translation.add(form.value);
	emit('success')
	emit('closed')
	proxy.$message.success(res.msg)
}
</script>
