<template>
  <div>
    <!-- 左侧树形结构 -->
    <el-container>
      <!-- <el-aside width="250px">
        <div class="JKWTree-tree">
          <h3>机器检验计件单据维护</h3>
          <el-tree :data="treeData" :props="defaultProps" highlight-current="true"
            @node-click="handleNodeClick"></el-tree>
        </div>
      </el-aside> -->
	  
	  
	  <layout-sider :resize-directions="['right']" :width="220" style="margin-right: 10px;" >
	     <div class="JKWTree-tree" style="height: 70vh;" >
	       <h3>机器检验计件单据维护</h3>
	       <el-tree :data="treeData" highlight-current @node-click="handleNodeClick" />
	     </div>
	   </layout-sider>
      <el-container>
		  
        <el-main>
          <!-- 按钮区域 -->
          <div class="gva-table-box">
            <el-form-item>
              <el-input v-model="positionvalue" placeholder="输入工单编号或产品名称" style="width: 180px;" />
              <el-button type="primary" class="search" icon="search" @click="onSearch"></el-button>
              <el-button type="primary" class="bt" icon="plus" @click="onAdd">新增</el-button>
			  <el-button type="primary" class="bt"  icon="copy-document" @click="onCountByGdbh">切换显示方式</el-button>
			  <el-button type="primary" class="bt" icon="refresh" @click="onRefresh">刷新质检系数</el-button>
			  <el-button type="primary" class="bt" icon="delete" @click="onDel">删除</el-button>
              <div style="margin-left: auto;">
                <el-button type="primary" :icon="Download" @click="exportExcel">导出到Excel</el-button>
              </div>
            </el-form-item>
            <!-- 数据展示 -->
            <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
              highlight-current-row="true" border @selection-change="handleSelectionChange"  @row-click="Click"
			  :show-overflow-tooltip="true" @row-dblclick="doubleClick">
              <el-table-column align="left" sortable label="分类" prop="sczl_单据类型" width="77"/>
              <el-table-column align="left" sortable label="工单印件" prop="combinedProp"width="250"/>
              <el-table-column align="left" sortable label="印件工序" prop="combinedProp2" width="120"/>
              <el-table-column align="left" sortable label="机台编号" prop="sczl_jtbh" width="105"/>
              <el-table-column align="left" sortable label="机台" prop="sczl_jtbh" width="77"/>
              <el-table-column align="left" sortable label="日期" prop="sczl_rq" width="105"/>
              <el-table-column align="left" sortable label="计件产量" prop="sczl_cl" width="105"/>
              <el-table-column align="left" sortable label="检验类别" prop="sczl_检验类别" width="105"/>
              <el-table-column align="left" sortable label="废品率系数" prop="sczl_废品率系数" width="120"/>
			  <el-table-column align="left" sortable label="日定额" prop="日定额" width="91"/>
			  <el-table-column align="left" sortable label="员工姓名1" prop="sczl_bh1_name" width="113"/>
			  <el-table-column align="left" sortable label="员工姓名2" prop="sczl_bh2_name"width="113" />
			  <el-table-column align="left" sortable label="员工姓名3" prop="sczl_bh3_name" width="113"/>
			  <el-table-column align="left" sortable label="员工姓名4" prop="sczl_bh4_name"width="113" />
			  <el-table-column align="left" sortable label="班组代号" prop="sczl_bzdh" width="105"/>
			  <el-table-column align="left" sortable label="千件工价" prop="千件工价" width="105"/>
			  <el-table-column align="left" sortable label="日通电工时" prop="sczl_设备运行工时" width="120"/>
			  <el-table-column align="left" sortable label="流程单备注" prop="qczl_NumDesc" width="120"/>			
			  <el-table-column align="left" sortable label="创建用户" prop="sys_id" width="120"/>
              <el-table-column align="left" sortable label="创建时间" prop="sys_rq" width="160"/>
              <el-table-column align="left" sortable label="修改时间" prop="mod_rq" width="160"/>
              <el-table-column align="left" sortable label="UNIQID" prop="UniqId" width="120"/>			
            </el-table>
            <!-- 分页 -->
            <div class="gva-pagination">
              <el-pagination layout="total, sizes, prev, pager, next, jumper" v-model:current-page="page"
                v-model:page-size="limit"
                :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 === 'create' ? '添加' : '修改'"
            destroy-on-close width="1000px">
            <!-- <el-scrollbar height="500px"> -->
             <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="70px" >
			  <el-row :gutter="24">
				 <el-col :span="4">
				   <el-form-item label="日期" prop="id" class="mab">
					 <el-input type="date" max="9999-12-31" v-model="formData.sczl_rq" id="日期"  @keydown="ent1($event, '其他备注', '日期', '组别')"   />
				   </el-form-item>
				 </el-col>
				 <el-col :span="4">
				   <el-form-item label="组别" prop="name" label-width="90px" class="mab">
						 <el-input v-model="formData.sczl_bzdh" id="组别"  @keydown="ent1($event, '日期', '组别', '工单编号')"   />
				   </el-form-item>
				 </el-col>
			   </el-row>  
				<el-row :gutter="24">
					<el-col :span="24">
						  <el-form-item label="工单编号" prop="id" class="mab">
							<el-input v-model="formData.sczl_gdbh" id="工单编号"  @keydown="ent1($event, '每箱数', '工单编号', 'yjgx')" @blur="getGxMcsubmit" style="width: 118px; margin-right: 5px;"/>
							<el-input v-model="formData.sczl_yjgx" id="yjgx"  @keydown="ent1($event, '工单编号', 'yjgx', 'gxmc')" style="width: 80px; margin-right: 5px;"/>
							<el-input v-model="formData.sczl_gxmc" id="gxmc"  @keydown="ent1($event, 'yjgx', 'gxmc', 'yjmc')" style="width: 135px; margin-right: 5px;"/>
							<el-input v-model="formData.yj_yjmc" id="yjmc"  @keydown="ent1($event, 'gxmc', 'yjmc', '产量合计')" style="width: 542px;"/>
						  </el-form-item>
					</el-col>	 
				</el-row>
						   
					<el-row :gutter="24">
					 <el-col :span="6">
					   <el-form-item label="机台编号" prop="id" class="mab">
						 <el-input v-model="formData.sczl_jtbh" id="机台编号"  @keydown="ent1($event, 'yj_yjmc', '机台编号', '检验类型')" @keyup.enter.native="getJtbhsubmit" style="width: 80px;" />
					   </el-form-item>
					 </el-col>
					 <el-col :span="6">
						<el-form-item label="检验类型" prop="id" class="mab">
						 <el-input v-model="formData.sczl_单据类型" id="检验类型"  @keydown="ent1($event, '机台编号', '检验类型', '检验类别')" style="width: 150px;" />
						</el-form-item>
					 </el-col>
					 <el-col :span="6">
					   <el-form-item label="检验类别" prop="name" class="mab">
						 <el-input v-model="formData.sczl_检验类别" id="检验类别"  @keydown="ent1($event, '检验类型', '检验类别', '废品率系数')" style="width: 150px;" />
					   </el-form-item>
					 </el-col>
					 <el-col :span="6">
					   <el-form-item label="废品率系数" prop="name" class="mab" label-width="100px">
						 <el-input v-model="formData.sczl_废品率系数" id="废品率系数"  @keydown="ent1($event, '检验类别', '废品率系数', '计件箱数')" style="width: 150px;" />
					   </el-form-item>
					 </el-col>
				   </el-row>
						   
					<el-row :gutter="24">
					   <el-col :span="6">
						 <el-form-item label="计件箱数" prop="id" class="mab">
						   <el-input v-model="formData.sczl_cl" id="计件箱数"  @keydown="ent1($event, '废品率系数', '计件箱数', '每箱数量')" style="width: 118px;"/>
						 </el-form-item>
					   </el-col>
					 <el-col :span="6">
						 <el-form-item label="每箱数量" prop="name" class="mab">
						   <el-input v-model="formData.sczl_PgCl" id="每箱数量"  @keydown="ent1($event, '计件箱数', '每箱数量', '定额代号')"   />
						 </el-form-item>
					   </el-col>
					   <el-col :span="6">
							<el-form-item label="定额代号" prop="id" class="mab">
								<el-input v-model="formData.sczl_dedh" id="定额代号"  @keydown="ent1($event, '产量合计', '定额代号', '检验类别')" @blur="getDedhsubmit" style="width: 150px;" />
							</el-form-item>
					   </el-col>
					</el-row>
					 
					 
					 
					 <el-row :gutter="24">
						 <el-col :span="17">
						   <el-form-item label="流程单号" prop="id" class="mab">
								<!-- <el-input v-model="formData.address" id="流程单号"  @keydown="ent1($event, '定额代号', '流程单号', '流程单号1')" style="width: 60px; margin-right: 5px;"/> -->
								<el-input v-model="formData.流程单号1" id="流程单号1"  @keydown="ent1($event, '冲月定额', '流程单号1', '流程单号2')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号2" id="流程单号2"  @keydown="ent1($event, '流程单号1', '流程单号2', '流程单号3')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号3" id="流程单号3"  @keydown="ent1($event, '流程单号2', '流程单号3', '流程单号4')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号4" id="流程单号4"  @keydown="ent1($event, '流程单号3', '流程单号4', '流程单号5')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号5" id="流程单号5"  @keydown="ent1($event, '流程单号4', '流程单号5', '流程单号6')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号6" id="流程单号6"  @keydown="ent1($event, '流程单号5', '流程单号6', '流程单号7')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号7" id="流程单号7"  @keydown="ent1($event, '流程单号6', '流程单号7', '流程单号8')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号8" id="流程单号8"  @keydown="ent1($event, '流程单号7', '流程单号8', '流程单号9')" style="width: 60px; margin-right: 5px;"/>
								<el-input v-model="formData.流程单号9" id="流程单号9"  @keydown="ent1($event, '流程单号8', '流程单号9', '备注')" style="width: 60px;"/>
							</el-form-item>			  			
						 </el-col>
						 <el-col :span="7">
							<el-form-item label="备注" prop="id" class="mab" label-width="50px">
								<el-input v-model="formData.qczl_NumDesc" id="备注"  @keydown="ent1($event, '流程单号9', '备注', 'bh1')"   />
							</el-form-item>
						 </el-col>
					   </el-row>
								   
								   
				<el-row :gutter="24">
					 <el-col :span="6">
					   <el-form-item label="换模补产工时" prop="id" class="mab" label-width="96px">
						 <el-input v-model="formData.sczl_装版工时" id="换模补产工时"  @keydown="ent1($event, '备注', '换模补产工时', '设备保养工时')"   />
					   </el-form-item>
					 </el-col>
					 <el-col :span="6">
						<el-form-item label="设备保养工时" prop="id" class="mab" label-width="100px">
							<el-input v-model="formData.sczl_保养工时" id="设备保养工时"  @keydown="ent1($event, '换模补产工时', '设备保养工时', '异常停机')"   />
						</el-form-item>
					 </el-col>
					 <el-col :span="6">
					   <el-form-item label="异常停机" prop="name" class="mab" >
						 <el-input v-model="formData.sczl_异常停机工时" id="异常停机"  @keydown="ent1($event, '设备保养工时', '异常停机', '设备通电工时')"   />
					   </el-form-item>
					 </el-col>
					 <el-col :span="6">
					   <el-form-item label="设备通电工时" prop="name" class="mab" label-width="100px">
						 <el-input v-model="formData.sczl_设备运行工时" id="设备通电工时"  @keydown="ent1($event, '异常停机', '设备通电工时', 'sczl_bh1')"   />
					   </el-form-item>
					 </el-col>
				</el-row>				   
						   
				<el-row :gutter="24" class="mab" >
					<el-col :span="2"><span>组员信息</span></el-col>
					<div v-for="index in 8" :key="index">
					  <div style="width: 50px;margin-right: 50px;">
						<el-input style="width: 90px; margin-right: 5px; margin-bottom: 5px;" v-model="formData['sczl_bh' + index]" :id="'bh' + index" @keydown="ent1($event, index.toString())" />
						<el-input style="width: 90px; margin-right: 5px; margin-bottom: 5px; color: red;" :readonly="true" :value="formData['sczl_bh' + index + '_name']" :id="'name' + index" @keydown="ent1($event)"/>
						<el-input style="width: 90px; margin-right: 5px;" v-model="formData['sczl_rate' + index]" :id="'rate' + index" @keydown="ent1($event)"/>
					  </div>
					</div>
				</el-row>	
																 
				<el-row :gutter="24">
			   <el-col :span="24">
			     <el-form-item label="其他备注" prop="id">
			       <el-input v-model="formData.sczl_desc" id="其他备注"  @keydown="ent1($event, 'NumDesc8', '其他备注', '日期')"   />
			     </el-form-item>
			   </el-col>
			 </el-row>													 
						   
			 </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="dialogSelectVisible"
            title="选择"
            destroy-on-close
            width="600px"
			>
            <el-table
              tooltip-effect="dark"
              :data="selectData"
              row-key="ID"
              highlight-current-row="true"
              border
              style="width:100%"
              @row-dblclick="handleSelectClick"
            >
              <el-table-column
                prop="Gd_cpmc"
                label="印件名称"
                width="340"
              />
			  <el-table-column
			    prop="jyGx"
			    label="检验工序"
			    width="150"
			  />
              <el-table-column
                prop="Gy0_gxmc"
                label="工序名称"
                width="150"
              />			 
            </el-table>
          </el-dialog>
		  
		  
		  <el-dialog
		    v-model="GetMachineDedhVisible"
		    title="选择"
		    destroy-on-close
		    width="600px"
		  			>		     
		       <el-aside width="250px">
		         <div class="JKWTree-tree">		          
		           <el-tree :data="GetMachineDedhtreeData" :props="defaultProps" highlight-current="true"
		             @node-click="GetMachineDedhhandleNodeClick" @node-dblclick="handleNodeDoubleClick"></el-tree>
		         </div>
		       </el-aside>		       
		  </el-dialog>
		  
		  
		  <el-dialog
		    v-model="GetjtbhVisible"
		    title="选择"
		    destroy-on-close
		    width="600px"
		  			>
		    <el-table
		      tooltip-effect="dark"
		      :data="JTBHselectData"
		      row-key="ID"
		      highlight-current-row="true"
		      border
		      style="width:100%"
		      @row-dblclick="JTBHSelectClick"
		    >
		      <el-table-column
		        prop="jtbh"
		        label="机台编号"
		        width="150"
		      />
			  <el-table-column
				prop="jtmc"
				label="机台名称"
				width="400"
			  />		      	 
		    </el-table>
		  </el-dialog>
		  
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script setup>
import {
  getMachineCount,
  getDateMachine,
  machineLocate,
  MachineInfo,
  getYg,
  getMachineGxMc,
  getMachineDedh,
  getMachineScrapFactor,
  getJtbh,
  machineEdit,
  machineDel,
  getMachineCountByGdbh,
  machineAdd
} from '@/api/jixiaoguanli/jitairibaobiao'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ref, reactive, nextTick, onMounted, onBeforeMount } from 'vue'
import { getPackingSideTable, getPackingTable } from '@/api/mes_api_gty/myapi'
import { login } from '@/api/user'
import { Layout, LayoutContent, LayoutHeader, LayoutSider } from '@arco-design/web-vue'
defineOptions({
  name: '06-packingDocuments'
})

