﻿<template>
	<div class="mesWorkSite-container">
		<el-dialog v-model="isShowDialog" :width="800" draggable="" :close-on-click-modal="false" :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="workSiteCode">
							<el-input v-model="ruleForm.workSiteCode" placeholder="请输入工位编码" :readonly="isEditable" 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="workSiteName">
							<el-input v-model="ruleForm.workSiteName" 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="mesWorkStationCode">
							<!--							<el-input v-model="ruleForm.mesWorkStationCode" placeholder="请输入所属工站编码" maxlength="100" show-word-limit clearable />-->
							<el-cascader
								:options="mesWorkShopTypeTreeData"
								:props="{ checkStrictly: false, emitPath: false, value: 'code', label: 'code' }"
								placeholder="请选择所属工站"
								clearable=""
								class="w100"
								v-model="ruleForm.mesWorkStationCode"
                @change="getProductionLineCode"
							>
								<template #default="{ node, data }">
									<span>[{{data.code}}]{{ data.name }}</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="X坐标" prop="siteX">
							<el-input v-model="ruleForm.siteX" placeholder="请输入X坐标" 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="Y坐标" prop="siteY">
							<el-input v-model="ruleForm.siteY" placeholder="请输入Y坐标" 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="Z坐标" prop="siteZ">
							<el-input v-model="ruleForm.siteZ" placeholder="请输入Z坐标" 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="remark">
							<el-input v-model="ruleForm.remark" placeholder="请输入备注" 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="createOrgName">-->
					<!--							<el-input v-model="ruleForm.createOrgName" placeholder="请输入创建者部门名称" maxlength="64" show-word-limit clearable />-->
					<!--						</el-form-item>-->
					<!--					</el-col>-->
				</el-row>
			</el-form>
			<el-tabs v-model="activeChild">
				<el-tab-pane label="关联员工" name="staff"></el-tab-pane>
				<el-tab-pane label="关联设备" name="equipment"></el-tab-pane>
			</el-tabs>
			<el-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn">新增</el-button>
			<el-table :data="staffTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'staff'">
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="account" label="账号" show-overflow-tooltip="" />
				<el-table-column prop="realName" 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>
			<el-table :data="equipmentTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'equipment'">
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="equipmentCode" label="设备编码" show-overflow-tooltip="" />
				<el-table-column prop="equipmentName" 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>
			<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-user title="选择人员" ref="chooseUserRef" :is-any="true" @finish="onChooseFinish"></choose-user>
		<!--  设备选择组件  -->
		<choose-equipment title="选择设备" ref="chooseEquipmentRef" :is-any="true" @finish="onChooseFinish"></choose-equipment>
	</div>
</template>
<style scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted } 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 { addMesWorkSite, updateMesWorkSite, detailMesWorkSite } from '/@/api/mes/mesWorkSite';
import ChooseUser from '/@/businessComponents/chooseUser.vue';
import { getWorkShopTree } from '/@/api/mes/mesProductionLine';
import { updateworksit } from '/@/api/simple/mesVirtualPackLog';
import chooseEquipment from '/@/businessComponents/chooseEquipment.vue';
//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
});
  const productionLineCode = ref("")
  const getProductionLineCode = (value)=>{
    console.log(value)
    let current = flattenTree(mesWorkShopTypeTreeData.value[0]).find(item=>item.code == value);
    console.log(current)
    let line = flattenTree(mesWorkShopTypeTreeData.value[0]).filter(item=>item.sign == 3);
    console.log(line)
    let flag = false;
    line.forEach(item=>{
      let has = (item?.children || []).find(site=>site.code == value);
      if(has){
        flag = true;
        productionLineCode.value = item.code;
        console.log(productionLineCode.value);
      }
    })
    if(!flag){
      productionLineCode.value = ""
    }
  }

