<template>
	<div>
		<el-container>
			<!-- 左侧树形结构 -->
			<!-- <el-scrollbar max-height="75vh"> -->

				<layout-sider :resize-directions="['right']" :width="220" style="margin-right: 10px">
					<div class="JKWTree-tree" style="height: 70vh;width:100vh" >
					  <h3>工单核验单维护</h3>
					  <el-tree :data="treeData" highlight-current @node-click="handleNodeClick"/>
					</div>
				</layout-sider>
			
			<!-- </el-scrollbar> -->

			<el-container>
				<el-main>
					<div class="gva-table-box">
						<!-- 按钮区域 -->
						<el-form>
							<el-form-item>
								<el-input v-model="searchInfo" placeholder="请输入工单编号"  style="width: 180px;"/>
								<el-button type="primary" :icon="Search" class="bt" @click="handleSearch"></el-button>
								<el-button type="primary" class="bt" icon="plus" @click="handleShowAdd">新增</el-button>
								<el-button type="primary" icon="copy-document" class="bt"@click="dialogMrhjtj = true">每日核检统计</el-button>
								<el-button type="primary" icon="copy-document" class="bt" @click="showGdzjfptj">工单质检废品统计</el-button>
								<el-button type="primary" icon="edit"   @click="gdlcdcxconlick"    class="bt" title="流程单查询">流程单查询</el-button>
								<el-button type="primary" icon="delete" class="bt" @click="handleDelete">删除</el-button>
							</el-form-item>
						</el-form>
						<!-- 数据展示 -->
						<el-table ref="table" style="width: 100%;height: 62vh;" :data="tableData" row-key="ID" 
							@row-click="handleSelectChange"
							highlight-current-row="true"
							border  
							:row-style="{ height: '20px' }"  :header-cell-style="{ padding: '0px' }"
							:cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
							:show-overflow-tooltip="true"
							@row-dblclick="doubleClick">
							<!-- 循环渲染表格列 -->
							<el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop"
								:label="column.label" :width="column.width"  />

						</el-table>
						<!-- 分页 -->
						<div class="gva-pagination">
							<el-pagination v-model:current-page="page" v-model:page-size="limit"
								layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 30, 50, 100]"
								:total="total" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
						</div>
					</div>

					<!-- 弹出框 -->
					<!-- <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type" destroy-on-close
						width="1200px" style="margin-top: 0%;height: 100%;;"> -->
					<el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type" destroy-on-close
						width="1200px" style="margin-top: 2%;height: 80%;">
						<el-form ref="elFormRef" :model="detailData" inline label-position="right" :rules="rule"
							id="detail-form" label-width="70px">
							<el-row :gutter="24">
								<el-col :span="5">
									<el-form-item label="日期">
										<el-input type="date" max="9999-12-31" v-model="detailData.qczl_rq" id = '日期' @keydown="ent1($event)" @focus="rqHandleFocus()"
											style="width: 150px;" />
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="工单编号">
										<el-input v-model="detailData.qczl_gdbh" style="width: 120px;" @keydown="ent1($event)"
											@blur="handleGdbhEnter" placeholder="Enter回车" />
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="拼印主工单" label-width="90px">
										<el-input v-model="detailData.qczl_Pygd" style="width: 120px;" @keydown="ent1($event)" />
									</el-form-item>
								</el-col>
								<el-col :span="9">
									<el-form-item label="产品名称">
										<el-input v-model="detailData.Gd_cpmc" style="width: 300px;" disabled />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="5">
									<el-form-item label="印件号">
										<el-input v-model="detailData.qczl_yjno" style="width: 150px;" disabled/>
									</el-form-item>
								</el-col>
								<el-col :span="10">
									<el-form-item label="印件名称" >
										<el-input v-model="detailData.yj_yjmc" style="width: 385px;" disabled/>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="废品总数">
										<el-input v-model="detailData.qczl_fp"  @keydown="ent1($event)" style="width: 100px;" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="5">
									<el-form-item label="工序">
										<el-input v-model="detailData.qczl_gxmc" style="width: 150px;"
											@keydown="ent1($event,index,row,'工序')" />
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="工序号">
										<el-input v-model="detailData.qczl_gxh" @keydown="ent1($event)" id="工序号" style="width: 120px;" />
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="总流程号" label-width="90px">
										<el-input v-model="detailData.total_liucheng" @keydown="ent1($event)" style="width: 120px;" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="15">
									<el-form-item label="流程单号">
										<el-input v-model="detailData.qczl_num" id='qczl_num' @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc1" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc2" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc3" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc4" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc5" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc6" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc7" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
										<el-input v-model="detailData.qczl_NumDesc8" @keydown="ent1($event,index,row,'流程单号')" style="width: 60px; margin-right: 5px;" />
									</el-form-item>
								</el-col>
								<el-col :span="9">
									<el-form-item label="备注">
										<el-input v-model="detailData.qczl_NumDesc" @keydown="ent1($event)" style="width: 300px;" />
									</el-form-item>
								</el-col>
							</el-row>

							<el-scrollbar height="400px">
								<el-table :data="detailData.table" border tooltip-effect="dark"
									:row-style="{ height: '20px' }" :cell-style="{ padding: '0px' }"
									:header-row-style="{ height: '20px' }" :header-cell-style="{ padding: '0px' }">
									<el-table-column label="废品类别" width="200">
										<template #default="{ row, $index }">
											<el-input v-model="row.fp_lb" @keydown="ent1($event,$index,row,'废品类别')"   />
										</template>
									</el-table-column>
									<el-table-column label="数量" width="100">
										<template #default="{ row, $index }">
											<el-input v-model="row.fp_sl" @keydown="ent1($event,$index,row,'数量')" @input="countEnter($index, row)"/>
										</template>
									</el-table-column>
									<el-table-column label="工序及责任机长" >
										<template #default="{ row, $index }">
											<el-input v-model="row.fp_gxmc" @keydown="ent1($event,$index,row,'工序及责任机长')"/>
										</template>
									</el-table-column>
									<el-table-column label="" width="100">
										<template #default="{ row }">
											<el-input v-model="row.fp_bz" @keydown="ent1($event,$index,row,'')" readonly/>
										</template>
									</el-table-column>
									<el-table-column label="" width="100">
										<template #default="{ row }">
											<el-input v-model="row.fp_bh" @keydown="ent1($event,$index,row,'')" readonly/>
										</template>
									</el-table-column>
									<el-table-column label="" width="100">
										<template #default="{ row }">
											<el-input v-model="row.fp_name" @keydown="ent1($event,$index,row,'')" readonly/>
										</template>
									</el-table-column>
								</el-table>
							</el-scrollbar>
						</el-form>
						<template #footer>
							<div class="dialog-footer">
								<el-button @click="closeDialog">取 消</el-button>
								<el-button type="primary" @click="enterDialog">确 定
								</el-button>
							</div>
						</template>
					</el-dialog>

					<!-- 废品类别弹出 -->
					<el-dialog v-model="dialogSelectVisible1" id="tableFplb" @keydown="ent($event)" style="margin-top: 5%;"  >
						<el-form>
								<el-form-item label="废品类别" class="mab" prop="keyOrder"></el-form-item>
								<div style="border:1px solid #eee; width:100%; height: 600px; overflow-y: auto;">
									<el-tree :data="selecTreeData" ref="table_fplb" 
										@keydown="handleTreeKeydown" 
										:props="{ children: 'children',label: 'label'}"
										node-key="id" @node-click="handleFplbClick">
									</el-tree>
								</div>
						</el-form>
					</el-dialog>

					<!-- 弹出选项框 数量 -->
					<el-dialog v-model="dialogSelectVisible2" title="数量选择" destroy-on-close width="900px" style="margin-top: 3%;" @keydown="selectSL($event)">
					    <el-table tooltip-effect="dark" :data="selectData" row-key="ID" highlight-current-row border style="width:100%" @row-dblclick="handleSelectClick" ref="table2">
					        <el-table-column v-for="column in selectColumns" :key="column.prop" :prop="column.prop" :label="column.label" :width="column.width" />
					    </el-table>
					</el-dialog>

					<!--流程单查询【弹窗】-->
					<el-dialog v-model="gd_lcdlist" title="工单工序生产进程" style="width: 100%;height: 100%;margin: 0px;padding: 0px;">
						<div style="width: 100%;height: 100%;">
						<el-button type="" @click="gd_lcdCancel">退出</el-button>
						</div>
						<div style="width: 100%; height: 100%; display: flex; align-items: center;">
						<el-form-item label="工单编号" style="margin-right: 20px; padding: 0;">
							<el-input v-model="gd_lcdformData['gdbh']" @keyup.enter="gd_lcdProductValue"/>
						</el-form-item>
						<el-form-item label="印件号" style="margin-right: 20px; padding: 0;">
							<el-input v-model="gd_lcdformData['yjno']" @keyup.enter="gd_lcdProductValue"/>
						</el-form-item>
						<el-form-item label="" style="margin-right: 5px; padding: 0;">
							<el-input v-model="gd_lcdformData['code']" disabled/>
						</el-form-item>
						<el-form-item label="" style="margin-right: 5px; padding: 0;">
							<el-input v-model="gd_lcdformData['name']" disabled style="width: 500px"/>
						</el-form-item>
						</div>
						<div style="width: 100%; height: 70vh; display: flex;">
						<layout>
							<layout-sider :resize-directions="['right']" :width="240" style="margin-right: 10px;height: 70vh;">
							<div class="JKWTree-tree">
								<el-tree :data="lcd_treeData" @node-click="lcd_handleNodeClick" default-expand-all></el-tree>
							</div>
							</layout-sider>
							<layout-main>
							<!-- 这里放右侧的内容 -->
							<div style="display: flex; align-items: center;margin-left: 20px;">
								<el-tag type="success" style="width: 55px; height: 40px; margin-right: 10px;"><h2>流程号</h2></el-tag>
								<h2 style="margin: 0 20px 0 0;">绿格子图标表示“已完成”</h2>
								<el-tag type="danger" style="width: 55px; height: 40px; margin-right: 10px;"><h2>流程号</h2></el-tag>
								<h2 style="margin: 0;">红格子图标表示“未完成”</h2>
							</div>
							<br>
							 <el-space wrap style="margin-left: 20px;">
								<!-- 右侧内容 -->
								<template v-for="item in processList.total_process">
									<el-button  class="custom-button" disabled :type="! processList.process.includes(item) ? 'danger' : 'info'" plain style="width: 50px;">{{ item }}</el-button>
								<!-- <el-button disabled :type="! processList.process.includes(item) ? 'danger' : 'info'" plain style="width: 50px">{{ item }}</el-button> -->
								</template>
							</el-space>
							</layout-main>
						</layout>
						</div>
          			</el-dialog>

					<!-- 弹出选项框 工单 -->
					<el-dialog v-model="dialogSelectVisible" title="选择" destroy-on-close width="1000px"
						@keydown="selectGX($event)">
						<el-table tooltip-effect="dark" :data="selectData_gd" row-key="ID" highlight-current-row="true"
							border style="width:100%" @row-dblclick="handleSelectClick_gd" ref="table_gd">
							<el-table-column prop="Gd_cpmc" label="工单名称" width="430" />
							<el-table-column prop="yj_Yjno" label="印件号" width="100" />
							<el-table-column prop="yj_yjmc" label="印件名称" width="430" />
						</el-table>
					</el-dialog>
					
					<!-- 弹出选项框 工序 -->
					<el-dialog v-model="dialogSelectVisible_gx" title="工序选择" destroy-on-close width="600px" 
						@keydown="select_gx($event)">
						<el-table tooltip-effect="dark" :data="selectData_gx" row-key="ID" highlight-current-row="true"
							border style="width:100%" @row-dblclick="handleSelectClick_gx" ref="table_gx">
							<el-table-column prop="gxh" label="工序号" width="100" />
							<el-table-column prop="gxmc" label="工序名称" width="460" />
						</el-table>
					</el-dialog>
					
					
					      <el-dialog v-model="dialogbutton" title="是否确认"
						   @keydown="handleKeydown ($event)"
						   destroy-on-close width="300px" style="height: 140px; margin-top: 20%;">
							  <br>
					        <span slot="footer" class="dialog-footer" style="display: flex; justify-content: space-between; align-items: center; padding: 0 20px;">
							  <el-button @click="dialogbutton = false">取消</el-button>
							  <el-button type="primary" @click="enterDialog">确 定
							  </el-button>
					        </span>
					      </el-dialog>



					<!-- 废品日统计 -->
					<Meirihejiantongji v-if="dialogMrhjtj" v-model="dialogMrhjtj" />

					<!-- 工单质检废品统计 -->
					<Gongdanzhijianfeipintongji v-if="dialogGdzjfptj" v-model="dialogGdzjfptj" :val="value1" />

					<!-- 测试图表 -->
					<Shebeizhuangtai v-if="dialogSbyxgl" v-model="dialogSbyxgl"
						title="【01.30 08:30】【JY01#--海德堡对开八色平版胶印机(JY08-01)】【2311116-->钻石(荷花）盒包装纸】【01--胶印】" />

				</el-main>
			</el-container>
		</el-container>

	</div>