// 侧边栏数据请求
const treeData = reactive([]);
let GetMachineDedhtreeData = reactive([]);
const getTabdata = async () => {
    //接口调用函数
    const response  = await getMachineCount();
	console.log(response)
//根据日期获取侧边栏
const transformedData = response.data.map(item => ({
	      label: `${item.sys_rq.replace(/-/g, '.')}【单据数: ${item.count}张】`,
	      children: item.sys.map(sysItem => ({
	        label: `${sysItem.sys_id} 【记录数: ${sysItem.count}张】`,
	        params: {
	          date: item.sys_rq.replace(/\./g, '-'),
	          sys_id: sysItem.sys_id,
	          total: sysItem.count,
	        },
	      })),
	    }));
	    treeData.splice(0, treeData.length, ...transformedData);
        displayMod.value = 'date'
	}

getTabdata();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
		  sczl_gdbh: '',
          sczl_yjgx: '',
          sczl_gxmc: '',
          sczl_jtbh: '',
          sczl_bzdh: '',
          sczl_rq: '',
          sczl_cl: '',
          sczl_PgCl: '',
          sczl_单据类型: '',
          sczl_dedh: '',
          sczl_装版工时: '',
          sczl_保养工时: '',
          sczl_异常停机工时: '',
          sczl_设备运行工时: '',
          sczl_废品率系数: '',
          sczl_检验类别: '',
          流程单号1 :'',
          流程单号2: '',
          流程单号3: '',
          流程单号4: '',
          流程单号5: '',
          流程单号6: '',
          流程单号7: '',
          流程单号8: '',
          流程单号9:'',
          qczl_NumDesc:'',
		  sczl_bh1: '',
		  sczl_bh2: '',
		  sczl_bh3: '',
		  sczl_bh4: '',
		  sczl_bh5: '',
		  sczl_bh6: '',
		  sczl_bh7: '',
		  sczl_bh8: '',
          sczl_bh1_name:'',
          sczl_bh2_name:'',
          sczl_bh3_name: '',
          sczl_bh4_name: '',
          sczl_bh5_name: '',
          sczl_bh6_name: '',
          sczl_bh7_name: '',
          sczl_bh8_name: '',
		  sczl_rate1: '',
		  sczl_rate2: '',
		  sczl_rate3: '',
		  sczl_rate4: '',
		  sczl_rate5: '',
		  sczl_rate6: '',
		  sczl_rate7: '',
		  sczl_rate8: '',
          sczl_desc:'',
          yj_yjmc: '',
})

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

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const tableData = reactive([])



