<template>
	<div class="langConfig">
		<div class="content">
			<byTable
				:source="sourceList.data"
				:pagination="sourceList.pagination"
				:config="config"
				:loading="loading"
				highlight-current-row
				:selectConfig="selectConfig"
				searchKey="userName"
				:table-events="{
					//element talbe事件都能传
					select: select,
				}"
				:action-list="[
					{
						text: '同步其他语种配置',
						action: () => openModal('add'),
						disabled: !sourceList.pagination.tenantId,
					},
				]"
				@get-list="getList"

			>
				<template #slotName="{ item }">
					{{ item.createTime }}
				</template>
			</byTable>
		</div>
		<el-dialog
			:title="modalType == 'add' ? '修改语言配置' : '修改语言配置'"
			v-if="dialogVisible"
			v-model="dialogVisible"
			width="500"
			v-loading="loading"
		>
			<byForm
				:formConfig="formConfig"
				:formOption="formOption"
				v-model="formData.data"
				:rules="rules"
				ref="byform"
			>
			</byForm>
			<template #footer>
				<el-button @click="dialogVisible = false" size="large"
					>取 消</el-button
				>
				<el-button
					type="primary"
					@click="submitForm('byform')"
					size="large"
					:loading="submitLoading"
					>确 定</el-button
				>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from 'element-plus'
import byTable from '@/components/byTable/index'
import byForm from '@/components/byForm/index'
import treeList from '@/components/treeList/index'
import { computed, defineComponent, ref } from 'vue'
const loading = ref(false)
const submitLoading = ref(false)
const sourceList = ref({
	data: [],
	pagination: {
		total: 3,
		pageNum: 1,
		pageSize: 10,
		type:'web'
	},
})
let dialogVisible = ref(false)
let modalType = ref('add')
const validatePass = (rule, value, callback) => {
	if (!formData.data.password && modalType.value == 'add') {
		callback(new Error('请输入账号和密码'))
	} else {
		callback()
	}
}
let rules = ref({

	
})

const userId = ref('')
const { proxy } = getCurrentInstance()
const password = ref('')
const selectConfig = computed(() => {
	return [
		{
			label: "选择系统",
			prop: "type",
			data: [
				{
					label:'web',
					id:'web'
				},
				{
					label:'app',
					id:'app'
				}
			],
		},
	]
})
const config = computed(() => {
	return [
		{
			attrs: {
				label: '中文名称',
				prop: 'value',
			},
		},

		{
			attrs: {
				label: '英文名称',
				prop: 'enText',
			},
		},
		{
			attrs: {
				label: '对象索引',
				prop: 'key',
				align: 'left',
			},
		},
		{
			attrs: {
				label: '操作',
				width: '200',
				align: 'right',
			},
			// 渲染 el-button，一般用在最后一列。
			renderHTML(row) {
				return [
					{
						attrs: {
							label: '修改',
							type: 'primary',
							text: true,
						},
						el: 'button',
						click() {
							getDtl(row)
						},
					},
				]
			},
		},
	]
})

let formData = reactive({
	data: {},
})
const formOption = reactive({
	inline: true,
	labelWidth: 100,
	itemWidth: 100,
	rules: [],
})
const byform = ref(null)
const treeListData = ref([])
const formConfig = computed(() => {
	return [
		
		{
			type: 'input',
			prop: 'value',
			label: '中文名称',
			required: true,
			itemType: 'text',
			disabled:true,
		},
		{
			type: 'input',
			prop: 'enText',
			label: '英文名称',
			required: true,
			itemType: 'text',
		},
	]
})

//根据resurl获取数据
const getFormat = (formatStr, props) => {
  if (!formatStr) return props;
  return formatStr
    .split(".")
    .reduce((total, cur) => (!total ? "" : total[cur]), props);
};

const submitData = ref('')

const getList = async (req) => {
	sourceList.value.pagination = { ...sourceList.value.pagination, ...req }
	console.log(sourceList.value.pagination.type)
	loading.value = false
	proxy
		.get('/open/multilingual/getJson', {})
		.then((message) => {
			submitData.value = JSON.parse(message.data)
            const res = JSON.parse(message.data)
			// proxy.post('/open/multilingual/setJson',{configValue:JSON.stringify(res)}).then((message) => {
			// })
			console.log(res[sourceList.value.pagination.type],12312312)
            const tableData = getAllKeys(res.app.cn)
			console.log(tableData)
			//根据key获取res里其他语言的值
			for (let i = 0; i < tableData.length; i++) {
				const element = tableData[i];
				element.enText = getFormat(element.key,res.app.en)
			}
			sourceList.value.data = tableData
		})
}
//递归对象所有对象,将不是对象的属性放入数组，数组为对象类型，记录所有父级的key以数组方式存储
const getAllKeys = (obj) => {
	let result = []
	const getKeys = (obj, parentKey) => {
		Object.keys(obj).forEach((key) => {
			if (typeof obj[key] === 'object') {
				getKeys(obj[key], parentKey ? `${parentKey}.${key}` : key)
			} else {
				result.push({
					key: parentKey ? `${parentKey}.${key}` : key,
					value: obj[key],
				})
			}
		})
	}
	getKeys(obj)
	return result

}

const treeChange = (e) => {
	console.log(e)
	sourceList.value.pagination.tenantId = e.id
	getList({ tenantId: e.id })
	getUserList()
	getDept()
}

const openModal = () => {
	dialogVisible.value = true
	modalType.value = 'add'
	formData.data = {
		userType: 1,
	}
}

const tree = ref(null)
const submitForm = () => {
	byform.value.handleSubmit((valid) => {
		console.log(formData.data)
		//根据key修改submitData里的值
		const key = formData.data.key
		const value = formData.data.value
		const enText = formData.data.enText
		const keyArr = key.split('.')
		let obj = submitData.value.app.en
		for (let i = 0; i < keyArr.length; i++) {
			const element = keyArr[i]
			if (i == keyArr.length - 1) {
				obj[element] = enText
			} else {
				obj = obj[element]
			}
		}
		proxy.post('/open/multilingual/setJson',{configValue:JSON.stringify(submitData.value)}).then((message) => {
			console.log(message)
			dialogVisible.value = false
			getList()
		})
	})
}

const getDtl = (row) => {
	formData.data = { ...row}
	modalType.value = 'edit'
	dialogVisible.value = true
	
}
getList()
</script>

<style lang="scss" scoped>
.langConfig {
	padding: 20px;
	display: flex;
	justify-content: space-between;

	.content {
		width: 100%;
	}
}
</style>