</template>

<script setup>
	// 全量引入格式化工具 请按需保留
	import {createCompany,deleteCompany,deleteCompanyByIds,updateCompany,findCompany,getCompanyList} from '@/api/company'
	import {ElMessage,ElMessageBox,} from 'element-plus'
	import {Search,Refresh,Download} from '@element-plus/icons-vue'
	import {ref,reactive,nextTick} from 'vue'
	import {getOrderProcessLeft,getOrderProcessRight} from "@/api/yunyin/yunying";
	import {getSide,getTable,getOneWorkOrder,getOrderInfo,getGxAndLeader,getYjInfo,getWastInfo,updateData,add,del} from '@/api/mes_api_gty/workOrderVerification'
	import Meirihejiantongji from '@/view/performance/09-workOrderVerification/componets/meirihejiantongji.vue'
	import Gongdanzhijianfeipintongji from '@/view/performance/09-workOrderVerification/componets/gongdanzhijianfeipintongji.vue'
	import Shebeizhuangtai from '@/view/performance/09-workOrderVerification/componets/shebeizhuangtai.vue'
	import {Layout,LayoutContent,LayoutHeader,LayoutSider} from '@arco-design/web-vue'
	import {useUserStore} from '@/pinia/modules/user'
	const userStore = useUserStore()
	const sys_id = '[' + userStore.userInfo.userName + '/' + userStore.userInfo.nickName + ']'
	defineOptions({name: '06PackingDocuments'})

	// 侧边栏数据请求
	const treeData = reactive([])
	const getSideData = async () => {
		const response = await getSide()
		if (response.code === 0) {
			const transformedData = response.data.map(item => ({
				label: `${item.date.replace(/-/g, '.')}【单据数: ${item.counts}张】`,
				children: item.sys.map(sysItem => ({
					label: `${sysItem.sys_id} 【记录数: ${sysItem.count}张】`,
					params: {
						date: item.date.replace(/\./g, '-'),
						sys_id: sysItem.sys_id,
					},
				})),
			}))
			treeData.splice(0, treeData.length, ...transformedData)
		}
	}
	getSideData()

	// 验证规则
	const rule = reactive({})
	const elFormRef = ref()
	const elSearchFormRef = ref()

	// =========== 表格控制部分 ===========
	const tableColumns = [
		{label: '工单编号',		prop: 'qczl_gdbh',		width: '100'},
		{label: '印件号',		prop: 'qczl_yjno',		width: '70'},
		{label: '印件名称',		prop: 'Gd_cpmc',		width: '400'},
		{label: '日期',			prop: 'qczl_rq',		width: '100'},
		{label: '流程单号',		prop: 'qczl_num',		width: '100'},
		{label: '流程单备注',	prop: 'qczl_NumDesc',	width: '120'},
		{label: '总废品',		prop: 'qczl_fp',		width: '100'},
		{label: '废品1',			prop: 'sl_lb1',			width: '250'},
		{label: '废品2',			prop: 'sl_lb2',			width: '250'},
		{label: '废品3',			prop: 'sl_lb3',			width: '250'},
		{label: '废品4',			prop: 'sl_lb4',			width: '250'},
		{label: '废品5',			prop: 'sl_lb5',			width: '250'},
		{label: '废品6',			prop: 'sl_lb6',			width: '250'},
		{label: '废品7',			prop: 'sl_lb7',			width: '250'},
		{label: '废品8',			prop: 'sl_lb8',			width: '250'},
		{label: '废品9',			prop: 'sl_lb9',			width: '250'},
		{label: '废品10',		prop: 'sl_lb10',		width: '250'},
		{label: '废品11',		prop: 'sl_lb11',		width: '250'},
		{label: '废品12',		prop: 'sl_lb12',		width: '250'},
		{label: '废品13',		prop: 'sl_lb13',		width: '250'},
		{label: '废品14',		prop: 'sl_lb14',		width: '250'},
		{label: '废品15',		prop: 'sl_lb15',		width: '250'},
		{label: '废品16',		prop: 'sl_lb16',		width: '250'},
		{label: '废品17',		prop: 'sl_lb17',		width: '250'},
		{label: '创建用户',		prop: 'sys_id',			width: '160'},
	]
	const tableData = reactive([])
	const total = ref(0)
	const page = ref(1)
	const limit = ref(10)
	const searchInfo = ref('')
	const params = {
		date: '',
		sys_id: '',
		order: '',
		page: page.value.toString(),
		limit: limit.value.toString(),
	}
	
	// 工序弹窗选择控制
	const dialogSelectVisible_gx = ref(false)
	const selectData_gx = reactive([])
	const handleSelectClick_gx = (row, column, event) => {
		const { gxh, gxmc } = row
		detailData.qczl_gxmc = gxh + '-' + gxmc
		detailData.qczl_gxh = gxh
		dialogSelectVisible_gx.value = false
	}
	const currentIndex_gx = ref(0);
	const current_gx = ref(0);
	const select_gx = (event) => {
		if (event.keyCode === 40) { // 向下箭头
			if (currentIndex_gx.value < selectData_gx.length - 1) {
				currentIndex_gx.value++;
				setCurrent_gx(selectData_gx[currentIndex_gx.value]);
			} else {
				currentIndex_gx.value = 0;
				setCurrent_gx(selectData_gx[currentIndex_gx.value]); // 到达最后一行时回到第一行			
			}
		} else if (event.keyCode === 38) { // 向上箭头
			if (currentIndex_gx.value > 0) {
				currentIndex_gx.value--;
				setCurrent_gx(selectData_gx[currentIndex_gx.value]);
			} else {
				currentIndex_gx.value = selectData_gx.length - 1;
				setCurrent_gx(selectData_gx[currentIndex_gx.value]); // 到达第一行时回到最后一行
			}
		} else if (event.keyCode === 13) { // 回车键
			dialogSelectVisible_gx.value = false;
			setTimeout(() => {
					const inputElement = document.getElementById('工序号');
						if (inputElement) {
							inputElement.focus();		
						}
			}, 100);
			
	// 获取工序
	const getgxsubmit = () => {
		if(!detailData.qczl_gdbh || !detailData.qczl_yjno){
			return
		}
		GetJtbh()
	}
	const GetJtbh = async () => {
		const { qczl_gdbh, qczl_yjno } = detailData
		const response = await getYjInfo({ order: qczl_gdbh, yj_no: qczl_yjno })
		if (response.code === 0) {
			const data = response.data
			if (data) {
				detailData.total_liucheng = data.max_num
				const tableData = data.gx_data.map(item => ({
					gxh: item.Gy0_gxh,
					gxmc: item.Gy0_gxmc + (item.Add_gxmc === '' ? '' : '-' + item.Add_gxmc),
					// addGxmc: item.Add_gxmc
				}))
				selectData_gx.splice(0, selectData_gx.length, ...tableData)
				setCurrent_gx(selectData_gx[0])
				dialogSelectVisible_gx.value = true
			}
		}
	}
		}
	}
	const table_gx = ref()
	const setCurrent_gx = (row) => {
		setTimeout(() => {
			table_gx.value?.setCurrentRow(row)
			const { gxh, gxmc } = row
			detailData.qczl_gxmc = gxh + '-' + gxmc
			detailData.qczl_gxh = gxh
		})
	}
	
	// 批量删除控制标记
	const deleteVisible = ref(false)
	const multipleSelection = ref([])
	const getTableData = async () => {
		const response = await getTable(params)
		if (response.code === 0) {
			total.value = response.data.total
			// Object.assign(tableData, response.data.rows)

			tableData.splice(0, tableData.length, ...response.data.rows)
		}
	}

	// 左侧树结构点击
	const handleNodeClick = (node, check) => {
		if (node.params) {
			params.date = node.params.date
			params.sys_id = node.params.sys_id
			page.value = 1
			handleCurrentChange()
		}
	}

	// =========== 流程单查询 ===========