const total = ref(0)
const page = ref(1)
const limit = ref(10)
const searchInfo = ref('')
const params = {
  type: '',
  date: '',
  sys_id: '',
  gdbh: '',
}

// 分页设置
const handleSizeChange = (val) => {
  switch (params.type) {
    case 'getTableData':
      getTableData()
      break
    case 'getLocateTable':
      GetmachineLocate()
      break
    default:
      break
  }
}

// 页面跳转
const handleCurrentChange = (val) => {
 switch (params.type) {
   case 'getTableData':
     getTableData()
     break
   case 'getLocateTable':
     GetmachineLocate()
     break
   default:
     break
 }
}

const getTableData = async() => {
	
	
	const response = await getDateMachine({
	  date: params.date, sys_id: params.sys_id,
	  page: page.value.toString(), limit: limit.value.toString(),
	})
	if (response.code === 0) {
		console.log(response)
	  const processedData = response.data.data.map(item => {
	    return {
	      ...item,
	      combinedProp: item.sczl_gdbh + '--'+item.yj_yjmc,
	      combinedProp2: item.sczl_yjgx + '-'+item.sczl_gxmc
	    };
	  });
	  tableData.splice(0, tableData.length, ...processedData);
	}
	
  // const response = await getDateMachine(params);
  // console.log(response)
  // if (response.code === 0) {
  //   const processedData = response.data.data.map(item => {
  //     return {
  //       ...item,
  //       combinedProp: item.sczl_gdbh + '--'+item.yj_yjmc,
  //       combinedProp2: item.sczl_yjgx + '-'+item.sczl_gxmc
  //     };
  //   });
  //   tableData.splice(0, tableData.length, ...processedData);
  // }
}

