﻿<template>
	<div class="mesEquipmentGroup-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备组编码" prop="equipmentGroupCode">
							<el-input v-model="state.ruleForm.equipmentGroupCode" placeholder="请输入设备组编码" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备组名称" prop="equipmentGroupName">
							<el-input v-model="state.ruleForm.equipmentGroupName" placeholder="请输入设备组名称" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>

					<el-col :span="24" class="mb20">
						<el-form-item label="设备" prop="equipmentCodes">
							<div><el-button type="primary" @click="subAdd">选择</el-button></div>
							<div style="margin-top: 6px;display: block;">
								<el-tag v-for="(tag,tagIdx) in equipmentList" :key="tag.equipmentCode" style="margin-right: 5px;" closable type="primary" @close="onRemoveMold(tag,tagIdx)"> [{{ tag.equipmentCode }}]{{ tag.equipmentName }} </el-tag>
							</div>
							<!-- <el-transfer
								v-model="state.ruleForm.equipmentCodes"
								:titles="['待选取', '已选取']"
								filterable
								filter-placeholder="搜索"
								:props="{
									key: 'value',
									label: 'displayLabel',
								}"
								:data="mesEquipmentEquipmentCodesDropdownList"
							>
							<template #default="{ option }">
          <span>[{{ option.value }}]{{ option.label }}</span>
        </template>
						</el-transfer> -->
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" type="textarea" maxlength="500" show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!--  设备选择组件  -->
	<choose-equipment title="选择设备" ref="chooseEquipmentRef" :is-any="true" @finish="onChooseFinish1"></choose-equipment>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { addMesEquipmentGroup, updateMesEquipmentGroup, detailMesEquipmentGroup } from '/@/api/mes/mesEquipmentGroup';
import { pageMesEquipmentGroup, deleteMesEquipmentGroup } from '/@/api/mes/mesEquipmentGroup';
import { getMesEquipmentEquipmentCodesDropdown } from '/@/api/mes/mesEquipmentGroup';
import chooseEquipment from '/@/businessComponents/chooseEquipment.vue';
import { formatDate } from '/@/utils/formatTime';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const state = reactive({
	isShowDialog: false,
	ruleForm: {} as any,
});

//自行添加其他规则
const rules = ref<FormRules>({
	equipmentGroupCode: [{ required: true, message: '请输入设备组编码！', trigger: 'blur' }],
});

// 页面加载时
onMounted(() => {});

// 打开弹窗
const openDialog = async (row: any) => {
	// state.ruleForm = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
	// getMesEquipmentEquipmentCodesDropdownList();
	equipmentList.value=[];

	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id){
		var res = (await detailMesEquipmentGroup(rowData.id)).data.result;
		var codes = res.equipmentCodes.split(",");
		var names = res.equipmentNames.split(",");

		codes.forEach((item, index) => {
			equipmentList.value.push({
				equipmentCode: item,
				equipmentName: names[index],
			});
		});
		state.ruleForm = res;
	}
	else state.ruleForm = rowData;
	state.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit('reloadTable');
	state.isShowDialog = false;
};


const chooseEquipmentRef = ref();
const subAdd = () => {
	chooseEquipmentRef.value.openDialog({});
};
const equipmentList = ref([]);
const onChooseFinish1 = (data: any) => {
	let list: any[] = (data?.rows || []).map((item: any) => ({
		equipmentName: item.equipmentName,
		equipmentCode: item.equipmentCode,
	}));
	list.forEach((el)=>{
		if(equipmentList.value.findIndex((u:any)=>u.equipmentCode==el.equipmentCode)==-1){
			equipmentList.value.push(el);
		}
	})
};
const onRemoveMold = (tag,tagIdx)=>{
	equipmentList.value.splice(tagIdx,1);
}

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = JSON.parse(JSON.stringify(state.ruleForm));

			var names = [];
			var codes = [];
			equipmentList.value.forEach((el) => {
				
					names.push(el.equipmentName);
					codes.push(el.equipmentCode);
			});
			values.equipmentCodes = codes.join(',');
			values.equipmentNames = names.join(',');
			if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == '' || state.ruleForm.id == 0) {
				await addMesEquipmentGroup(values);
			} else {
				await updateMesEquipmentGroup(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: 'error',
			});
		}
	});
};

const mesEquipmentEquipmentCodesDropdownList = ref<any>([]);
const getMesEquipmentEquipmentCodesDropdownList = async () => {
	let list = await getMesEquipmentEquipmentCodesDropdown();
	mesEquipmentEquipmentCodesDropdownList.value = list.data.result ?? [];
	
	mesEquipmentEquipmentCodesDropdownList.value.forEach(item => {
		item.displayLabel = `[${item.value}]: ${item.label}`;
		});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