const gd_lcdlist = ref(false);
const gd_lcdformData = reactive({
  gdbh: '',
  code: '',
  name: '',
});
// 流程单查询按钮
const processList = ref([]);
const gdlcdcxconlick = async () => {
	// console.log(lcdyjno.value)
  if(currentRow.gdbh === '' || currentRow.gdbh === null || currentRow.gdbh === undefined){
    ElMessage({type: 'warning',message: '请选择具体的工单，在进行操作'})
    return false;
  }else{
    gd_lcdformData['gdbh'] = currentRow.gdbh;
	gd_lcdformData['yjno'] = lcdyjno.value
    _getOrderProcessLeft_list();
    gd_lcdlist.value = true;
    processList.value = []
  }
}
//流程单查询回车
const gd_lcdProductValue = async () => {
  if(gd_lcdformData['gdbh'] == '' || gd_lcdformData['gdbh'] === null){
    ElMessage({type: 'warning',message: '工单编号为空'})
    return false;
  }
  _getOrderProcessLeft_list();
}

const lcd_treeData = ref([]);
const _getOrderProcessLeft_list = async () => {
  const order = gd_lcdformData['gdbh'];
  const yjno = gd_lcdformData['yjno']
  try {
    //5.1流程单查询-工单工序生产进程菜单栏
    const getOrderProcessLeft_list = await getOrderProcessLeft({ order:order,yjno:yjno});
    console.log(getOrderProcessLeft_list)	
    if(getOrderProcessLeft_list.data.Gd_info === null || getOrderProcessLeft_list.data.Gd_info === ''){
      ElMessage({type: 'warning',message: '未查询到具体工单信息'})
      lcd_treeData.value = [];
      return false;
    }
    gd_lcdformData['code'] = getOrderProcessLeft_list.data.Gd_info['code'];
    gd_lcdformData['name'] = getOrderProcessLeft_list.data.Gd_info['name'];
    lcd_treeData.value = [{
      label: order + '-' + getOrderProcessLeft_list.data.Gd_info['name'],
      // label: getOrderProcessLeft_list.data.Gd_info['code'] + '-' + getOrderProcessLeft_list.data.Gd_info['name'],
      value: undefined,
      children: []
    }]
    const newData = [];
    for (let key in getOrderProcessLeft_list.data.Gy_info) {
      let temp = getOrderProcessLeft_list.data.Gy_info[key];
      let concatenatedValue = `${temp.Gy0_yjno}-${temp.Gy0_gxh} ---> ${temp.Gy0_gxmc}`;
      newData.push({ label: concatenatedValue,value: temp.Gy0_gxh });
    }
    lcd_treeData.value[0].children = newData;
    //5.2流程单查询-获取工单工序生产进程右侧【接口】【进入页面默认显示第一个数据】
    const getOrderProcessRight_list = await getOrderProcessRight({order: order, gxNo:newData[0].value,yjno:yjno});
    processList.value = getOrderProcessRight_list.data
  } catch (error) {
    console.error(error);
  }
};
//点击左侧获取工序显示右侧数据
const lcd_handleNodeClick = async (node) => {
  if (node.value === undefined || node.value === null){
      return false;
  }
  const order = gd_lcdformData['gdbh'];
  const yjno = gd_lcdformData['yjno'];
  //5.2流程单查询-获取工单工序生产进程右侧【接口】
  const getOrderProcessRight_list = await getOrderProcessRight({order:order, gxNo:node.value,yjno:yjno});
  processList.value = getOrderProcessRight_list.data

};