//定位
const GetmachineLocate = async () => {
  const response = await machineLocate({
    gdbh: params.gdbh,
    page: page.value.toString(), limit: limit.value.toString(),
  })
  console.log(response)
  if (response.code === 0) {
    const processedData = response.data.rows.map(item => {
      return {
        ...item,
        combinedProp: item.sczl_gdbh + '--'+item.yj_yjmc,
        combinedProp2: item.sczl_yjgx + '-'+item.sczl_gxmc
      };
    });
	  total.value = response.data.total
    tableData.splice(0, tableData.length, ...processedData);
  }
  // if (response.code === 0) {
  //   total.value = response.data.total
  //   tableData.splice(0, tableData.length, ...response.data.rows)
  // }
  
  // const response = await machineLocate(locatevalue);
  // console.log(locatevalue)
  // console.log(response)
  // if (response.code === 0) {
  //   tableData.splice(0, tableData.length, ...response.data.rows);
  // }
}

//获取详细信息
const GetMachineInfo = async (value) => {
  const response = await MachineInfo({UniqId:value});
  console.log(response) 
  if (response.code === 0) {
	formData.value=response.data;
  }
}

//键盘 input框跳转
const ent1 = (event) => {
  const inputs = document.getElementsByTagName('input');
  const currentIndex = Array.from(inputs).indexOf(event.target);
  if (event.keyCode === 13 || event.keyCode === 40) { // Enter 或向下箭头
	  if(event.target.id=='其他备注'){
		  ElMessageBox.confirm('数据存盘?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				  }).then(() => {
					enterDialog()
				})
	  }
    for (let i = currentIndex + 1; i < inputs.length; i++) {
      if (!inputs[i].readOnly) {
		  nextTick(()=>{
			  inputs[i].focus();
			  inputs[i].select();
		  })
        break;
      }
    }
	if(event.target.id.substring(0, 2)=='cl' || event.target.id.substring(0, 2)=='fp'){
		ent_sum()
	}
  } 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;
      }
    }
	if(event.target.id.substring(0, 2)=='cl' || event.target.id.substring(0, 2)=='fp'){
		ent_sum()
	}
  } else if (event.keyCode === 8) { // 删除箭头
    if (event.target.selectionStart === 0) {
      for (let i = currentIndex - 1; i >= 0; i--) {
        if (!inputs[i].readOnly) {
          nextTick(()=>{
          	inputs[i].focus();
			inputs[i].setSelectionRange(0, 0);
          })
          break;
        }
      }
	  if(event.target.id.substring(0, 2)=='cl' || event.target.id.substring(0, 2)=='fp'){
	  	ent_sum()
	  }
    }
  } 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;
        }
      }
	  if(event.target.id.substring(0, 2)=='cl' || event.target.id.substring(0, 2)=='fp'){
	  	ent_sum()
	  }
    }
  } else if (event.keyCode === 39) { // 向右箭头
	  if(event.target.id=='其他备注'){
		  ElMessageBox.confirm('数据存盘?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				  }).then(() => {
					enterDialog()
				})
	  }
    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;
        }
      }
    }
	if(event.target.id.substring(0, 2)=='cl' || event.target.id.substring(0, 2)=='fp'){
		ent_sum()
	}
  }
}