const flattenTree = (tree) => {
  let result = [];

  // 定义一个递归函数来遍历树
  function traverse(node) {
    // 首先，将当前节点添加到结果数组中
    if (node) {
      result.push(node);

      // 然后，如果存在children，遍历它们
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child));
        // 可选：如果你不需要原始树中的children属性，可以在这里删除它
        // delete node.children;
      }
    }
  }

  // 从根节点开始遍历
  traverse(tree);

  // 返回结果数组
  return result;
}
//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const isShowDialog = ref(false);
const ruleForm = ref<any>({});
//自行添加其他规则
const rules = ref<FormRules>({
	workSiteCode: [{ required: true, message: '请输入工位编码！', trigger: 'blur' }],
	workSiteName: [{ required: true, message: '请输入工位名称！', trigger: 'blur' }],
	mesWorkStationCode: [{ required: true, message: '请输入所属工站编码！', trigger: 'blur' }],
});
let fullScreen = ref(false);
const isEditable=ref(false);
// 打开弹窗
const openDialog = async (row: any) => {
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	activeChild.value = 'staff';
	staffTableData.value = [];
	equipmentTableData.value = [];
	// 改用detail获取最新数据来编辑
	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id) {
		let data = (await detailMesWorkSite(rowData.id)).data.result;
		ruleForm.value = data;
    getProductionLineCode(ruleForm.value.mesWorkStationCode);
		// 映射子表
		// -人员
		staffTableData.value = (data.personCodes || '')
			.split(',')
			.filter((item) => item)
			.map((item, index) => {
				return {
					account: item || '',
					realName: (data.personNames || '').split(',').filter((item) => item)?.[index] || '',
				};
			});
		// -设备
		equipmentTableData.value = (data.equipmentCodes || '')
			.split(',')
			.filter((item) => item)
			.map((item, index) => {
				return {
					equipmentCode: item || '',
					equipmentName: (data.equipmentNames || '').split(',').filter((item) => item)?.[index] || '',
				};
			});
	if(props.title=="编辑工位档案")
	{
		isEditable.value=true;
	}
	} else {
		ruleForm.value = rowData;
		isEditable.value=false;
	}
	
	
	
	isShowDialog.value = true;
};

// 关闭弹窗
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.personCodes = staffTableData.value.map((item: any) => item.account).join(',');
			values.personNames = staffTableData.value.map((item: any) => item.realName).join(',');
			// 设备绑定
			values.equipmentCodes = equipmentTableData.value.map((item: any) => item.equipmentCode).join(',');
			values.equipmentNames = equipmentTableData.value.map((item: any) => item.equipmentName).join(',');
			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == '' || ruleForm.value.id == 0) {
				await addMesWorkSite(values);
				onScanAccount("新增",values.workSiteCode,values.workSiteName);
			} else {
				await updateMesWorkSite(values);
				onScanAccount("修改",values.workSiteCode,values.workSiteName);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: 'error',
			});
		}
	});
};

const activeChild = ref('staff');
// 子表
const staffTableData = ref([]);
const equipmentTableData = ref([]);

const chooseUserRef = ref();
const chooseEquipmentRef = ref();
const subAdd = () => {
	if (activeChild.value === 'staff') {
    if(productionLineCode.value){
      chooseUserRef.value.openDialog({
        productionLineCode:productionLineCode.value
      });
    }else{
      chooseUserRef.value.openDialog({});
    }
	}
	if (activeChild.value === 'equipment') {
    if(productionLineCode.value){
      chooseEquipmentRef.value.openDialog({
        productionLineCode:productionLineCode.value
      });
    }else{
      chooseEquipmentRef.value.openDialog({});
    }
	}
};

// 删除子表
const subDelete = (row: any, index: number) => {
	if (activeChild.value === 'staff') {
		staffTableData.value.splice(index, 1);
	}
	if (activeChild.value === 'equipment') {
		equipmentTableData.value.splice(index, 1);
	}
};

const onChooseFinish = (data: any) => {
	console.log(data);
	if (activeChild.value === 'staff') {
		let list: any[] = (data?.rows || []).map((item: any) => ({
			...item,
			realName: item.realName,
			account: item.account,
		}));
		staffTableData.value.push(...list);
	}
	if (activeChild.value === 'equipment') {
		let list: any[] = (data?.rows || []).map((item: any) => ({
			...item,
			equipmentName: item.equipmentName,
			equipmentCode: item.equipmentCode,
		}));
		equipmentTableData.value.push(...list);
	}
};

const mesWorkShopTypeTreeData = ref<any>([]);
const getMesWorkShopTypeTreeData = async () => {
	let list = await getWorkShopTree(4);
	mesWorkShopTypeTreeData.value = list.data.result ?? [];
};
getMesWorkShopTypeTreeData();


//新增方法，添加工位时同时添加或修改仓库中对应工位信息
const onScanAccount = async (val:any,code:any,name:any) => {
	 var res = await updateworksit({ val:val,code:code,name:name });
	 let data = res.data.result || {};
	// state.ruleForm.people = data.account+"-"+data.realName;
	// state.ruleForm.peopleCode=undefined;
	// ElMessage.success('扫描成功');
};

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

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