// 流程单查询退出
const gd_lcdCancel = async () => {
  gd_lcdlist.value = false;
}



	// 搜索
	function handleSearch() {
		params.sys_id = ''
		params.date = ''
		params.order = searchInfo.value
		page.value = 1
		handleCurrentChange()
	}

	// 分页
	const handleSizeChange = () => {
		params.limit = limit.value.toString()
		getTableData()
	}

	// 页面跳转
	const handleCurrentChange = () => {
		params.page = page.value.toString()
		getTableData()
	}

	const detailData = reactive({})
	// ============== 详情页面 ==============
	const selectColumns = [{
			label: '',
			prop: 'sczl_gxmc',
			width: '500'
		},
		{
			label: '',
			prop: 'sczl_bzdh',
			width: '100'
		},
		{
			label: '',
			prop: 'sczl_bh1',
			width: '100'
		},
		{
			label: '',
			prop: 'name',
			width: '150'
		},
	]
	// 行为控制标记（弹窗内部需要增还是改）
	const type = ref('')

	// 弹窗控制标记
	const dialogFormVisible = ref(false)
	const dialogSelectVisible2 = ref(false)


	const getDetailData = async (id) => {
		try {
			const res = await getOneWorkOrder({ UniqId: id })
			if (res.code === 0) {
				const obj = res.data
				// 裁剪返回数据的前后空格
				for (const key in obj) {
					if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'string') {
						obj[key] = obj[key].trim()
					}
				}
				// 修改日期格式
				if (Object.prototype.hasOwnProperty.call(obj, 'qczl_rq') && typeof obj['qczl_rq'] === 'string') {
					obj['qczl_rq'] = obj['qczl_rq'].split(' ')[0]
				}

				Object.assign(detailData, obj)
				const table = []

				// 循环13行数据
				for (let i = 1; i <= 13; i++) {
					table.push({
						fp_lb: detailData[`fp_lb${i}`] || '',
						fp_sl: detailData[`fp_sl${i}`] || '',
						fp_gxmc: detailData[`fp_gxmc${i}`] || '',
						fp_bz: detailData[`fp_bz${i}`] || '',
						fp_bh: detailData[`fp_bh${i}`] || '',
						fp_name: detailData[`fp_name${i}`] || '',
					})
					// 从原对象中删除这些属性
					delete detailData[`fp_lb${i}`]
					delete detailData[`fp_sl${i}`]
					delete detailData[`fp_gxmc${i}`]
					delete detailData[`fp_bz${i}`]
					delete detailData[`fp_bh${i}`]
					delete detailData[`fp_name${i}`]
				}
				detailData.table = table
				getOrderInfo({ order: detailData.qczl_gdbh }).then(resposne => {
					if (resposne.code === 0) {
						//循环resposne.data当子项yj_Yjno的值等于obj中的qczl_yjno的值时设置detailData.Gd_cpmc的值为res.data[i].Gd_cpmc
						for (let i = 0; i < resposne.data.length; i++) {
							if (resposne.data[i].yj_Yjno == detailData.qczl_yjno) {
								detailData.yj_yjmc = resposne.data[i].yj_yjmc
								detailData.Gd_cpmc = resposne.data[i].Gd_cpmc
							}
						}
						showDialog()
					}
				})
			}
		} catch (e) {
			console.log(e)
		}
	}
	
	//日期获得焦点事件
	const rqHandleFocus = () => {
		if (detailData.qczl_rq == undefined || detailData.qczl_rq == '') {
			detailData.qczl_rq = new Date().toISOString().split('T')[0]
		}
	}

	// 工单编号回车
	const handleGdbhEnter = async () => {
		if (detailData.qczl_gdbh != undefined) {
			const res = await getOrderInfo({
				order: detailData.qczl_gdbh
			})
			if (res.code === 0) {
				if (res.data.length == 0) {
					ElMessage({
						type: 'error',
						message: '查无此编号的工单，请仔细检查后重新输入'
					})
					//设置输入框的值为空
					detailData.Gd_cpmc = ''
					detailData.qczl_yjno = ''
					detailData.yj_yjmc = ''
				} else if (res.data.length == 1) {
					detailData.Gd_cpmc = res.data[0]['Gd_cpmc']
					detailData.qczl_yjno = res.data[0]['yj_Yjno']
					detailData.yj_yjmc = res.data[0]['yj_yjmc']
				} else if (res.data.length > 1) {
					selectData_gd.splice(0, selectData_gd.length, ...res.data)
					setGXCurrent(selectData_gd[0])
					dialogSelectVisible.value = true
				}

			}
		} else {
			detailData.Gd_cpmc = ''
			detailData.qczl_yjno = ''
			detailData.yj_yjmc = ''
		}

	}
	const dialogSelectVisible = ref(false)
	const selectData_gd = reactive([])
	// 处理选择框
	const handleSelectClick_gd = (row, column, event) => {
		detailData.Gd_cpmc = row.Gd_cpmc
		detailData.qczl_yjno = row.yj_Yjno
		detailData.yj_yjmc = row.yj_yjmc
		dialogSelectVisible.value = false
	}
	const currentIndex = ref(0);
	const GXCurrent = ref(0);
	const selectGX = (event) => {
		if (event.keyCode === 40) { // 向下箭头
			if (currentIndex.value < selectData_gd.length - 1) {
				currentIndex.value++;
				setGXCurrent(selectData_gd[currentIndex.value]);
			} else {
				currentIndex.value = 0;
				setGXCurrent(selectData_gd[currentIndex.value]); // 到达最后一行时回到第一行			
			}
		} else if (event.keyCode === 38) { // 向上箭头
			if (currentIndex.value > 0) {
				currentIndex.value--;
				setGXCurrent(selectData_gd[currentIndex.value]);
			} else {
				currentIndex.value = selectData_gd.length - 1;
				setGXCurrent(selectData_gd[currentIndex.value]); // 到达第一行时回到最后一行
			}
		} else if (event.keyCode === 13) { // 回车键
			dialogSelectVisible.value = false;
		}
	}
	const table_gd = ref()
	const setGXCurrent = (row) => {
		setTimeout(() => {
			table_gd.value?.setCurrentRow(row)
			detailData.Gd_cpmc = row.Gd_cpmc
			detailData.qczl_yjno = row.yj_Yjno
			detailData.yj_yjmc = row.yj_yjmc
		})
	}

	// 解译HTML实体编码的函数
	function decodeEntities(encodedString) {
		const textArea = document.createElement('textarea')
		textArea.innerHTML = encodedString
		return textArea.value
	}
	// 双击表格操作
	function doubleClick(row, column, event) {
		type.value = '修改工单核验单维护'
		getDetailData(row.UniqId)
	}

	// 处理选择框回车操作
	const handleSelectClick = (row, column, event) => {
		const {
			sczl_gxmc,
			sczl_bzdh,
			sczl_bh1,
			name
		} = row
		const index = selectIndex
		console.log("index",index);
		detailData.table[index].fp_gxmc = sczl_gxmc
		detailData.table[index].fp_bz = sczl_bzdh
		detailData.table[index].fp_bh = sczl_bh1
		detailData.table[index].fp_name = name
		dialogSelectVisible2.value = false
	}
	const table2 = ref()
	const setCurrent = (row, rowIndex) => {
	    setTimeout(() => {
	        table2.value?.setCurrentRow(row);
	        detailData.table[rowIndex].fp_gxmc = row.sczl_gxmc;
	        detailData.table[rowIndex].fp_bz = row.sczl_bzdh;
	        detailData.table[rowIndex].fp_bh = row.sczl_bh1;
	        detailData.table[rowIndex].fp_name = row.name;
	    });
	};


	const countEnter = async (index, row) => {
		// 计算总数
		let total = 0;
		detailData.table.forEach((item) => {
		    if (item.fp_sl != 0 && item.fp_sl != '') {
		        total += parseInt(item.fp_sl);
		    }
		});
		detailData.qczl_fp = total;
	}
	
	// 数量回车事件
	let selectData = []; // 初始化为数组
	// const handleFpslEnter = async (event, index, row, title) => {
	//     // 保存当前行索引
	//     selectIndex.value = index;
	
	//     // 如果数量为 0，则清空对应字段并直接返回
	//     if (row.fp_sl === 0 || row.fp_sl === '0' || row.fp_sl === '') {
	//         detailData.table[index].fp_gxmc = '';
	//         detailData.table[index].fp_bz = '';
	//         detailData.table[index].fp_bh = '';
	//         detailData.table[index].fp_name = '';
	//         return;
	//     }
	
	//     // 调用接口获取数据
	//     const params = {
	//         type: row.fp_lb,
	//         order: detailData.qczl_gdbh,
	//         yjno: detailData.qczl_yjno,
	//     };
	
	//     let res;
	//     try {
	//         res = await getGxAndLeader(params);
	//         console.log("接口返回结果", res);
	//         if (res.code !== 0) {
	//             return;
	//         }
	//     } catch (e) {
	//         console.log(e);
	//         return;
	//     }
	
	//     // 解析返回的数据
	//     const decodedData = res.data.map(item => ({
	//         sczl_gxmc: decodeEntities(item.sczl_gxmc),
	//         sczl_bzdh: item.sczl_bzdh,
	//         sczl_jtbbh: item.sczl_jtbh,
	//         sczl_bh1: item.sczl_bh1,
	//         name: item.name.trim(),
	//     }));
	
	//     // 如果数据为空，直接返回
	//     if (decodedData.length === 0) {
	//         console.log("接口返回数据为空");
	//         return;
	//     }
	
	//     // 初始化选中数据
	//     selectData = decodedData;
	//     SLIndex.value = 0; // 初始化索引为第一个
	//     setCurrent(selectData[0]); // 设置当前选中为第一个
	//     dialogSelectVisible2.value = true; // 显示弹窗
	// };
	
	// 选择逻辑
	const SLIndex = ref(0); // 初始化索引为 0
	const selectSL = (event) => {
	    console.log("键盘事件触发", event.keyCode);
	    if (event.keyCode === 40) { // 向下箭头
	        if (SLIndex.value < selectData.length - 1) {
	            SLIndex.value++;
	            setCurrent(selectData[SLIndex.value]);
	        } else {
	            SLIndex.value = 0;
	            setCurrent(selectData[SLIndex.value]);
	        }
	    } else if (event.keyCode === 38) { // 向上箭头
	        if (SLIndex.value > 0) {
	            SLIndex.value--;
	            setCurrent(selectData[SLIndex.value]);
	        } else {
	            SLIndex.value = selectData.length - 1;
	            setCurrent(selectData[SLIndex.value]);
	        }
	    } else if (event.keyCode === 13) { // 回车键
	        console.log("回车键触发");
	
	        // 如果未通过上下箭头选择，则默认选中第一个
	        if (SLIndex.value === null || SLIndex.value === undefined || selectData.length === 0) {
	            SLIndex.value = 0; // 默认选中第一个
	        }
	
	        // 获取当前选中的数据
	        const selectedRow = selectData[SLIndex.value];
	        if (!selectedRow) {
	            console.log("选中数据为空");
	            return;
	        }
	
	        console.log("关闭弹窗，选中数据为:", selectedRow);
			console.log("selectIndex.value:", selectIndex.value);
	        // 确保 selectIndex.value 是有效的当前行索引
	        if (selectIndex.value !== null) {
	            detailData.table[selectIndex.value].fp_gxmc = selectedRow.sczl_gxmc;
	            detailData.table[selectIndex.value].fp_bz = selectedRow.sczl_bzdh;
	            detailData.table[selectIndex.value].fp_bh = selectedRow.sczl_bh1;
	            detailData.table[selectIndex.value].fp_name = selectedRow.name;
	        }
	
	        // 关闭弹窗
	        dialogSelectVisible2.value = false;
	    }
	};
	// 弹窗确定
	const enterDialog = async () => {
		console.log(type.value)
		if (type.value === '修改工单核验单维护') {
			updateDetailData()
		} else if (type.value === '新增工单核验单维护') {
			addDetailData()
		}
	}
	const addDetailData = async () => {
		const formatDate = (date) => {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		};

		const restoredData = {
			UniqId: detailData.UniqId,
			qczl_gdbh: detailData.qczl_gdbh,
			qczl_yjno: detailData.qczl_yjno,
			qczl_gxh: detailData.qczl_gxh,
			qczl_gxmc: detailData.qczl_gxmc,
			qczl_rq: formatDate(new Date(detailData.qczl_rq)),
			qczl_fp: detailData.qczl_fp,
			qczl_num: detailData.qczl_num,
			qczl_NumDesc: detailData.qczl_NumDesc,
			qczl_NumDesc1: detailData.qczl_NumDesc1,
			qczl_NumDesc2: detailData.qczl_NumDesc2,
			qczl_NumDesc3: detailData.qczl_NumDesc3,
			qczl_NumDesc4: detailData.qczl_NumDesc4,
			qczl_NumDesc5: detailData.qczl_NumDesc5,
			qczl_NumDesc6: detailData.qczl_NumDesc6,
			qczl_NumDesc7: detailData.qczl_NumDesc7,
			qczl_NumDesc8: detailData.qczl_NumDesc8,
			sys_id: sys_id
		};

		detailData.table.forEach((item, index) => {
			const num = index + 1;
			restoredData[`fp_lb${num}`] = item.fp_lb;
			restoredData[`fp_sl${num}`] = item.fp_sl;
			restoredData[`fp_bh${num}`] = item.fp_bh;
			restoredData[`fp_bz${num}`] = item.fp_bz;
			restoredData[`fp_gxmc${num}`] = item.fp_gxmc;
		});

		console.log(restoredData);
		setTimeout(() => {
		const inputElement = document.getElementById('qczl_num');
			if (inputElement) {
				inputElement.focus();		
			}
		}, 100);
		dialogbutton.value = false;
		// return;
		const res = await add(restoredData)
		console.log(res)

		if (res.code === 0) {
			ElMessage({type: 'success',message: '新增成功',})
			//刷新
			if (params.date != '') {
				getTableData()
			}
			getSideData()
			detailData.table.forEach((item, index) => {
				item.fp_sl = 0;
			});
			// dialogFormVisible.value = false
		}
		detailData.qczl_fp = 0
	};
	// 修改
	const updateDetailData = async () => {
		// console.log("确认")
		const formatDate = (date) => {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		};
		const restoredData = {
			UniqId: detailData.UniqId,
			qczl_gdbh: detailData.qczl_gdbh,
			qczl_yjno: detailData.qczl_yjno,
			qczl_gxh: detailData.qczl_gxh,
			qczl_gxmc: detailData.qczl_gxmc,
			qczl_rq: formatDate(new Date(detailData.qczl_rq)),
			qczl_fp: detailData.qczl_fp,
			qczl_num: detailData.qczl_num,
			qczl_NumDesc: detailData.qczl_NumDesc,
			qczl_NumDesc1: detailData.qczl_NumDesc1,
			qczl_NumDesc2: detailData.qczl_NumDesc2,
			qczl_NumDesc3: detailData.qczl_NumDesc3,
			qczl_NumDesc4: detailData.qczl_NumDesc4,
			qczl_NumDesc5: detailData.qczl_NumDesc5,
			qczl_NumDesc6: detailData.qczl_NumDesc6,
			qczl_NumDesc7: detailData.qczl_NumDesc7,
			qczl_NumDesc8: detailData.qczl_NumDesc8,
		}
		detailData.table.forEach((item, index) => {
			const num = index + 1
			restoredData[`fp_lb${num}`] = item.fp_lb
			restoredData[`fp_sl${num}`] = item.fp_sl
			restoredData[`fp_bh${num}`] = item.fp_bh
			restoredData[`fp_bz${num}`] = item.fp_bz
			restoredData[`fp_gxmc${num}`] = item.fp_gxmc
		})
		const res = await updateData(restoredData)
		if (res.code === 0) {
			ElMessage({
				type: 'success',
				message: res.msg,
			})
			dialogFormVisible.value = false
		}
	}

	// 多选
	const handleSelectionChange = (val) => {
		multipleSelection.value = val
	}

	// 多选删除
	const onDelete = async () => {
		const ids = []
		if (multipleSelection.value.length === 0) {
			ElMessage({
				type: 'warning',
				message: '请选择要删除的数据'
			})
			return
		}
		multipleSelection.value &&
			multipleSelection.value.map(item => {
				ids.push(item.ID)
			})
		const res = await deleteCompanyByIds({
			ids
		})
		if (res.code === 0) {
			ElMessage({
				type: 'success',
				message: '删除成功'
			})
			if (tableData.value.length === ids.length && page.value > 1) {
				page.value--
			}
			deleteVisible.value = false
			getTableData()
		}
	}

	// 更新行
	const updateCompanyFunc = async (row) => {
		const res = await findCompany({
			ID: row.ID
		})
		type.value = 'update'
		if (res.code === 0) {
			formData.value = res.data.recompany
			// dialogFormVisible.value = true
			showDialog()
		}
	}

	// 关闭弹窗
	const closeDialog = () => {
		dialogFormVisible.value = false
	}

	// 导出excel
	function exportExcel() {
		console.log('导出到excel')
	}

	const dialogMrhjtj = ref(false)
	const dialogGdzjfptj = ref(false)
	const dialogSbyxgl = ref(false)
	const dialoglcdcx = ref(false)
	const value1 = ref('')
	const table = ref(null)

	const showGdzjfptj = () => {
		value1.value = currentRow.gdbh
		dialogGdzjfptj.value = true
		
	}
	const currentRow = ref()
	const lcdyjno = ref()
	const handleSelectChange = (row, column, event) => {
		currentRow.value = row.UniqId
		currentRow.gdbh = row.qczl_gdbh
		lcdyjno.value = row.qczl_yjno
	}

	//新增工单核验单维护
	const handleShowAdd = async () => {
		type.value = '新增工单核验单维护'
		dialogFormVisible.value = true
		setTimeout(() => {
		const inputElement = document.getElementById('日期');
			if (inputElement) {
				inputElement.focus();		
			}
		}, 100);
		if (currentRow.value == undefined) {
			// 循环13行数据
			const table = []
			for (let i = 1; i <= 13; i++) {
				table.push({
					fp_lb: '',
					fp_sl: '',
					fp_gxmc: '',
					fp_bz: '',
					fp_bh: '',
					fp_name: '',
				})
			}
			detailData.table = table
			dialogFormVisible.value = true
		} else {
			getOneWorkOrder({ UniqId: currentRow.value }).then(res => {
				if (res.code === 0) {
					const obj = res.data
					// 裁剪返回数据的前后空格
					for (const key in obj) {
						if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'string') {
							obj[key] = obj[key].trim()
						}
					}
					// 修改日期格式
					if (Object.prototype.hasOwnProperty.call(obj, 'qczl_rq') && typeof obj['qczl_rq'] === 'string') {
						obj['qczl_rq'] = obj['qczl_rq'].split(' ')[0]
					}
					obj['qczl_num'] = '0'
					obj['qczl_NumDesc1'] = '0'
					obj['qczl_NumDesc2'] = '0'
					obj['qczl_NumDesc3'] = '0'
					obj['qczl_NumDesc4'] = '0'
					obj['qczl_NumDesc5'] = '0'
					obj['qczl_NumDesc6'] = '0'
					obj['qczl_NumDesc7'] = '0'
					obj['qczl_NumDesc8'] = '0'
					obj['qczl_fp'] = ''
					Object.assign(detailData, obj)
					const table = []
					// 循环13行数据
					for (let i = 1; i <= 13; i++) {
						table.push({
							fp_lb: detailData[`fp_lb${i}`] || '',
							fp_sl: 0,
							fp_gxmc: detailData[`fp_gxmc${i}`] || '',
							fp_bz: detailData[`fp_bz${i}`] || '',
							fp_bh: detailData[`fp_bh${i}`] || '',
							fp_name: detailData[`fp_name${i}`] || '',
						})
						// 从原对象中删除这些属性
						delete detailData[`fp_lb${i}`]
						delete detailData[`fp_sl${i}`]
						delete detailData[`fp_gxmc${i}`]
						delete detailData[`fp_bz${i}`]
						delete detailData[`fp_bh${i}`]
						delete detailData[`fp_name${i}`]
					}
					detailData.table = table
					getOrderInfo({ order: detailData.qczl_gdbh }).then(resposne => {
						if (resposne.code === 0) {
							//循环resposne.data当子项yj_Yjno的值等于obj中的qczl_yjno的值时设置detailData.Gd_cpmc的值为res.data[i].Gd_cpmc
							for (let i = 0; i < resposne.data.length; i++) {
								if (resposne.data[i].yj_Yjno == detailData.qczl_yjno) {
									detailData.yj_yjmc = resposne.data[i].yj_yjmc
									detailData.Gd_cpmc = resposne.data[i].Gd_cpmc
								}
							}
							showDialog()
						}
					})
				}
			})
		}
	}
	// 开启弹窗
	const showDialog = () => {
		dialogFormVisible.value = true
	}

	const dialogSelectVisible1 = ref(false); // 控制对话框显示
	const selecTreeData = ref([]); // 树形数据
	const table_fplb = ref(null); // el-tree 的 ref
	const defaultExpandedKey = ref(null); // 默认展开的节点 key
	const selectIndex = ref(0); // 当前选中的索引
	
	
	// 异步加载废品类别的回车事件
	const handleFplbEnter = async (event, index, row, title) => {
	  // 更新当前选中的索引
	  selectIndex.value = index;
	  if (dialogSelectVisible1.value || !row.fp_lb?.trim()) {
	    console.log("废品类别为空或弹窗已打开");
	    return;
	  }
	  try {
	    const res = await getWastInfo();
	    if (res.code === 0 && res.data && res.data.废品分类) {
	      const categories = res.data.废品分类;
	      if (typeof categories !== 'object') {
	        console.error("废品分类数据格式错误，预期为对象格式", categories);
	        return;
	      }
	      const hasMatch = checkMatchInTree(processTreeData(categories, ''), row.fp_lb.trim());
	      if (hasMatch) {
	        return;
	      }
	      const treeData = processTreeData(categories, row.fp_lb.trim());
	      selecTreeData.value = treeData;
	      dialogSelectVisible1.value = true;
	      nextTick(() => {
	        if (treeData.length > 0) {
	          defaultExpandedKey.value = treeData[0].id;
	          const firstNode = treeData[0];
	          if (table_fplb.value) {
	            table_fplb.value.setCurrentKey(firstNode.id);
	            handleFplbClick(firstNode, true);
	          }
	        }
	      });
	    }
	  } catch (error) {
	    console.error("获取废品分类数据时出错:", error);
	  }
	};
	
	// 递归检查树形数据是否存在匹配项
	const checkMatchInTree = (tree, targetLabel) => {
	  if (!tree || !targetLabel) return false;
	  for (const node of tree) {
	    if (node.label === targetLabel) {
	      return true; // 找到匹配项
	    }
	    if (node.children && node.children.length > 0) {
	      const foundInChildren = checkMatchInTree(node.children, targetLabel);
	      if (foundInChildren) {
	        return true;
	      }
	    }
	  }
	  return false; // 未找到匹配项
	};
	
	// 处理数据构建树形结构（支持模糊筛选）
	const processTreeData = (categories, prefix) => {
	  const result = [];
	  if (!categories || typeof categories !== 'object') {
	    console.error("processTreeData：废品分类数据格式不正确", categories);
	    return result;
	  }
	  // 处理分类数据
	  const isPrefixValid = prefix && /^[a-zA-Z]+$/.test(prefix);
	  const upperPrefix = isPrefixValid ? prefix.toUpperCase() : null;
	  for (const categoryKey in categories) {
	    if (Object.prototype.hasOwnProperty.call(categories, categoryKey)) {
	      const items = categories[categoryKey];
	      const categoryNode = {
	        id: categoryKey,
	        label: categoryKey,
	        children: [],
	      };
	      for (const [index, item] of items.entries()) {
	        if (!upperPrefix || item.toUpperCase().includes(upperPrefix)) {
	          categoryNode.children.push({
	            id: `${categoryKey}-${index}`,
	            label: item,
	            children: [],
	          });
	        }
	      }
	      if (categoryNode.children.length > 0) {
	        result.push(categoryNode);
	      }
	    }
	  }
	  return result; // 确保返回的总是数组
	};

	// 废品类别分类点击事件
	const handleFplbClick = (node) => {
	  const tree = table_fplb.value; // 获取树实例
	  if (!tree) {
	    console.error("树实例未加载");
	    return;
	  }
	  // 清除上一次的选中状态
	  clearPreviousSelection(tree);
	  // 遍历所有节点，收起所有节点
	  Object.keys(tree.store.nodesMap).forEach((key) => {
	    tree.store.nodesMap[key].expanded = false; // 收起所有节点
	  });
	};
	
	// 废品类别分类键盘事件
	const handleTreeKeydown = (event) => {
	  const tree = table_fplb.value; // 获取树实例
	  if (!tree) {
	    console.error("树组件未加载");
	    return;
	  }
	
	  const focusedElement = document.activeElement;
	  const focusedNodeId = focusedElement?.getAttribute("data-key"); // 获取 DOM 的 data-key 属性
	
	  if (event.keyCode === 13 && focusedNodeId) { // 判断是否是回车键
	    tree.setCurrentKey(focusedNodeId); // 设置当前节点为选中
	    tree.$nextTick(() => {
	      const currentNode = tree.getCurrentNode(); // 获取当前选中的节点
	      if (!currentNode) {
	        console.warn("没有选中的节点");
	        return;
	      }
		// 清除上一次的选中状态
		clearPreviousSelection(tree);
	      // 收起所有其他节点
	      Object.keys(tree.store.nodesMap).forEach((key) => {
	        tree.store.nodesMap[key].expanded = false; // 收起所有节点
	      });
	
	      // 展开当前节点
	      tree.store.nodesMap[currentNode.id].expanded = true;
	
	      // 如果当前节点有子节点，选中第一个子节点
	      if (currentNode.children && currentNode.children.length > 0) {
	        const firstChild = currentNode.children[0];
	        if (firstChild) {
	          const firstChildKey = firstChild.id.toString();
	          tree.setCurrentKey(firstChildKey); // 设置第一个子节点为选中
	          setTimeout(() => {
	            const firstChildDom = tree.$el.querySelector(`[data-key="${firstChildKey}"]`);
	            if (firstChildDom) {
	              firstChildDom.focus();
	              firstChildDom.scrollIntoView({ block: "nearest" });
	            }
	          });
	        }
	      } else {
	        console.log("当前子节点:", currentNode.label);
	        detailData.table[selectIndex.value].fp_lb = currentNode.label; // 更新数据
	        dialogSelectVisible1.value = false; // 关闭对话框
	      }
	    });
	  } else if (event.keyCode === 38 || event.keyCode === 40) { // 上下箭头键
	    const currentNode = tree.getCurrentNode();
	    if (currentNode) {
	      const currentNodeDom = tree.$el.querySelector(`[data-key="${currentNode.id}"]`);
	      if (currentNodeDom) {
	        currentNodeDom.focus();
	      }
	    }
	  }
	};
	
	// 工序弹出框键盘事件
	const ent = (event) => {
	  if (document.activeElement.id === "tableFplb") {
	    if (table_fplb.value) {
	      const tree = table_fplb.value?.$el;
	      console.log(111, tree);
	      if (tree) {
	        const node = tree.querySelector("[data-key]");
	        console.log(222, node);
	        if (event.keyCode === 13) {
	          dialogSelectVisible1.value = false;
	        }
	        if (node) {
	          node.scrollIntoView({ block: "nearest" }); // 确保节点可见
	          node.focus(); // 确保焦点正确
	        }
	      }
	    }
	  }
	};
	
	// 清除之前的选中状态
	const clearPreviousSelection = (tree) => {
	  const selectedNodes = tree.getCheckedNodes();
	  selectedNodes.forEach(node => {
	    tree.setChecked(node, false);
	  });
	  tree.setCurrentKey(null);
	};
	
	
	//键盘事件监听逻辑确认
	const handleKeydown = (event) => {
	  if (dialogbutton.value && event.key === "Enter") {
		  ElMessage({
		  	type: 'warning',
		  	message: '正在保存数据中'
		  })
	    enterDialog(); // 调用确认按钮逻辑
	  }
	};
	
	// 获取工序
	const getgxsubmit = () => {
		console.log("获取工序")
		if(!detailData.qczl_gdbh || !detailData.qczl_yjno){
			return
		}
		GetJtbh()
	}
	const GetJtbh = async () => {
		const { qczl_gdbh, qczl_yjno } = detailData
		const response = await getYjInfo({ order: qczl_gdbh, yj_no: qczl_yjno })
		if (response.code === 0) {
			const data = response.data
			console.log(data)
			if (data) {
				detailData.total_liucheng = data.max_num
				const tableData = data.gx_data.map(item => ({
					gxh: item.Gy0_gxh,
					gxmc: item.Gy0_gxmc + (item.Add_gxmc === '' ? '' : '-' + item.Add_gxmc),
					// addGxmc: item.Add_gxmc
				}))
				selectData_gx.splice(0, selectData_gx.length, ...tableData)
				setCurrent_gx(selectData_gx[0])
				dialogSelectVisible_gx.value = true
			}
		}
	}

	let isProcessing = false; // 标志位
	let lastFpSl = null; // 记录上一次输入的数量
	const dialogbutton  = ref(false); // 控制对话框显示
	let enterCount = 0; // 记录回车键按下的次数

	 //新增回车事件
	 const ent1 = async(event,index,row,title) => {
	   const inputs = document.getElementsByTagName('input');
	   const currentIndex = Array.from(inputs).indexOf(event.target);
	   if (event.keyCode === 13 && title === '工序') {
		   getgxsubmit()
	   }else if (event.keyCode === 13 && title === '流程单号') {
		  // 获取所有相关的输入框值
		  const allValues = [
			detailData.qczl_num,
			detailData.qczl_NumDesc1,
			detailData.qczl_NumDesc2,
			detailData.qczl_NumDesc3,
			detailData.qczl_NumDesc4,
			detailData.qczl_NumDesc5,
			detailData.qczl_NumDesc6,
			detailData.qczl_NumDesc7,
			detailData.qczl_NumDesc8,
		  ];
		  // 获取当前输入框的值
		  const currentValue = event.target.value;

		  // 如果当前值为 0，不进行校验，直接跳转到下一个输入框
		  if (currentValue === "0") {
			console.log("输入值为 0，无需校验");

			// 跳转到下一个输入框
			let nextIndex = currentIndex + 1;
			let foundNext = false; // 标记是否找到下一个可用输入框
			while (nextIndex < inputs.length) {
			  if (inputs[nextIndex].disabled) {
				console.log("当前输入框为 disabled，跳过");
				nextIndex++; // 跳过 disabled 的输入框
				continue;
			  }
			  if (!inputs[nextIndex].readOnly) {
				nextTick(() => {
				  inputs[nextIndex].focus();
				  inputs[nextIndex].select();
				});
				foundNext = true; // 找到下一个可用输入框
				break;
			  }
			  nextIndex++;
			}
			if (!foundNext) {
			  console.log("没有更多可用的输入框");
			}
			return;
		  }

		  // 检查是否有重复的值
		  const isDuplicate = allValues.filter((val) => val === currentValue).length > 1;

		  if (isDuplicate) {
			// 如果有重复值，提示用户并清空当前输入框
			event.target.value = 0;
			ElMessage({
			  type: 'error',
			  message: '输入的值已存在，请重新输入'
			});
		  } else {
			console.log('输入值无重复');
			// 跳转到下一个输入框
			let nextIndex = currentIndex + 1;
			let foundNext = false; // 标记是否找到下一个可用输入框
			while (nextIndex < inputs.length) {
			  if (inputs[nextIndex].disabled) {
				console.log("当前输入框为 disabled，跳过");
				nextIndex++; // 跳过 disabled 的输入框
				continue;
			  }
			  if (!inputs[nextIndex].readOnly) {
				nextTick(() => {
				  inputs[nextIndex].focus();
				  inputs[nextIndex].select();
				});
				foundNext = true; // 找到下一个可用输入框
				break;
			  }
			  nextIndex++;
			}
			if (!foundNext) {
			  console.log("没有更多可用的输入框");
			}
		  }
		}else if (event.keyCode === 13 && title === '废品类别') {
			 handleFplbEnter(event,index,row,title)
			let nextIndex = currentIndex + 1;
			   let foundNext = false; // 标记是否找到下一个可用的输入框
			   while (nextIndex < inputs.length) {
				   if (inputs[nextIndex].disabled) {
					   console.log("当前输入框为disabled，跳过");
					   nextIndex++; // 跳过disabled的输入框
					   continue;
				   }
				   if (!inputs[nextIndex].readOnly) {
					   nextTick(() => {
						   inputs[nextIndex].focus();
						   inputs[nextIndex].select();
					   });
					   foundNext = true; // 找到下一个可用输入框
					   break;
				   }
				   nextIndex++;
			   }
	   }else if (event.keyCode === 13 && title === '数量') {
		  // 去掉数量前导的0
		  if (typeof row.fp_sl === 'string') {
			row.fp_sl = row.fp_sl.replace(/^0+(?=\d)/, '');
		  }

		  // 判断数量是否为 0 或为空
		  if (row.fp_sl === '0' || row.fp_sl === '' || row.fp_sl === 0) {
			console.log("数量为 0，清空对应字段");
			['fp_gxmc', 'fp_bz', 'fp_bh', 'fp_name'].forEach(field => {
			  detailData.table[index][field] = '';
			});
		  } 

		  // 焦点跳转逻辑
		  let nextIndex = currentIndex + 1;
		  let foundNext = false;

		  while (nextIndex < inputs.length) {
			const nextInput = inputs[nextIndex];
			if (!nextInput.disabled && !nextInput.readOnly) {
			  nextInput.focus();
			  nextInput.select();
			  foundNext = true;
			  console.log(`焦点已跳转到输入框索引: ${nextIndex}`);
			  break;
			}
			nextIndex++;
		  }

		  if (!foundNext) {
			console.log("未找到下一个可用的输入框");

			enterCount++; // 增加回车键按下的次数

			if (enterCount === 2) {
			  dialogbutton.value = true; // 第二次按下回车键时弹出弹窗
			  enterCount = 0; // 重置计数器
			}
		  }

		  isProcessing = false; // 标志位重置，允许下一次回车处理
		}else 
	if (event.keyCode === 13 && title === '工序及责任机长') {
	    console.log('工序及责任机长');
	    console.log('row', row['fp_gxmc']);
	
	    // 判断工序字段是否为空
	    if (!row.fp_gxmc || row.fp_gxmc.trim() === '') {
	        console.log('工序及责任机长为空，跳转到下一个输入框');
	        let nextIndex = currentIndex + 1;
	        let foundNext = false;
	
	        // 找下一个可用输入框
	        while (nextIndex < inputs.length) {
	            if (!inputs[nextIndex].disabled && !inputs[nextIndex].readOnly) {
	                nextTick(() => {
	                    inputs[nextIndex].focus();
	                    inputs[nextIndex].select();
	                });
	                foundNext = true;
	                break;
	            }
	            nextIndex++;
	        }
	
	        // 如果找不到下一个输入框，触发弹窗逻辑
	        if (!foundNext) {
	            console.log('未找到下一个可用的输入框');
	            dialogbutton.value = true;
	            handleKeydown();
	        }
	        return; // 提前返回
	    }
	
	    // 如果数量为 0，清空字段并返回
	    if (row.fp_sl === 0 || row.fp_sl === '0' || row.fp_sl === '') {
	        detailData.table[index].fp_gxmc = '';
	        detailData.table[index].fp_bz = '';
	        detailData.table[index].fp_bh = '';
	        detailData.table[index].fp_name = '';
	        return;
	    }
	
	    // 保存当前行索引
	    selectIndex.value = index;
	
	    // 调用接口获取数据
	    const params = {
	        type: row.fp_lb,
	        order: detailData.qczl_gdbh,
	        yjno: detailData.qczl_yjno,
	    };
	
	    let res;
	    try {
	        res = await getGxAndLeader(params);
	        console.log('接口返回结果', res);
	        if (res.code !== 0) {
	            return; // 如果接口报错，直接返回
	        }
	    } catch (e) {
	        console.log('接口调用异常:', e);
	        return;
	    }
		
		// 解析接口返回数据
		const decodedData = res.data.map(item => ({
		    sczl_gxmc: item.sczl_gxmc,
		    sczl_bzdh: item.sczl_bzdh,
		    sczl_jtbbh: item.sczl_jtbh,
		    sczl_bh1: item.sczl_bh1,
		    name: item.name ? item.name.trim() : '', // 防止 name 为 null
		}));
		
		// 如果接口返回数据为空，直接返回
		if (decodedData.length === 0) {
		    console.log('接口返回数据为空');
		    return;
		}
		
		console.log('row:', row);
		
		// 匹配接口返回数据中的 sczl_gxmc 和 name
		const matchedItem = decodedData.find(item => {
			// console.log('正在匹配:', item.sczl_gxmc, '与', row.fp_gxmc);
			// return item.name === row.fp_name;
		    console.log('正在匹配工序名称:', `: ${item.sczl_gxmc} 与 ${row.fp_gxmc}`);
			console.log('正在匹配名字:', `名字: ${item.name} 与 ${row.fp_name}`);
			// 运行匹配不成功继续匹配,成功代表匹配成功
		    return item.sczl_gxmc === row.fp_gxmc && item.name === row.fp_name;
		});
		
		
		console.log('匹配到的项:', matchedItem);
		
		if (matchedItem) {
		    // 如果找到匹配的数据，更新当前行
		    console.log('匹配成功，数据正确，不需要弹窗');
		    detailData.table[index].fp_bz = matchedItem.sczl_bzdh;
		    detailData.table[index].fp_bh = matchedItem.sczl_bh1;
		    detailData.table[index].fp_name = matchedItem.name;
		
		    // 跳转到下一个输入框
		    let nextIndex = currentIndex + 1;
		    let foundNext = false;
		
		    while (nextIndex < inputs.length) {
		        if (!inputs[nextIndex].disabled && !inputs[nextIndex].readOnly) {
		            nextTick(() => {
		                inputs[nextIndex].focus();
		                inputs[nextIndex].select();
		            });
		            foundNext = true;
		            break;
		        }
		        nextIndex++;
		    }
		
		    if (!foundNext) {
		        console.log('未找到下一个可用的输入框');
		        dialogbutton.value = true;
		        handleKeydown();
		    }
		} else {
		    // 如果未找到匹配的数据，弹窗选择
		    console.log('匹配失败，需要弹窗');
		    selectData = decodedData;
		    SLIndex.value = 0; // 初始化索引为第一个
		    setCurrent(selectData[0]); // 设置当前选中为第一个
		    dialogSelectVisible2.value = true; // 显示弹窗
		}
	}

		else if (event.keyCode === 13 || event.keyCode === 40 && title === '') {
		   console.log('其他')
		   let nextIndex = currentIndex + 1;
		   let foundNext = false; // 标记是否找到下一个可用的输入框
		   while (nextIndex < inputs.length) {
			   if (inputs[nextIndex].disabled) {
				   nextIndex++; // 跳过disabled的输入框
				   continue;
			   }
			   if (!inputs[nextIndex].readOnly) {
				   nextTick(() => {
					   inputs[nextIndex].focus();
					   inputs[nextIndex].select();
				   });
				   foundNext = true; // 找到下一个可用输入框
				   break;
			   }
			   nextIndex++;
		   }
		// 如果没有找到下一个可用输入框，提示用户
		if (!foundNext) {
			console.log("已经是最后一个输入框");
		}
	   }
	 else if (event.keyCode === 38) { // 向上箭头
		 for (let i = currentIndex - 1; i >= 0; i--) {
		   if (!inputs[i].readOnly) {
			 nextTick(()=>{
				inputs[i].focus();
				inputs[i].select();
			 })
			 break;
		   }
		 }
	   } else if (event.keyCode === 37) { // 向左箭头
		 if (event.target.selectionStart === 0) {
		   for (let i = currentIndex - 1; i >= 0; i--) {
			 if (!inputs[i].readOnly) {
			   nextTick(()=>{
				inputs[i].focus();
				inputs[i].select();
			   })
			   break;
			 }
		   }
		 }
	   } else if (event.keyCode === 39) { // 向右箭头
		 if (event.target.selectionStart === event.target.value.length) {
		   for (let i = currentIndex + 1; i < inputs.length; i++) {
			 if (!inputs[i].readOnly) {
			   nextTick(()=>{
				inputs[i].focus();
				inputs[i].select();
			   })
			   break;
			 }
		   }
		 }
	   }
	 }
 