//获取员工信息
const GetYg = async (value,inputName) => {
  const response = await getYg({sczl_bh:value});
  console.log(response) 
  if (response.code === 0) {
	console.log(response.data.ygxm) 
	let Bname = 'sczl_bh' + inputName+'_name';
	formData.value[Bname]=response.data.ygxm
	// console.log(formData.value[Bname])
  }
}
//员工编号回车事件
const getGxMcsubmit = (event, inputName) => {

	  console.log(inputName)
	  let combinedString = 'sczl_bh' + inputName;
	  console.log(combinedString)
	 //  let variableName = 'sczl_gdbh'+inputName;
	  let variableValue = eval('formData.value.' + combinedString);
	  console.log(variableValue)
	  GetYg(variableValue,inputName)
}

const dialogSelectVisible = ref(false)
const GetMachineDedhVisible = ref(false)
const selectData = reactive([])
const GetjtbhVisible = ref(false)
const JTBHselectData = reactive([])
//查询印件工序及产品名称
const GetMachineGxMc = async () => {
  console.log(formData.value.sczl_gdbh)
  const response = await getMachineGxMc({gdbh:formData.value.sczl_gdbh});
  console.log(response) 
 
  if (response.code === 0) {
	  if(response.data.length==1){
	  const { Gd_cpmc, Gy0_yjno, Gy0_gxh, Gy0_gxmc,jyGx} = response.data[0]
	  formData.value.yj_yjmc=Gd_cpmc
	  formData.value.sczl_gxmc=Gy0_gxmc
	  formData.value.sczl_yjgx=jyGx
	  console.log(Gy0_gxmc)
	  console.log(formData.value.sczl_gxmc)	  
	  }else{
		  
		  selectData.splice(0, selectData.length, ...response.data)
		  dialogSelectVisible.value=true
	  }
	// console.log(response.data.ygxm) 
	// let Bname = 'sczl_bh' + inputName+'_name';
	// formData.value[Bname]=response.data.ygxm
	// // console.log(formData.value[Bname])
	// console.log(response.data.length)
  }
}
//工单编号回车事件
const getMachineGxMcsubmit = async() => {

  console.log(formData.value.sczl_gdbh) 
  GetMachineGxMc()
}


