<template>
	<div class="system-edit-dic-container">
		<!-- 编辑标签定义/新增标签定义 -->
		<el-dialog :title="ruleForm.id !== 0 ? $t('message.device.dialogI18n.editTagDefinition') : $t('message.device.dialogI18n.addTagDefinition')" v-model="isShowDialog" width="769px">
			<el-form :model="ruleForm" ref="formRef" :rules="rules" label-width="120px">
				<!-- 标签定义标识 -->
				<el-form-item :label="$t('message.device.formI18nLabel.tagKey')" prop="key">
					<!-- 请输入标签定义标识 -->
					<el-input v-model="ruleForm.key" :placeholder="$t('message.device.formI18nPlaceholder.tagKey')" :disabled="ruleForm.id !== 0 ? true : false" />
				</el-form-item>
				<!-- 标签定义名称 -->
				<el-form-item :label="$t('message.device.formI18nLabel.tagName')" prop="name">
					<!-- 请输入标签定义名称 -->
					<el-input v-model="ruleForm.name" :placeholder="$t('message.device.formI18nPlaceholder.tagName')" />
				</el-form-item>

				<!-- 数据类型 -->
				<el-form-item :label="$t('message.device.formI18nLabel.dataType')" prop="type">
					<!-- 请选择数据类型 -->
					<el-select v-model="valueType.type" :placeholder="$t('message.device.formI18nPlaceholder.selectDataType')" @change="seletChange">
						<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>
				</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.inputPrecision')" />
				</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.enumValue')" 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>

				<!-- JSON对象 -->
				<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">
							<!-- 参数名称 -->
							<div>{{$t('message.device.formI18nLabel.jsonObject')}}：</div>
							<div style="width: 60%">{{ item.name }}</div>
							<div class="jsonoption">
								<!-- <el-link type="primary">编辑</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.enumValue')" 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>

				<!-- JSON对象 -->
				<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">
							<!-- 参数名称 -->
							<div>{{$t('message.device.formI18nLabel.parameterName')}}：</div>
							<div style="width: 60%">{{ item.name }}</div>
							<div class="jsonoption">
								<!-- 编辑 -->
								<el-link type="primary">{{ $t('message.tableI18nAction.edit') }}</el-link>
								<!-- 删除 -->
								<el-link type="primary">{{ $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>

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

				<!-- 是否只读 -->
				<el-form-item :label="$t('message.device.formI18nLabel.isReadOnly')" prop="accessMode">
					<el-radio-group v-model="ruleForm.accessMode">
						<!-- 只读 -->
						<el-radio :label="1">{{ $t('message.device.formI18nOption.readonly') }}</el-radio>
						<!-- 读写 -->
						<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.tagDescription')" prop="desc">
					<!-- 请输入标签定义描述 -->
					<el-input v-model="ruleForm.desc" type="textarea" :placeholder="$t('message.device.formI18nPlaceholder.tagDescription')"></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">
import { reactive, toRefs, defineComponent, ref, unref, computed } from 'vue';
import api from '/@/api/device';
import { Plus, Minus, Right } from '@element-plus/icons-vue';
import EditOption from './editOption.vue';
import { validateNoSpace } from '/@/utils/validator';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';

interface RuleFormState {
	id: number;
	productKey: string;
	accessMode: number;
	name: string;
	key: string;
	type: string;
	transportProtocol: string;
	dictType: string;
	valueType: any;
	status: number;
	desc: string;
}
interface DicState {
	isShowDialog: boolean;
	productKey: string;
	type: string;
	types: string;
	valueType: any;
	elementType: any;
	ruleForm: RuleFormState;
	jsondata: any;
	typeData: any[];
	enumdata: any[];
	// rules: {};
}

const ruleForm = {
	id: 0,
	productKey: '',
	name: '',
	dictType: '',
	type: '',
	key: '',
	transportProtocol: '',
	accessMode: 1,
	status: 1,
	valueType: {
		type: '',
		maxLength: '',
	},
	desc: '',
}

export default defineComponent({
	name: 'deviceEditPro',
	components: { Plus, Minus, Right, EditOption },
	setup(prop, { emit }) {
		const formRef = ref<HTMLElement | null>(null);
		const editOptionRef = ref();
		const { t, locale } = useI18n();
		const rules = computed(() => ({
			name: [
				// 标签定义名称不能为空
				{ required: true, message: t('message.device.rules.tagKeyName'), trigger: 'blur' },
				// 标签定义名称不能超过32个字符
				{ max: 32, message: t('message.device.rules.tagKeyMax32'), trigger: 'blur' },
				// 标签定义名称不能包含空格
				{ validator: validateNoSpace, message: t('message.device.rules.tagKeyValidator'), trigger: 'blur' }
			],
			// 标签定义标识不能为空
			key: [{ required: true, message: t('message.device.rules.tagKey'), trigger: 'blur' }],
			// 请选择是否只读
			accessMode: [{ required: true, message: t('message.device.rules.tagAccessMode'), trigger: 'blur' }],
			// 请选择数据类型
			type: [{ required: true, message: t('message.device.rules.tagType'), trigger: 'blur' }],
		}))
		const state = reactive<DicState>({
			isShowDialog: false,
			typeData: [], //
			type: '',
			types: '',
			productKey: '',
			valueType: {
				type: '',
				maxLength: '',
				trueText: '是',
				trueValue: true,
				falseText: '否',
				falseValue: false,
			},
			elementType: {
				type: '',
				maxLength: '',
			},
			enumdata: [
				{
					text: '',
					value: '',
				},
			],

			jsondata: [],

			ruleForm: JSON.parse(JSON.stringify(ruleForm)),

		});

		// 打开弹窗
		const openDialog = (row: RuleFormState, productKey: string) => {
			resetForm();

			api.product.getDataType({ status: -1 }).then((res: any) => {
				const datat = Object.values(res.dataType) as any[];
				datat.forEach((item, index) => {
					if (index == 0) {
						// 基础类型
						datat[index]['label'] = t('message.device.baseType');
						datat[index]['options'] = item;
					} else {
						// 扩展类型
						datat[index]['label'] = t('message.device.extendType');
						datat[index]['options'] = item;
					}
				});

				state.typeData = datat || [];
			});
			state.ruleForm = row;
			if (row.valueType) {
				state.ruleForm = row;

				state.productKey = productKey;
				state.valueType = row.valueType;
				state.ruleForm.valueType.type = row.valueType.type;
				state.ruleForm.type = row.valueType.type;
				state.type = row.valueType.type;
				state.ruleForm.accessMode = row.accessMode;
				if (row.valueType.elementType) {
					state.elementType = row.valueType.elementType;
					state.types = row.valueType.elementType.type;
				}

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

				if (row.type == 'object') {
					state.jsondata = row.valueType.properties;
				}

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

			state.isShowDialog = true;
		};
		const resetForm = () => {
			state.ruleForm = JSON.parse(JSON.stringify(ruleForm))
			state.type = '';
			state.types = '';
			state.valueType = {};
			state.elementType = {};
			state.jsondata = [];
			state.enumdata = [{
				text: '',
				value: '',
			},];
		};

		const seletChange = (val: string) => {
			state.type = val;
			state.ruleForm.type = val;

		};
		const seletChanges = (val: string) => {
			state.types = val;
		};

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

		const deljson = (index: number) => {
			state.jsondata.splice(index, 1);
		};

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

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

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

						api.model.tagedit(state.ruleForm).then(() => {
							// 标签定义类型修改成功
							ElMessage.success(t('message.tableI18nConfirm.editSuccess'));
							closeDialog(); // 关闭弹窗
							emit('typeList');
						});
					} else {
						//添加
						if (state.type == 'enum') {
							state.valueType.elements = state.enumdata;
						}

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

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

						state.ruleForm.valueType = state.valueType;
						api.model.tagadd(state.ruleForm).then(() => {
							// 标签定义类型添加成功
							ElMessage.success(t('message.tableI18nConfirm.addSuccess'));
							closeDialog(); // 关闭弹窗
							emit('typeList');
						});
					}
				}
			});
		};

		return {
			rules,
			editOptionRef,
			getOptionData,
			openDialog,
			deljson,
			addEnum,
			delEnum,
			addJson,
			seletChange,
			seletChanges,
			closeDialog,
			onCancel,
			onSubmit,
			formRef,
			...toRefs(state),
		};
	},
});
</script>
<style scoped>
.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 {}

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