//删除按钮
const handleDelete = () => {
	if (currentRow.value == undefined) {
		ElMessage({type: 'warning',message: '未选中记录',})
		return
	}
	ElMessageBox.confirm(`确认删除这条数据么?`,'警告', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			del({'UniqId': currentRow.value}).then(res => {
				if (res.code === 0) {
					ElMessage({
						type: 'success',
						message: '删除成功',
					})
					currentRow.value = undefined
					getSideData()
					getTableData()
				}
			})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
}
</script>

<style>
.JKWTree-container {
  display: flex;
}

.JKWTree-tree {
  width: 300px;
  background-color: #fff;
  padding: 10px;
  margin-right: 20px;
}

.JKWTree-tree h3 {
  font-size: 15px;
  font-weight: 700;
  margin: 10px 0;
}

.JKWTree-content {
  flex: 1;
}

/* 选中某行时的背景色*/
.el-table__body tr.current-row > td {
  background: #ff80ff !important;
  /* 背景颜色 */
}
</style>
<style scoped>
:deep(.el-table td .cell) {
  line-height: 20px !important;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.search {
  margin-left: 0px !important;
  margin-right: 10px !important;
}

.bt {
  margin-left: 2px !important;
  padding: 3px !important;
  font-size: 12px;
}

.el-tabs__header {
  margin: 0px !important;
}

.gva-table-box {
  padding: 0px !important;
}

.mab {
  margin-bottom: 5px;
}

:deep(.plan-usage-low div) {
  color: blue !important;
  font-size: 16px;
  font-weight: bold;
}

/* 工序产量核查高亮 */
:deep(.lan-plan-usage-lows  div) {
  color: blue !important;
  font-weight: bold;
}
/* tree组件背景高亮 */
:deep(.el-tree-node:focus > .el-tree-node__content){
		background: #ff80ff !important;
	}
/*!* 流程单查询按钮颜色控制未完成*/
:deep(.custom-button.el-button--info) {
	background-color: palegreen !important;
  color: #155724;
  font-size: 20px;
  border-color: #c3e6cb;
}
/* 已完成 */
:deep(.custom-button.el-button--danger) {
	background-color: rgb(236, 135, 135) !important;
  color: #721c24;
  font-size: 20px;
  border-color: #f5c6cb;
}
</style>