// 处理选择框
const handleSelectClick = (row, column, event) => {
  const { Gd_cpmc, Gy0_yjno, Gy0_gxh, Gy0_gxmc,jyGx } = row
  formData.value.yj_yjmc=Gd_cpmc
  formData.value.sczl_gxmc=Gy0_gxmc
  formData.value.sczl_yjgx=jyGx
  dialogSelectVisible.value = false
}

//获取定额代号
const GetMachineDedh = async (value) => {
  const response = await getMachineDedh();
  console.log(response)
  const treeData = {};
  if(response.code==0){
	  
	  // 遍历接口返回的数据，构建父子关系
response.data.bh_mc.forEach(item => {
  if (item.sys_bh === response.data.sys_bh) {
    if (!treeData[item.sys_bh]) {
      treeData[item.sys_bh] = { label: item.sys_bh, children: [] };
    }
    treeData[item.sys_bh].children.push({ label: item.sys_bh + item.sys_mc, params: { sys_bh: item.sys_bh } });
  } else if (item.sys_bh.startsWith(response.data.sys_bh)) {
    if (!treeData[response.data.sys_bh]) {
      treeData[response.data.sys_bh] = { label: response.data.sys_bh, children: [] };
    }
    treeData[response.data.sys_bh].children.push({ label: item.sys_bh + item.sys_mc, params: { sys_bh: item.sys_bh } });
  }
});
      // 将父子关系转换为数组
      const transformedData = Object.values(treeData);
	  console.log(transformedData)
	  GetMachineDedhtreeData = transformedData;
	  
	   // const treeData = fillDataToTree(response);
	   // console.log(treeData)
	   // // GetMachineDedhtreeData=treeData
	   // GetMachineDedhtreeData.splice(0, GetMachineDedhtreeData.length, ...treeData);
	   // const GetMachineDedhtreeData=
	    GetMachineDedhVisible.value=true
		console.log(formData)
  }

}
//定额代号树形结构单机
const GetMachineDedhhandleNodeClick = (node,check,nodeData) => {
  //存放当前节点的nodeId
  //存放当前节点的nodeId
  if (node.params) {
       // 点击的是父节点
       // 执行相应的父节点单击事件处理逻辑
	   console.log(node.params)
	    formData.value.sczl_dedh=node.params.sys_bh
		console.log(formData.value.sczl_dedh)
		GetMachineDedhVisible.value=false
     } else {
       // 点击的是子节点
       // 执行相应的子节点单击事件处理逻辑
       console.log('11111');
	   console.log(node.params)
       // 例如，您可以在这里执行子节点单击事件触发的操作
     }
}




const GetJtbh = async () => {
  const response = await getJtbh({sys_mc:'检验车间'});
  if(response.code==0){
	  if(response.data.length==1){
	  // const { Gd_cpmc, Gy0_yjno, Gy0_gxh, Gy0_gxmc,jyGx} = response.data[0]
	  // formData.value.yj_yjmc=Gd_cpmc
	  // formData.value.sczl_gxmc=Gy0_gxmc
	  // formData.value.sczl_yjgx=jyGx
	  // console.log(Gy0_gxmc)
	  // console.log(formData.value.sczl_gxmc)	  
	  }else{
	  		  
	  		  JTBHselectData.splice(0, selectData.length, ...response.data)
	  		  GetjtbhVisible.value=true
	  }  
  }
  console.log(response)
}

const JTBHSelectClick = (row, column, event) => {
  const { jtbh, jtmc } = row
  formData.value.sczl_jtbh=jtbh
  GetjtbhVisible.value = false
}


const getJtbhsubmit = () => {
	 GetJtbh()
}
//定额代号回车事件
const getMachineDedhsubmit = () => {

	 GetMachineDedh()
}
//刷新废品率系数
const GetMachineScrapFactor = async (value) => {
  const response = await getMachineScrapFactor(value);
  if(response.code==0){
	console.log(response.data.num)
	const rowIndex = tableData.findIndex(row => row.UniqId === lastCellValue);
	console.log(rowIndex)
	tableData[rowIndex].sczl_废品率系数 = response.data.num;
  }
  // console.log(response)
  // const rowIndex = tableData.findIndex(row => row.UniqId === 123);
}

