<template>
	<div class="system-edit-dic-container">
		<!-- 新增属性定义/编辑属性定义 -->
		<el-dialog
			:title="ruleForm.id !== 0 ? $t('message.device.dialogI18n.editPropertyDefinition') : $t('message.device.dialogI18n.addPropertyDefinition')"
			v-model="isShowDialog"
			width="769px"
		>
			<!-- 根据当前语言设置label-width -->
			<el-form :model="ruleForm" ref="formRef" :rules="rules" :label-width="currentLocale == 'en' ? '150px' : '120px'">
				<!-- 属性定义标识 -->
				<el-form-item :label="$t('message.device.formI18nLabel.propertyIdentifier')" prop="key">
					<!-- 请输入属性定义标识 -->
					<el-input
						v-model="ruleForm.key"
						:placeholder="$t('message.device.formI18nPlaceholder.propertyIdentifier')"
						:disabled="ruleForm.id !== 0 ? true : false"
					/>
				</el-form-item>
				<!-- 属性定义名称 -->
				<el-form-item :label="$t('message.device.formI18nLabel.propertyName')" prop="name">
					<!-- 请输入属性定义名称 -->
					<el-input v-model.trim="ruleForm.name" :placeholder="$t('message.device.formI18nPlaceholder.propertyName')" />
				</el-form-item>

				<!-- 数据类型 -->
				<el-form-item :label="$t('message.device.formI18nLabel.dataType')" prop="type">
					<template v-if="typeData.length > 0">
						<!-- 请选择数据类型 -->
						<el-select
							v-model="valueType.type"
							:placeholder="$t('message.device.formI18nPlaceholder.selectDataType')"
							@change="seletChange"
							:disabled="ruleForm.id !== 0 ? true : false"
						>
							<el-option-group v-for="group in typeData" :key="group.label" :label="group.label">
								<el-option v-for="item in group.options" :key="item.type" :label="item.title" :value="item.type" />
							</el-option-group>
						</el-select>
					</template>
				</el-form-item>

				<!--根据数据类型输出不同表单-->

				<!-- 精度 -->
				<el-form-item :label="$t('message.device.formI18nLabel.precision')" prop="decimals" v-if="type == 'float' || type == 'double'">
					<!-- 请输入精度 -->
					<el-input v-model="valueType.decimals" :placeholder="$t('message.device.formI18nPlaceholder.precision')" />
				</el-form-item>

				<!-- 单位 -->
				<el-form-item
					:label="$t('message.device.formI18nLabel.unit')"
					prop="unit"
					v-if="type == 'int' || type == 'long' || type == 'float' || type == 'double'"
				>
					<!-- 请输入单位 -->
					<el-input v-model="valueType.unit" :placeholder="$t('message.device.formI18nPlaceholder.inputUnit')" />
				</el-form-item>

				<!-- 最大长度 -->
				<el-form-item :label="$t('message.device.formI18nLabel.maxLength')" prop="maxLength" v-if="type == 'string'">
					<!-- 请输入最大长度 -->
					<el-input v-model="valueType.maxLength" :placeholder="$t('message.device.formI18nPlaceholder.inputMaxLength')" />
				</el-form-item>

				<!-- 时间格式 -->
				<el-form-item :label="$t('message.device.formI18nLabel.timeFormat')" prop="maxLength" v-if="type == 'date'">
					<!-- 请输入时间格式 -->
					<el-input v-model="valueType.maxLength" :placeholder="$t('message.device.formI18nPlaceholder.inputTimeFormat')" />
				</el-form-item>

				<!-- 布尔值 -->
				<el-form-item :label="$t('message.device.formI18nLabel.booleanValue')" prop="trueText" v-if="type == 'boolean'">
					<div class="input-box flex-row">
						<!-- 请输入true时显示的文字 -->
						<el-input v-model="valueType.trueText" :placeholder="$t('message.device.formI18nPlaceholder.inputTrueText')" /><span
							style="margin: 0px 10px"
							>~</span
						>
						<!-- 请输入布尔值 -->
						<el-input v-model="valueType.trueValue" :placeholder="$t('message.device.formI18nPlaceholder.inputBooleanValue')" disabled />
					</div>

					<div class="input-box flex-row">
						<!-- 请输入false时显示的文字 -->
						<el-input v-model="valueType.falseText" :placeholder="$t('message.device.formI18nPlaceholder.inputFalseText')" />
						<span style="margin: 0px 10px">~</span>
						<!-- 请输入布尔值 -->
						<el-input v-model="valueType.falseValue" :placeholder="$t('message.device.formI18nPlaceholder.inputBooleanValue')" disabled />
					</div>
				</el-form-item>

				<!-- 枚举项 -->
				<el-form-item :label="$t('message.device.formI18nLabel.enumItems')" prop="maxLength" v-if="type == 'enum'">
					<div class="input-box flex-row" v-for="(item, index) in enumdata" :key="index">
						<!-- 请输入枚举文本 -->
						<el-input v-model="item.text" :placeholder="$t('message.device.formI18nPlaceholder.inputEnumText')" /><span style="margin: 0px 10px"
							><el-icon> <Right /> </el-icon
						></span>
						<!-- 请输入枚举值 -->
						<el-input v-model="item.value" :placeholder="$t('message.device.formI18nPlaceholder.inputEnumValue')" />
						<div class="input-option">
							<el-icon @click="addEnum" v-if="index == 0">
								<Plus />
							</el-icon>
							<el-icon @click="delEnum(index)" v-if="index != 0">
								<Minus />
							</el-icon>
						</div>
					</div>
				</el-form-item>

				<el-form-item :label="$t('message.device.formI18nLabel.jsonObject')" prop="maxLength" v-if="type == 'object'">
					<div v-for="(item, index) in jsondata" :key="index" class="jslist">
						<div class="jsonlist">
							<!-- 参数标识：{{ item.key }} -->
							<div>{{ $t('message.device.formI18nLabel.parameterIdentifier') }}：{{ item.key }}</div>
							<!-- 参数名称：{{ item.name }} -->
							<div>{{ $t('message.device.formI18nLabel.parameterName') }}：{{ item.name }}</div>
							<!-- 数据类型：{{ item.valueType.type }} -->
							<div>{{ $t('message.device.formI18nLabel.dataType') }}：{{ item.valueType.type }}</div>
							<div class="jsonoption">
								<!-- 编辑 -->
								<el-link type="primary" @click="editjson(index)">{{ $t('message.tableI18nAction.edit') }}</el-link>
								<!-- 删除 -->
								<el-link type="primary" @click="deljson(index)">{{ $t('message.tableI18nAction.delete') }}</el-link>
							</div>
						</div>
					</div>

					<div style="display: block; width: 100%">
						<div class="input-options" @click="addJson">
							<el-icon>
								<Plus />
							</el-icon>
							<!-- 添加参数 -->
							<div>{{ $t('message.device.formI18nButton.addParameter') }}</div>
						</div>
					</div>
				</el-form-item>

				<div v-if="type == 'array'">
					<!-- 元素类型 -->
					<el-form-item :label="$t('message.device.formI18nLabel.elementType')" prop="types">
						<!-- 请选择元素类型 -->
						<el-select v-model="elementType.type" :placeholder="$t('message.device.formI18nPlaceholder.selectElementType')" @change="seletChanges">
							<el-option-group v-for="group in typeData" :key="group.label" :label="group.label">
								<el-option v-for="item in group.options" :key="item.type" :label="item.title" :value="item.type" :disabled="item.type == 'array'" />
							</el-option-group>
						</el-select>
					</el-form-item>

					<!-- 精度 -->
					<el-form-item :label="$t('message.device.formI18nLabel.precision')" prop="decimals" v-if="types == 'float' || types == 'double'">
						<!-- 请输入精度 -->
						<el-input v-model="elementType.decimals" :placeholder="$t('message.device.formI18nPlaceholder.inputPrecision')" />
					</el-form-item>

					<!-- 单位 -->
					<el-form-item
						:label="$t('message.device.formI18nLabel.unit')"
						prop="unit"
						v-if="types == 'int' || types == 'long' || types == 'float' || types == 'double'"
					>
						<!-- 请输入单位 -->
						<el-input v-model="elementType.unit" :placeholder="$t('message.device.formI18nPlaceholder.inputUnit')" />
					</el-form-item>

					<!-- 最大长度 -->
					<el-form-item :label="$t('message.device.formI18nLabel.maxLength')" prop="maxLength" v-if="types == 'string'">
						<!-- 请输入最大长度 -->
						<el-input v-model="elementType.maxLength" :placeholder="$t('message.device.formI18nPlaceholder.inputMaxLength')" />
					</el-form-item>

					<!-- 时间格式 -->
					<el-form-item :label="$t('message.device.formI18nLabel.timeFormat')" prop="maxLength" v-if="types == 'date'">
						<!-- 请输入时间格式 -->
						<el-input v-model="elementType.maxLength" :placeholder="$t('message.device.formI18nPlaceholder.inputTimeFormat')" />
					</el-form-item>

					<!-- 布尔值 -->
					<el-form-item :label="$t('message.device.formI18nLabel.booleanValue')" prop="maxLength" v-if="types == 'boolean'">
						<div class="input-box flex-row">
							<!-- 请输入true时显示的文字 -->
							<el-input v-model="elementType.trueText" :placeholder="$t('message.device.formI18nPlaceholder.inputTrueText')" /><span
								style="margin: 0px 10px"
								>~</span
							>
							<!-- 请输入布尔值 -->
							<el-input v-model="elementType.trueValue" :placeholder="$t('message.device.formI18nPlaceholder.inputBooleanValue')" disabled />
						</div>

						<div class="input-box flex-row">
							<!-- 请输入false时显示的文字 -->
							<el-input v-model="elementType.falseText" :placeholder="$t('message.device.formI18nPlaceholder.inputFalseText')" />
							<span style="margin: 0px 10px">~</span>
							<!-- 请输入布尔值 -->
							<el-input v-model="elementType.falseValue" :placeholder="$t('message.device.formI18nPlaceholder.inputBooleanValue')" disabled />
						</div>
					</el-form-item>

					<!-- 枚举项 -->
					<el-form-item :label="$t('message.device.formI18nLabel.enumItems')" prop="maxLength" v-if="types == 'enum'">
						<div class="input-box flex-row" v-for="(item, index) in enumdata" :key="index">
							<!-- 请输入枚举文本 -->
							<el-input v-model="item.text" :placeholder="$t('message.device.formI18nPlaceholder.inputEnumText')" /><span style="margin: 0px 10px"
								><el-icon> <Right /> </el-icon
							></span>
							<!-- 请输入枚举值 -->
							<el-input v-model="item.value" :placeholder="$t('message.device.formI18nPlaceholder.inputEnumValue')" />
							<div class="input-option">
								<el-icon @click="addEnum" v-if="index == 0">
									<Plus />
								</el-icon>
								<el-icon @click="delEnum(index)" v-if="index != 0">
									<Minus />
								</el-icon>
							</div>
						</div>
					</el-form-item>
				</div>

				<el-form-item :label="$t('message.device.formI18nLabel.jsonObject')" prop="maxLength" v-if="types == 'object'">
					<div v-for="(item, index) in jsondata" :key="index" class="jslist">
						<div class="jsonlist">
							<!-- 参数标识：{{ item.key }} -->
							<div>{{ $t('message.device.formI18nLabel.parameterIdentifier') }}：{{ item.key }}</div>
							<!-- 参数名称：{{ item.name }} -->
							<div>{{ $t('message.device.formI18nLabel.parameterName') }}：{{ item.name }}</div>
							<!-- 数据类型：{{ item.valueType.type }} -->
							<div>{{ $t('message.device.formI18nLabel.dataType') }}：{{ item.valueType.type }}</div>
							<div class="jsonoption">
								<!-- 编辑 -->
								<el-link type="primary" @click="editjson(index)">{{ $t('message.tableI18nAction.edit') }}</el-link>
								<!-- 删除 -->
								<el-link type="primary" @click="deljson(index)">{{ $t('message.tableI18nAction.delete') }}</el-link>
							</div>
						</div>
					</div>

					<div style="display: block; width: 100%">
						<div class="input-options" @click="addJson">
							<el-icon>
								<Plus />
							</el-icon>
							<!-- 添加参数 -->
							<div>{{ $t('message.tableI18nAction.addParameter') }}</div>
						</div>
					</div>
				</el-form-item>

				<!--根据数据类型输出不同表单-->
				<!-- 是否只读 -->
				<el-form-item :label="$t('message.device.formI18nLabel.isReadOnly')" prop="accessMode">
					<el-radio-group v-model="ruleForm.accessMode">
						<!-- 1:只读 -->
						<el-radio :label="1">{{ $t('message.device.formI18nOption.readonly') }}</el-radio>
						<!-- 0:读写 -->
						<el-radio :label="0">{{ $t('message.device.formI18nOption.readWrite') }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<!-- 属性定义描述 -->
				<el-form-item :label="$t('message.device.formI18nLabel.propertyDescription')" prop="desc">
					<!-- 请输入属性定义描述 -->
					<el-input v-model="ruleForm.desc" type="textarea" :placeholder="$t('message.device.formI18nPlaceholder.inputDescription')"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<!-- 取消 -->
					<el-button @click="onCancel">{{ $t('message.tableI18nAction.cancel') }}</el-button>
					<!-- 编辑/添加 -->
					<el-button type="primary" @click="onSubmit">{{
						ruleForm.id !== 0 ? $t('message.tableI18nAction.edit') : $t('message.tableI18nAction.add')
					}}</el-button>
				</span>
			</template>
		</el-dialog>
		<EditOption ref="editOptionRef" @typeList="getOptionData" />
	</div>
</template>

<script lang="ts" setup>
import { computed, ref, unref } from 'vue'
import api from '/@/api/device'
import { Plus, Minus, Right } from '@element-plus/icons-vue'
import EditOption from './editOption.vue'
import { ElMessage } from 'element-plus'
import { validateNoSpace } from '/@/utils/validator'
import { useI18n } from 'vue-i18n'

// 国际化
const { locale, t } = useI18n()

const currentLocale = computed(() => locale.value)

const emit = defineEmits(['typeList'])

const valueTypeModule = {
	type: '',
	maxLength: '',
	trueText: '是',
	trueValue: true,
	falseText: '否',
	falseValue: false,
}

const formRef = ref<HTMLElement | null>(null)
const editOptionRef = ref()
const rules = computed(() => ({
	name: [
		// 属性定义名称不能为空
		{ required: true, message: t('message.device.rules.propertyName'), trigger: 'blur' },
		// 属性定义名称不能超过32个字符
		{ max: 32, message: t('message.device.rules.propertyNameMax32'), trigger: 'blur' },
		// 属性定义名称不能包含空格
		{ validator: validateNoSpace, message: t('message.device.rules.propertyNameValidator'), trigger: 'blur' },
	],
	// 属性定义标识不能为空
	key: [{ required: true, message: t('message.device.rules.propertyKey'), trigger: 'blur' }],
	// 请选择是否只读
	accessMode: [{ required: true, message: t('message.device.rules.accessMode'), trigger: 'blur' }],
	// 请选择数据类型
	type: [{ required: true, message: t('message.device.rules.selectDataType'), trigger: 'blur' }],
}))
const ruleForm = ref<any>({
	id: 0,
	productKey: '',
	deviceKey: '',
	name: '',
	key: '',
	transportProtocol: '',
	accessMode: 1,
	status: 1,
	valueType: JSON.parse(JSON.stringify(valueTypeModule)),
	desc: '',
})

const jsondata = ref<any>([])
const isShowDialog = ref(false)
const elementType = ref(JSON.parse(JSON.stringify(valueTypeModule)))
const valueType = ref(JSON.parse(JSON.stringify(valueTypeModule)))
const typeData = ref([])
const enumdata = ref([
	{
		text: '',
		value: '',
	},
])
const type = ref('')
const types = ref('')
const productKey = ref<any>('')

// 打开弹窗
const openDialog = (row: any, productKeys: string | null) => {
	resetForm()

	api.product.getDataType({ status: -1 }).then((res: any) => {
		const datat: any = Object.values(res.dataType)
		datat.forEach((item: any, index: any) => {
			if (index == 0) {
				datat[index]['label'] = t('message.device.baseType')
				datat[index]['options'] = item
			} else {
				datat[index]['label'] = t('message.device.extensionType')
				datat[index]['options'] = item
			}
		})
		typeData.value = datat || []
	})
	ruleForm.value = row
	if (row.valueType) {
		ruleForm.value = row

		productKey.value = productKeys
		// deviceKey.value = row.deviceKey
		valueType.value = row.valueType
		ruleForm.value.valueType.type = row.valueType.type
		ruleForm.value.type = row.valueType.type
		type.value = row.valueType.type
		ruleForm.value.accessMode = row.accessMode
		if (row.valueType.elementType) {
			elementType.value = row.valueType.elementType
			types.value = row.valueType.elementType.type
		}

		if (row.type == 'enum') {
			enumdata.value = row.valueType.elements
		}

		if (row.type == 'object') {
			jsondata.value = JSON.parse(JSON.stringify(row.valueType.properties))
		}

		if (row.type == 'array' && types.value == 'enum') {
			enumdata.value = row.valueType.elementType.elements
		}
		if (row.type == 'array' && types.value == 'object') {
			jsondata.value = JSON.parse(JSON.stringify(row.valueType.elementType.properties))
		}
	}

	isShowDialog.value = true
}
const resetForm = () => {
	ruleForm.value = {
		name: '',
		key: '',
		transportProtocol: '',
		accessMode: 1,
		status: 1,
		valueType: JSON.parse(JSON.stringify(valueType)),
		desc: '',
	}
	type.value = ''
	types.value = ''
	valueType.value = JSON.parse(JSON.stringify(valueType))
	elementType.value = JSON.parse(JSON.stringify(valueType))
	jsondata.value = []
	enumdata.value = [
		{
			text: '',
			value: '',
		},
	]
}

const seletChange = (val: string) => {
	type.value = val
	ruleForm.value.type = val
}
const seletChanges = (val: string) => {
	types.value = val
}

const addEnum = () => {
	enumdata.value.push({
		text: '',
		value: '',
	})
}
const delEnum = (index: number) => {
	enumdata.value.splice(index, 1)
}

const editjson = (index: number) => {
	editOptionRef.value.openDialog(jsondata.value[index])
}
const deljson = (index: number) => {
	jsondata.value.splice(index, 1)
}

const addJson = () => {
	editOptionRef.value.openDialog({ productKey: '', id: 0 })
}
const getOptionData = (data: any) => {
	jsondata.value.push(data)
}
// 关闭弹窗
const closeDialog = () => {
	isShowDialog.value = false
}
// 取消
const onCancel = () => {
	closeDialog()
}
// 新增
const onSubmit = () => {
	const formWrap = unref(formRef) as any
	if (!formWrap) return
	formWrap.validate((valid: boolean) => {
		if (valid) {
			if (ruleForm.value.id !== 0) {
				//修改
				if (type.value == 'enum') {
					valueType.value.elements = enumdata.value
				}

				if (type.value == 'object') {
					valueType.value.properties = jsondata.value
				}

				if (type.value == 'array') {
					valueType.value.elementType = elementType.value
					//如果是选中数组，并选择了枚举
					if (types.value == 'enum') {
						valueType.value.elementType = {
							elements: enumdata.value,
							type: 'enum',
						}
					}
					//如果是选中数组，并选择了object
					if (types.value == 'object') {
						valueType.value.elementType = {
							properties: jsondata.value,
							type: 'object',
						}
					}
				}

				ruleForm.value.valueType = valueType.value
				ruleForm.value.productKey = productKey.value
				api.model.propertyedit(ruleForm.value).then(() => {
					ElMessage.success(t('message.tableI18nConfirm.editSuccess'))
					closeDialog() // 关闭弹窗
					emit('typeList')
				})
			} else {
				//添加
				if (type.value == 'enum') {
					valueType.value.elements = enumdata.value
				}

				if (type.value == 'object') {
					valueType.value.properties = jsondata.value
				}

				if (type.value == 'array') {
					valueType.value.elementType = elementType.value
					//如果是选中数组，并选择了枚举
					if (types.value == 'enum') {
						valueType.value.elementType = {
							elements: enumdata.value,
							type: 'enum',
						}
					}
					//如果是选中数组，并选择了object
					if (types.value == 'object') {
						valueType.value.elementType = {
							properties: jsondata.value,
							type: 'object',
						}
					}
				}

				ruleForm.value.valueType = valueType.value
				api.model.propertyadd(ruleForm.value).then(() => {
					ElMessage.success(t('message.tableI18nConfirm.addSuccess'))
					closeDialog() // 关闭弹窗
					emit('typeList')
				})
			}
		}
	})
}

defineExpose({ openDialog })
</script>
<style scoped lang="scss">
.input-box {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	margin-top: 10px;
}

.input-option {
	line-height: 30px;
	padding-top: 5px;
	width: 140px;
}

.input-option i {
	margin: 0px 5px;
	border: 1px solid #c3c3c3;
	font-size: 16px;
}

.input-options {
	display: flex;
	align-items: center;
	color: #409eff;
	cursor: pointer;
}

.jslist {
	width: 100%;
	border: 1px solid #e8e8e8;
	padding: 10px;
	margin-bottom: 10px;
}

.jsonlist {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.jsonoption a {
	margin: 0px 10px;
}
</style>
