﻿<template>
	<div class="mesEquipment-container">
		<el-dialog v-model="isShowDialog" :width="800" draggable="" :close-on-click-modal="false" :append-to-body="true" :fullscreen="fullScreen">
			<template #header>
				<div style="color: #fff; display: flex; align-items: center; justify-content: space-between">
					<span>{{ props.title }}</span>
					<el-icon size="16" @click="fullScreen = !fullScreen" style="margin-right: 16px; display: block; vertical-align: middle; cursor: pointer">
						<ele-FullScreen v-if="!fullScreen" />
						<ele-Notification v-else />
					</el-icon>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备编码" prop="equipmentCode">
							<el-input v-model="ruleForm.equipmentCode" placeholder="请输入设备编码" maxlength="100" :disabled="props.title.includes('编辑')" 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="equipmentName">
							<el-input v-model="ruleForm.equipmentName" placeholder="请输入设备名称" maxlength="100" 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="设备IP" prop="ip">
							<el-input v-model="ruleForm.ip" placeholder="请输入设备IP" maxlength="100" 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="getway">
							<el-input v-model="ruleForm.getway" placeholder="请输入设备网关" maxlength="100" 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="equipmentTypeCode">
							<el-cascader
								:options="mesEquipmentTypeTreeData"
								:props="{ checkStrictly: true, emitPath: false, value: 'equipmentTypeCode', label: 'equipmentTypeName' }"
								placeholder="请选择设备类别编码"
								clearable=""
								class="w100"
								v-model="ruleForm.equipmentTypeCode"
							>
								<template #default="{ node, data }">
									<span>{{ data.equipmentTypeName }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备型号" prop="model">
							<el-input v-model="ruleForm.model" placeholder="请输入设备型号" maxlength="100" 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="guar1">
							<el-select clearable v-model="ruleForm.guar1" placeholder="请选择一保">
								<el-option v-for="(item, index) in mesWorkTeamList" :key="index" :value="item.workTeamCode" :label="`[${item.workTeamCode}] ${item.workTeamName}`"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="二保" prop="guar2">
							<el-select clearable v-model="ruleForm.guar2" placeholder="请选择二保">
								<el-option v-for="(item, index) in mesWorkTeamList" :key="index" :value="item.workTeamCode" :label="`[${item.workTeamCode}] ${item.workTeamName}`"></el-option>
							</el-select>
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备制造商" prop="maker">
							<el-input v-model="ruleForm.maker" placeholder="请输入设备制造商" maxlength="300" 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="makeDate">
							<el-date-picker v-model="ruleForm.makeDate" type="date" placeholder="制造日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="使用日期" prop="useDate">
							<el-date-picker v-model="ruleForm.useDate" type="date" placeholder="使用日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否停用" prop="isStop">
							<el-switch v-model="ruleForm.isStop" active-text="是" inactive-text="否" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产线" prop="productionLineCode">
							<!--							<el-cascader-->
							<!--								:options="mesProductionLineTreeData"-->
							<!--								:props="{ checkStrictly: true, emitPath: false, value: 'productionLineCode', label: 'productionLineName' }"-->
							<!--								placeholder="请选择产线编码"-->
							<!--								clearable=""-->
							<!--								class="w100"-->
							<!--								v-model="ruleForm.productionLineCode"-->
							<!--							>-->
							<!--								<template #default="{ node, data }">-->
							<!--									<span>{{ data.name }}</span>-->
							<!--									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>-->
							<!--								</template>-->
							<!--							</el-cascader>-->
							<el-select clearable="" v-model="ruleForm.productionLineCode" placeholder="请选择产线">
								<el-option v-for="(item, index) in mesProductionLineTreeData" :key="index" :value="item?.productionLineCode" :label="`[${item?.productionLineCode}] ${item?.productionLineName}`" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否质保期" prop="isQa">
							<el-switch v-model="ruleForm.isQa" active-text="是" inactive-text="否" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备图片" prop="img">
							<el-upload list-type="picture-card" :show-file-list="false" :http-request="uploadImgHandle">
								<img v-if="ruleForm.img" :src="ruleForm.img" @click="ruleForm.img = ''" style="width: 100%; height: 100%; object-fit: contain" />
								<el-icon v-else><Plus /></el-icon>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="ruleForm.remark" placeholder="请输入备注" show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<!--      <el-tabs v-model="activeChild">-->
			<!--        <el-tab-pane label="设备工艺参数" name="params"></el-tab-pane>-->
			<!--        <el-tab-pane v-if="props.title.includes('编辑')" label="执行指令" name="instruction"></el-tab-pane>-->
			<!--      </el-tabs>-->
			<!-- <el-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn" v-show="activeChild == 'params'" >新增</el-button> -->
			<!--  设备工艺参数    -->
			<!--      <el-table :data="paramsTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'params'">-->
			<!--        <el-table-column type="index" label="序号" width="55" align="center" />-->
			<!--        <el-table-column prop="params" label="参数编码"  show-overflow-tooltip="" />-->
			<!--        <el-table-column prop="paramNames" label="参数名称"  show-overflow-tooltip="" />-->
			<!--        <el-table-column label="操作" width="140" align="center" fixed="right">-->
			<!--          <template #default="scope">-->
			<!--            <el-button icon="ele-Delete" size="small" type="primary"-->
			<!--                       @click="subDelete(scope.row, scope.$index)">-->
			<!--              删除 </el-button>-->
			<!--          </template>-->
			<!--        </el-table-column>-->
			<!--      </el-table>-->
			<!--   指令   -->
			<!--      <mes-equipment-command  ref="commandRef" v-if="props.title.includes('编辑')" v-show="activeChild == 'instruction'" :equipmentCode="ruleForm.equipmentCode" ></mes-equipment-command>-->
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { UploadRequestOptions } from 'element-plus';
import { uploadImg } from '/@/api/mes/mesEquipment';
import { addMesEquipment, updateMesEquipment, detailMesEquipment } from '/@/api/mes/mesEquipment';
import { pageMesWorkTeam } from '/@/api/mes/mesWorkTeam';
// import { getMesEquipmentTypeTree } from '/@/api/mes/mesEquipment';
import { getMesEquipmentTypeTree } from '/@/api/mes/mesEquipmentType';
import { pageMesProductionLine } from '/@/api/mes/mesProductionLine';
import ChoosePart from '/@/businessComponents/choosePart.vue';
//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const isShowDialog = ref(false);
const ruleForm = ref<any>({});
//自行添加其他规则
const rules = ref<FormRules>({
	equipmentCode: [{ required: true, message: '请输入设备编码！', trigger: 'blur' }],
	equipmentName: [{ required: true, message: '请输入设备名称！', trigger: 'blur' }],
	// ip: [{required: true, message: '请输入设备IP！', trigger: 'blur',},],
	// getway: [{required: true, message: '请输入设备网关！', trigger: 'blur',},],
	equipmentTypeCode: [{ required: true, message: '请选择设备类别编码！', trigger: 'change' }],
	// guar1: [{ required: true, message: '请选择一保！', trigger: 'change' }],
	// guar2: [{ required: true, message: '请选择二保！', trigger: 'change' }],
});
let fullScreen = ref(false);
const commandRef = ref();
// 打开弹窗
const openDialog = async (row: any) => {
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	paramsTableData.value = [];
	// instructionTableData.value = [];
	// 改用detail获取最新数据来编辑
	GetMesProductionLineTreeData();
	getMesEquipmentTypeTreeData();
	GetWorkTeamList();

	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id) {
		let obj = (await detailMesEquipment(rowData.id)).data.result;
		ruleForm.value = {
			...obj,
		};
		paramsTableData.value = (obj.params || '')
			.split(',')
			.filter((item) => item)
			.map((item, index) => {
				return {
					params: item || '',
					paramNames: (obj.paramNames || '').split(',').filter((item) => item)?.[index] || '',
				};
			});
	} else {
		ruleForm.value = rowData;
		paramsTableData.value = (row.params || '')
			.split(',')
			.filter((item) => item)
			.map((item, index) => {
				return {
					params: item || '',
					paramNames: (row.paramNames || '').split(',').filter((item) => item)?.[index] || '',
				};
			});
	}
	// console.log(commandRef.value.handleQuery)
	isShowDialog.value = true;
	nextTick(() => {
		commandRef.value.handleQuery();
	});
};

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

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

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = ruleForm.value;
			// 参数子表
			values.params = paramsTableData.value.map((item) => item.params).join(',');
			values.paramNames = paramsTableData.value.map((item) => item.paramNames).join(',');
			// 指令子表自维护不随父表保存
			//  .....
			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == '' || ruleForm.value.id == 0) {
				await addMesEquipment(values);
			} else {
				await updateMesEquipment(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: 'error',
			});
		}
	});
};