// 更新数据
const updateDetailData = async() => {
  const restoredData = {
    UniqId: lastCellValue,
    sczl_rq: formData.value.sczl_rq,
    sczl_bzdh: formData.value.sczl_bzdh,
    sczl_gdbh: formData.value.sczl_gdbh,
    sczl_yjgx: formData.value.sczl_yjgx,
    sczl_gxmc: formData.value.sczl_gxmc,
    sczl_jtbh: formData.value.sczl_jtbh,
    sczl_单据类型: formData.value.sczl_单据类型,
	sczl_检验类别: formData.value.sczl_检验类别,
	sczl_废品率系数: formData.value.sczl_废品率系数,
	sczl_cl: formData.value.sczl_cl,
	sczl_PgCl: formData.value.sczl_PgCl,
	sczl_dedh: formData.value.sczl_dedh,
	qczl_Num: formData.value.流程单号1,
	qczl_NumDesc1: formData.value.流程单号2,
	qczl_NumDesc2: formData.value.流程单号3,
	qczl_NumDesc3: formData.value.流程单号4,
	qczl_NumDesc4: formData.value.流程单号5,
	qczl_NumDesc5: formData.value.流程单号6,
	qczl_NumDesc6: formData.value.流程单号7,
	qczl_NumDesc7: formData.value.流程单号8,
	qczl_NumDesc8: formData.value.流程单号9,
	qczl_NumDesc: formData.value.qczl_NumDesc,
	sczl_装版工时: formData.value.sczl_装版工时,
	sczl_保养工时: formData.value.sczl_保养工时,
	sczl_异常停机工时: formData.value.sczl_异常停机工时,
	sczl_设备运行工时: formData.value.sczl_设备运行工时,
	sczl_bh1: formData.value.sczl_bh1,
	sczl_bh2: formData.value.sczl_bh2,
	sczl_bh3: formData.value.sczl_bh3,
	sczl_bh4: formData.value.sczl_bh4,
	sczl_bh5: formData.value.sczl_bh5,
	sczl_bh6: formData.value.sczl_bh6,
	sczl_bh7: formData.value.sczl_bh7,
	sczl_bh8: formData.value.sczl_bh8,
	sczl_rate1: formData.value.sczl_rate1,
	sczl_rate2: formData.value.sczl_rate2,
	sczl_rate3: formData.value.sczl_rate3,
	sczl_rate4: formData.value.sczl_rate4,
	sczl_rate5: formData.value.sczl_rate5,
	sczl_rate6: formData.value.sczl_rate6,
	sczl_rate7: formData.value.sczl_rate7,
	sczl_rate8: formData.value.sczl_rate8,
	sczl_desc: formData.value.sczl_desc,
	sys_id:'[1008/姜剑娟]',
  }
  // detailData.table.forEach((item, index, array) => {
  //   const num = index + 1
  //   restoredData[`sczl_gdbh${num}`] = item.sczl_gdbh
  //   restoredData[`sczl_yjGx${num}`] = item.sczl_yjGx
  //   restoredData[`sczl_gxmc${num}`] = item.sczl_gxmc
  //   // restoredData[`Gd_cpmc${num}`] = item.Gd_cpmc
  //   restoredData[`sczl_cl${num}`] = item.sczl_cl
  //   restoredData[`sczl_PgCl${num}`] = item.sczl_PgCl
  //   restoredData[`sczl_clAdd${num}`] = item.sczl_clAdd
  // })
  if(ADD.value=='新增'){
  	 // console.log('新增')
  	 console.log('新增')
  	 console.log(ADD.value)
  	 console.log(restoredData)
  	 const response = await machineAdd(restoredData);
  	 // ADD.value='1'
  	 // console.log(ADD.value)
  	 ADD.value='0'
  	 console.log(response)
  	 if(response.code==0){
  	 		 ElMessage({
  	 		   type: 'success',
  	 		   message: '新增成功',
  	 		 })
  	 }
  	 dialogFormVisible.value = false
  }else{
		 console.log(restoredData)
  	     console.log(lastCellValue)
  	     formData.value.UniqId=lastCellValue
  	     console.log(formData)
  	 	restoredData.UniqId='5'
  	    const res = await machineEdit(restoredData);
  	   // console.log(FormData)
  	   console.log(res)
	   if(res.code==0){
	   ElMessage({
	     type: 'success',
	     message: '更新成功',
	   })
	   }
	   dialogFormVisible.value = false
  	 }
	
  }
 
//删除
const MachineDel = async () => {
  const response = await machineDel({UniqId:lastCellValue});
  if (response.code === 0) {
	
	ElMessage({
	  type: 'success',
	  message: '删除成功',
	})
  }
  getTableData()
}
const handleNodeClick = (node,check) => {
  //存放当前节点的nodeId
  //存放当前节点的nodeId
  if (node.params) {
    params.date = node.params.date;
    params.sys_id = node.params.sys_id;
    total.value = node.params.total;
	   params.type = 'getTableData'
	    page.value = 1
    getTableData();
  }
}