const mesEquipmentTypeTreeData = ref<any>([]);
const getMesEquipmentTypeTreeData = async () => {
	let list = await getMesEquipmentTypeTree();
	mesEquipmentTypeTreeData.value = list.data.result ?? [];
};

const mesProductionLineTreeData = ref([]);
const GetMesProductionLineTreeData = async () => {
	var res = await pageMesProductionLine({
		page: 1,
		pageSize: 99999,
	});
	mesProductionLineTreeData.value = res.data.result?.items ?? [];
	console.log(mesProductionLineTreeData.value);
};

const mesWorkTeamList = ref([]);
const GetWorkTeamList = async () => {
	let res = await pageMesWorkTeam({
		page: 1,
		pageSize: 99999,
	});
	mesWorkTeamList.value = res.data.result?.items ?? [];
};

const activeChild = ref('params');
// 子表
const paramsTableData = ref([]);
const instructionTableData = ref([]);

// 删除子表
const subDelete = (row: any, index: number) => {
	if (activeChild.value === 'params') {
		paramsTableData.value.splice(index, 1);
	}
	if (activeChild.value === 'instruction') {
		instructionTableData.value.splice(index, 1);
	}
};

const uploadImgHandle = async (options: UploadRequestOptions) => {
	const res = await uploadImg(options);
	ruleForm.value.img = res.data.result?.url;
};

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

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