const locatevalue={
	gdbh:'',
	cpmc:'',
	page:'5',
	limit:'10',  
}
let positionvalue=ref()
// 搜索
function onSearch() {
	params.gdbh = positionvalue.value
	params.type = 'getLocateTable'
	page.value = 1
	GetmachineLocate()
}
// 刷新废品率系数
function onRefresh() {
	GetMachineScrapFactor(ScrapFactor)
}
const ADD=ref('0')
//新增
function onAdd() {
	ADD.value='新增'
	type.value = 'create'
	if(typeof(lastCellValue)=='number'){
		GetMachineInfo(lastCellValue)
	}
	dialogFormVisible.value = true
	// Productionadd()
}
//删除
function onDel() {
	MachineDel()
}
const displayMod = ref('')
// 按工单显示
function onCountByGdbh() {
	console.log(displayMod.value)
	if (displayMod.value === 'date') {
	   displayMod.value = 'gd'	
	   CountByGdbh()
	   console.log(displayMod.value)
	} else {
	  getTabdata()
	}
	// CountByGdbh()
}
//按工单显示
const CountByGdbh = async () => {
  const response = await getMachineCountByGdbh();
  // console.log(response)
   treeData.splice(0, treeData.length);
  if (response.code === 0) {
	  console.log(response)
	  
	const transformedData = response.data.map(item => ({
		      label: `${item.sczl_gdbh+item.cpmc}`,
		      children: item.sys.map(sysItem => ({
		        label: `${sysItem.sys_id} 【记录数: ${sysItem.count}张】`,
		        params: {
		          date: item.sczl_gdbh,
		          sys_id: sysItem.sys_id,
		          total: sysItem.count,
		        },
		      })),
		    }));
		    treeData.splice(0, treeData.length, ...transformedData);
			
  }
  // getTableData()
}
// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([
	
])
// 多选
const ScrapFactor={
	gdbh:'',
	yjno:'',
	gxh:'',
	type:'',
}
const handleSelectionChange = (val) => {
	
  // multipleSelection.value = val
  if(val.length>0){
  	multipleSelection.value = val
  	const lenth=val.length
	ScrapFactor.gdbh=val[lenth-1].combinedProp.split('-')[0];
	const parts = val[lenth-1].combinedProp2.split('-')
	ScrapFactor.yjno=parts[0];
	ScrapFactor.gxh=parts[1];
	ScrapFactor.type=val[lenth-1].sczl_检验类别
	console.log(ScrapFactor)
  	lastCellValue=val[lenth-1].UniqId
  	console.log(val)
  	val.splice(0, val.length);  // 清空 val 数组	
  	console.log(lastCellValue)
  }
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
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 type = ref('')

// 更新行
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
  }
}

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

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    address: '',
    image: '',
    name: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
  // elFormRef.value?.validate(async (valid) => {
  //   if (!valid) return
  //   let res
  //   switch (type.value) {
  //     case 'create':
  //       res = await createCompany(formData.value)
  //       break
  //     case 'update':
  //       res = await updateCompany(formData.value)
  //       break
  //     default:
  //       res = await createCompany(formData.value)
  //       break
  //   }
  //   if (res.code === 0) {
  //     ElMessage({
  //       type: 'success',
  //       message: '创建/更改成功'
  //     })
  //     closeDialog()
  //     getTableData()
  //   }
  // })
  updateDetailData()
}
//键盘 input框跳转
const ent = (event,id1,id2,id3) => {

  if (event.keyCode === 13 || event.keyCode === 40) { // Enter 或向下箭头
    const idMap = {
       'bh0': '0',
       'bh1': '1',
       'bh2': '2',
       'bh3': '3',
       'bh4': '4',
       'bh5': '5',
       'bh6': '6',
       'bh7': '7',
       'bh8': '8',
     };
	if(id2=='工单编号'&&event.keyCode === 13){
		getMachineGxMcsubmit()
	}else if(id2=='机台编号'&&event.keyCode === 13){
		getJtbhsubmit()
	}else if(id2=='定额代号'&&event.keyCode === 13){
		getMachineDedhsubmit()
	}else if (idMap.hasOwnProperty(id2) && event.keyCode === 13) {
	    getGxMcsubmit('', idMap[id2]);
	}else if(id3!=''){
      document.getElementById(id3).focus()
    }	
  } else if (event.keyCode === 38) { // 向上箭头
    if(id1!=''){
      document.getElementById(id1).focus()
    }
  }else if (event.keyCode === 8) { // 删除箭头
    if(id1!='' && document.getElementById(id2).value==''){
      document.getElementById(id1).focus()
    }
    console.log(document.getElementById(id2).value)
  }else if (event.keyCode === 37) { // 向左箭头
    if(id1!='' && document.getElementById(id2).selectionStart==0){
      document.getElementById(id1).focus()
    }
  }else if (event.keyCode === 39) { // 向右箭头
    if(id3!='' && document.getElementById(id2).selectionStart == document.getElementById(id2).value.length){
      document.getElementById(id3).focus()
    }
  }
}
let table=ref(5);
let lastCellValue=ref()
// 双击表格操作
function doubleClick(row, column, event) {
		  type.value = 'update';		  
		  lastCellValue= row['UniqId'];
  		 console.log(lastCellValue)
  	    table.value=lastCellValue
	 	 dialogFormVisible.value = true
		// dialogSelectVisible.value = true
  GetMachineInfo(table.value)
}
// 单击表格操作
function Click(row, column, event) {
    lastCellValue= row['UniqId'];
   console.log(lastCellValue)
  // if(row['table_type']=='db_sczl'){
  // 	 dialogFormVisible.value = true
  // 	 GetInfo(table.value)
  // }else{
	 //  console.log('此数据不展示详细信息')
  // }  
}
// 导出excel
function exportExcel() {
  console.log('导出到excel');
}

// 生命周期钩子
onMounted(async () => {
});
</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;
}
</style>