<template>
  <div>
	<layout>
	  <layout-content >
		<div class="gva-table-box">
			<div style="display: flex; align-items: baseline; margin-bottom: 10px;">
			    <h1 style="margin: 0;">{{_code}}完工报工</h1>
			</div>
		      <el-row :gutter="10" style="align-items: center; margin-bottom: 20px;">
		      	<!-- 子订单编号输入框 -->
		      	<el-col :span="4"  style="padding: 0px;margin: 0px;">
		      	  <el-input v-model="add_searchInfo" placeholder="请扫描子订单编号条码"@keyup.enter="add_onSubmit" id="searchInput" style="width: 100%; height: 50px;"/>
		      	</el-col>
		      
		      	<!-- 查询按钮 -->
		      	<el-col :span="1.5"  style="padding: 0px;margin: 0px;">
		      	  <el-button type="primary" icon="search" @click="add_onSubmit"style="height: 50px;width: 80px;">查询</el-button>
		      	</el-col>
		      
		      	<el-col :span="1.5" style="padding: 0px;margin: 0px;">
		      	  <el-text style="font-size: 30px;">机台号</el-text>
		      	</el-col>
		      	<!-- 机台号输入框 -->
		      	<el-col :span="2"><el-input v-model="add_formData['机台号']" readonly style="width: 100%; height: 40px;"/></el-col>
		         
		      	<el-col :span="1.5" style="padding: 0px;margin: 0px;">
		      		<el-text style="font-size: 30px;">工序</el-text>
		      	</el-col>
		      	<!-- 工序输入框 -->
		      	<el-col :span="2"><el-input v-model="add_formData['工序']"  readonly  style="width: 100%; height: 40px;" /></el-col>
		      
		      	<el-col :span="1.5" style="padding: 0px;margin: 0px;">
		      		<el-text style="font-size: 30px;">组别</el-text>
		      	</el-col>
		      	<!-- 组别输入框 -->
		      	<el-col :span="2"><el-input v-model="add_formData['组别']" readonly  style="width: 100%; height: 40px;" /></el-col>
		      
		      	<el-col :span="1.5" style="padding: 0px;margin: 0px;">
		      		<el-text style="font-size: 30px;">人员</el-text>
		      	</el-col>
		      	<!-- 人员输入框 -->
		      	<el-col :span="2"><el-input v-model="add_formData['人员']" readonly style="width: 100%; height: 40px;"/></el-col>
		      </el-row>
			  
			
			<el-row :gutter="0">
				<el-col :span="2.5">
					<el-text style="font-size: 24px; margin-left: 70px;">尺 码&nbsp;</el-text>
				</el-col>
				<el-col v-for="(item, index) in 10" :key="index" :span="1" style="padding: 0; margin: 0;">
					<el-input v-model="cmformdata[`cm${index + 1}`]" :id="`cm${index + 1}`" readonly style="width: 70px; height: 40px;"/>
				</el-col>
				<el-col :span="1"><el-input v-model="cmformdata.cmtotal" id="cmtotal" readonly style="width: 80px;height: 40px;" /></el-col>
			</el-row>
					
			<el-row :gutter="0">
				<el-col :span="2.5">
					<el-text style="font-size: 24px; margin-left: 53px;">制单数&nbsp;</el-text>
				</el-col>
				<el-col v-for="(item, index) in 10" :key="index" :span="1" style="padding: 0; margin: 0;">
					<el-input v-model="cmslformdata[`cmsl${index + 1}`]" :id="`cmsl${index + 1}`" readonly style="width: 70px; height: 40px;"/>
				</el-col>
				<el-col :span="1"><el-input v-model="cmslformdata.zdtotal" id="zdtotal" readonly style="width: 80px;height: 40px;" /></el-col>
			</el-row>
			
			<el-row :gutter="0">
				<el-col :span="2.5">
					<el-text style="font-size: 24px; margin-left: 10px;">新增实裁数</el-text>
				</el-col>
				<el-col v-for="(item, index) in 10" :key="index" :span="1" style="padding: 0; margin: 0;">
					<el-input v-model="scsformdata[`scs${index + 1}`]" :id="`scs${index + 1}`" @input="updateTotal"  style="width: 70px; height: 40px;"/>
				</el-col>
				<el-col :span="1"><el-input v-model="scsformdata.sctotal" id="sctotal" readonly style="width: 80px;height: 40px;" /></el-col>
			</el-row>
			
			
		      <el-main>
				<!-- 表格数据 -->
				  <el-tabs v-model="activeName">
					  <el-tab-pane label="报工历史记录"   @click="showTable('报工历史记录')" name="first">
						<el-table ref="multipleTable" style="width: 100%;height: 52vh" tooltip-effect="dark"
								  :row-style="{ height: '50px' }" :header-cell-style="{ padding: '5px', fontSize: '20px' }"
								  :cell-style="{ padding: '10px', fontSize: '20px' }" :header-row-style="{ height: '20px' }"
								  :data="bgjdhz_tableData"  border row-key="ID"
								  size="small" 
								  highlight-current-row="true" @row-dblclick="updateCompanyFunc"
								  @row-click="tableRowClick" :show-overflow-tooltip="true"
								  @selection-change="selectionChange">
								  <el-table-column type="selection" width="60" />
								  <el-table-column align="left" label="报工时间"	prop="sys_rq"  		width="150"/>
								  <el-table-column align="left" label="子订单编号" prop="子订单编号"  	width="130"/>
								  <el-table-column align="left" label="生产款号" 	prop="款号"  	width="120"/>
								  <el-table-column align="left" label="款式" 		prop="款式"  		width="100"/>
								  <el-table-column align="left" label="组别" 		prop="sczl_jtbh"  		width="80"/>
								  <el-table-column align="left" label="尺码" 		prop="尺码"  		width="70"/>
								  <el-table-column align="left" label="实裁数量" 		prop="数量"  		width="100"/>
						</el-table>
					  </el-tab-pane>
					  
					  
					<el-tab-pane label="产量进度汇总记录"   @click="showTable('产量进度汇总记录')" name="two">
						<el-table ref="multipleTable" style="width: 100%;height: 52vh" tooltip-effect="dark"
								  :row-style="{ height: '50px' }" :header-cell-style="{ padding: '5px', fontSize: '20px' }"
								  :cell-style="{ padding: '10px', fontSize: '20px' }" :header-row-style="{ height: '20px' }"
								  :data="jdhz_tableData"  border row-key="ID"
								  size="small" 
								  show-summary  :summary-method="getSummaries"
								  highlight-current-row="true" @row-dblclick="updateCompanyFunc"
								  @row-click="tableRowClick" :show-overflow-tooltip="true"
								  @selection-change="handleSelectionChange">
								  <el-table-column  align="left" label="订单子编号" prop="子订单编号"  width="130"/>
								  <el-table-column  align="left" label="款号" prop="款号" width="140" />
								  <el-table-column  align="left" label="色系名称" prop="颜色" width="100" />
								  <el-table-column v-for="item in sizeDatas" :key="item" align="left" :label="item" :prop="item" width="60" :cell-style="cellStyle">
									<template v-slot="scope">
										<div style="width: 80px;" @click="handleSizeClick(scope.$index, item, scope.row)">
											{{ scope.row[item] }}
										</div>
									</template>
								  </el-table-column>
								  <el-table-column  align="left" label="实裁总数" 	 prop="裁剪数" width="90" />
								  <!-- <el-table-column  align="left" label="上报时间" prop="上报时间" width="160" /> -->
						</el-table>
					</el-tab-pane>
					
					<el-tab-pane label="订单资料附件" name="third">
					  <el-table ref="multipleTable"
								:row-style="{ height: '30px' }"
								:cell-style="{ padding: '0px' }" :header-row-style="{ height: '30px' }"
								:header-cell-style="{ padding: '0px' }"
								:show-overflow-tooltip="true"
								:cell-class-name="planUsageCellClass"
								highlight-current-row="true"
								@row-dblclick="gdbomupdateCompanyFunc"
								style="width: 100%;height: 36vh" border tooltip-effect="dark" :data="ddtableData" row-key="ID"
											   @selection-change="fjSelectionChange">
					   <el-table-column align="left" label="关联编号" prop="关联编号"  width="115"/>
					   <el-table-column align="left" label="备注" 	prop="附件备注"  width="110"/>
					   <el-table-column align="left" label="文件类型" prop="附件类型"  width="100"/>
					   <el-table-column align="left" label="建档时间" prop="sys_rq"  width="160"/>
					   <el-table-column align="left" label="建档用户" prop="sys_id"  width="200"/>
									 <el-table-column align="left" label="操作"width="100"fixed="right">
									   <template #default="scope">
										 <el-button type="success" size="small" :data="ddtableData" @click="showPdf(scope.row)" >PDF预览</el-button> 
									   </template>
									 </el-table-column>
					  </el-table>
					</el-tab-pane> 
					
					
					<el-tab-pane label="技术附件" @click="showTable('技术附件')" name="fourth">
						<el-table ref="multipleTable"
										  :row-style="{ height: '30px' }"
										  :cell-style="{ padding: '0px' }" :header-row-style="{ height: '30px' }"
										  :header-cell-style="{ padding: '0px' }"
										  :show-overflow-tooltip="true"
										  :cell-class-name="planUsageCellClass"
										  highlight-current-row="true"
										  @row-dblclick="ExcelShow"
										  style="width: 100%;height: 36vh" border tooltip-effect="dark" :data="jstableData" row-key="ID" @selection-change="fjSelectionChange">
									  <el-table-column align="left" label="关联编号" prop="关联编号"  width="115"/>
									  <el-table-column align="left" label="备注" 	prop="附件备注"  width="110"/>
									  <el-table-column align="left" label="文件类型" prop="附件类型"  width="100"/>
									  <el-table-column align="left" label="建档时间" prop="sys_rq"  width="160"/>
									  <el-table-column align="left" label="建档用户" prop="sys_id"  width="200"/>
									  <el-table-column align="left" label="操作"width="100"fixed="right">
										<template #default="scope">
										  <el-button type="success" size="small" :data="ddtableData" @click="showPdf(scope.row)" >PDF预览</el-button> 
										</template>
									  </el-table-column>
						</el-table>
					  </el-tab-pane>
					</el-tabs>
					
					<el-button  type="danger" icon="delete" @click="del_delclick"
					  v-if="delall === true" :disabled="Selection === ''"
					  :style="{
					    backgroundColor: Selection === '' ? '' : 'red',
					    borderColor: Selection === '' ? '' : 'red',
					    color: Selection === '' ? '' : '#fff'
					  }"
					  style="width: 150px; height: 40px; font-size: 20px; margin-left: 10px;">删除报工</el-button>
					  <el-button type="primary" @click="cp_gdprintonClick" style="width: 150px; height: 40px; font-size: 20px; margin-left: 10px;" >  子订单详情页 </el-button>
					  <el-button type="primary" @click="add_Dialog" style="width: 100px; height: 40px; font-size: 20px; margin-left: 10px;" >报工</el-button>
					  <el-button type="primary" @click="return_Dialog" style="width: 100px; height: 40px; font-size: 20px; margin-left: 10px;" >退还</el-button>
				</el-main>
			</div>
			
				<!-- 是否订单尾包确认弹窗 -->
				<el-dialog v-model="DialogVisible" title="是否订单尾包" destroy-on-close width="30%" style="top: 20%;">
					<h3>请再次确认是否该订单产品已全部报工，该批为订单尾包？</h3>
					<div class="dialog-footer" style="text-align: right;">
						<el-button @click="confirmDialogVisible">取消</el-button>
						<el-button type="primary" @click="handleConfirm">确认</el-button>
					</div>
				</el-dialog>
				
				  <!-- 退还 -->
					<el-dialog v-model="res_bomdialogFormVisible" :before-close="res_bomcloseDialog" title="报工领用" width="100%" top="2%" destroy-on-close>
						<div class="dialog-footer">
						<el-button @click="res_bomcloseDialog">取消</el-button>
						<el-button type="primary" @click="res_bomenterDialog">确定</el-button>
						</div>
						<div style="width: 100%; height: 60px; padding: 0px; margin: 10px 0px 0px 0px; display: flex; align-items: center;">
						<el-form-item label="订单编号 :" prop="currentProcess" style="margin-right: 20px; padding: 0px">
							<el-input v-model="ddhformData['ddh']" disabled style="width: 200px;"/>
						</el-form-item>
						<el-form-item label="生产款号 :" prop="currentProcess" style="margin-right: 20px; padding: 0px">
							<el-input v-model="ddhformData['kh']" disabled style="width: 200px;"/>
						</el-form-item>
						</div>
						<div>
							<el-table ref="paichengRef"
									:show-overflow-tooltip="true"
									highlight-current-row="true"
									:row-style="{ height: '0px' }"
									:cell-style="{ padding: '0px' }" :header-row-style="{ height: '0px' }"
									:header-cell-style="{ padding: '0px' }"
									style="width: 100%;height: 60vh" border tooltip-effect="dark"
									:data="resbomtableData" row-key="ID"
									:cell-class-name="scfjfpxsCellClass">
							<template v-for="(item, idx) in resbom_tableColumns">
								<el-table-column #default="{ row, column, $index }" align="left" :label="item.label" :width="item.width" >
								<div v-if="['退还'].includes(item.prop)">
									<el-input v-model="row[item.prop]" :clearable="false"
											:id="`input${idx}${$index}`" @keyup="resbom_handleKeyDown($event, idx, $index, item.prop)"/>
								</div>
								<div v-else>{{ row[item.prop] }}</div>
								</el-table-column>
							</template>
							</el-table>
						</div>
					</el-dialog>
				
        </layout-content>
      </layout>
    <SubOrderPage ref="SubOrderPageRef" />
	<PrintPage ref="printPageRef" />
	<!-- 子订单详情页 -->
	<luckyexcelPage ref="luckyexcelPageRef" />
	</div>
  </template>
<script>
export default {
  data() {
    return {
		currentTable: '', // 当前展示的表格
		activeName: 'first',
		dialogFormVisible: false,
		formDataTest: {
		imageUrl: '' // 添加一个字段来保存上传的图片路径
		},
		rule: {} // 初始化rule对象
    };
  }, 
  methods: {
    handleKeyDown(event, prevId, currentId, nextId) {
      const currentElement = document.getElementById(currentId);
      const isEmpty = currentElement.value === '';
      const atStart = currentElement.selectionStart === 0;
      const atEnd = currentElement.selectionStart === currentElement.value.length;
      switch (event.keyCode) {
        case 13: // Enter
        case 40: // 向下箭头
          if (nextId) {
            document.getElementById(nextId).focus();
          }
          break;
        case 38: // 向上箭头
          if (prevId) {
            document.getElementById(prevId).focus();
          }
          break;
        case 8: // 删除键
          if (prevId && (isEmpty || atStart)) {
            document.getElementById(prevId).focus();
          }
          break;
        case 37: // 向左箭头
          if (prevId && atStart) {
            document.getElementById(prevId).focus();
          }
          break;
        case 39: // 向右箭头
          if (nextId && atEnd) {
            document.getElementById(nextId).focus();
          }
          break;
        default:
          break;
      }
    },
  },
};
</script>
<script setup>
// 全量引入格式化工具 请按需保留
import $script from 'scriptjs'
import $ from 'jquery';
import LuckyExcel from 'luckyexcel';
import { Layout, LayoutSider, LayoutContent } from '@arco-design/web-vue';
import {ref, reactive} from 'vue';
import {getSpotList,getInfo,OrderAttachments,getTabByGdbh,search,spotcheckdel,SubWorkOrderStatusList,Mabaolist,orderBomList,orderSearch,outReport} from '@/api/mes/job';
import {getMachineMac} from '@/api/jixiaoguanli/jitairibaobiao'
import {getMac} from '@/api/jixiaoguanli/baogong'
import {ElMessage} from "element-plus";
import PrintPage from '../yunyin/shengchanguanli/components/print.vue';
import luckyexcelPage from '../yunyin/shengchanguanli/components/luckyexcel.vue';
import SubOrderPage from '../yunyin/shengchanguanli/components/SubOrder.vue';
import { useUserStore } from '@/pinia/modules/user';
defineOptions({name: 'Company'})
const path = `${import.meta.env.VITE_BASE_PATH}:${import.meta.env.VITE_UPLOADS_PORT}`
console.log(path)
//定义跳转页面
const SubOrderPageRef = ref()//子订单详情页
const printPageRef = ref()//打印预览
const luckyexcelPageRef = ref()//pdf预览
//获取登录用户信息
const userStore = useUserStore()
const _username = ref('')
_username.value = userStore.userInfo.userName + '/' + userStore.userInfo.nickName
console.log('获取用户名称',_username.value)
//全局获取当前日期
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要补零
const day = String(today.getDate()).padStart(2, '0');
const hours = String(today.getHours()).padStart(2, '0');
const minutes = String(today.getMinutes()).padStart(2, '0');
const seconds = String(today.getSeconds()).padStart(2, '0');
const currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
const currentDates = `${year}-${month}-${day}`;
const add_searchInfo = ref('')

//全局获取code，接口接收code
const _code = '裁剪'
//全局接口接受的物理地址
const Machine = ref('')
//全局获取UniqId
const UniqId = ref('')

//物理地址获取机台编号
const getMachineMacdata = async () => {
  try {
    const data  = await getMachineMac({sys_sbID:Machine.value});
	if (data.data === null) {
		// ElMessage({
		// 	type: 'error',
		// 	message: '未获取到机台编号请确认MAC地址或与管理员联系'
		// })
		add_formData['机台号'] = '测试机台'
		add_formData['工序'] = _code
		add_formData['组别'] = "测试"
		add_formData['人员'] = "测试"
		return;
	}
	add_formData['机台号'] = data.data['机台号']
	add_formData['工序'] = data.data['生产工序']
	add_formData['组别'] = data.data['组别']
	add_formData['人员'] = data.data['组长']
	setTimeout(() => {
		const inputElement = document.getElementById('searchInput');
		if (inputElement) {
			inputElement.focus();		
		}
	}, 100); // 延迟100毫秒
  } catch (error) {
    console.error(error)
  }
}
//自动获取物理地址
const GetAddr =  () => {
  var xmlhttp = null;
  var res;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  // 2. 设置回调函数
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      res = eval('('+xmlhttp.response+')');
      let result = ''
      for (let i = 0; i < res.macAddress.length; i++) {
        if (i % 2 === 0 && i !== 0) {
          result += '-' // 根据实际需求修改分隔符
        }
        result += res.macAddress[i]
      }
	  Machine.value = result
    getMachineMacdata(Machine.value)
    }
  }
  // 3. 打开一个连接
  xmlhttp.open("get", "http://127.0.0.1:8090/init")
  //  5. 发送
   xmlhttp.send();
}
// getMachineMacdata();
GetAddr()
// PDF预览
const showPdf = async (row) => {
	luckyexcelPageRef.value.open(row)
}

const add_formData = reactive({
  机台号: '',	
  工序: '',
  组别: '',
  人员: '',	
  尺码: '',
  数量: '',
  是否订单尾包: '',
});
//清空对象的属性值
const gd_clearFormData = () => {
  Object.keys(add_formData).forEach(key => {
    add_formData[key] = '';
  });
};
// 尺码
const cmformdata = reactive({
  cm1:'',
  cm2:'',
  cm3:'',
  cm4:'',
  cm5:'',
  cm6:'',
  cm7:'',
  cm8:'',
  cm9:'',
  cm10:'',
  cm11:'',
  cm12:'',
  cmtotal:'合计',
});

// 制单数
const cmslformdata = reactive({
  cmsl1: '',  
  cmsl2: '',  
  cmsl3: '',  
  cmsl4: '',  
  cmsl5: '',  
  cmsl6: '',  
  cmsl7: '',  
  cmsl8: '',  
  cmsl9: '',  
  cmsl10: '',  
  zdtotal: '' 
});
// 实裁数
const scsformdata = reactive({
  scs1:'',
  scs2:'',
  scs3:'',
  scs4:'',
  scs5:'',
  scs6:'',
  scs7:'',
  scs8:'',
  scs9:'',
  scs10:'',
  sctotal:'',
});

//实裁相加
function updateTotal() {  
  // 直接指定要累加的属性名  
  const relevantKeys = ['scs1', 'scs2', 'scs3', 'scs4', 'scs5', 'scs6', 'scs7', 'scs8', 'scs9', 'scs10'];  
  const values = relevantKeys.map(key => parseInt(scsformdata[key], 10) || 0); 
  scsformdata.sctotal = values.reduce((sum, value) => sum + value, 0);  
}  

//进度汇总表格数据
const add_tableData = reactive([]);
const jdhz_tableData = reactive([]);
const bgjdhz_tableData = reactive([]);
const _order = ref('');
const _UniqId = ref('');
//尺寸列表
const sizeDatas = reactive([])
//技术附件
const jstableData = reactive([])
const ddtableData = reactive([])
const _list = ref('');

//查询
const add_onSubmit = async ()=>{
  if(add_searchInfo.value === '' || add_searchInfo.value === undefined){
	const WorkListdata = [];
	// add_tableData.splice(0,add_tableData.length,...WorkListdata);
	jdhz_tableData.splice(0,jdhz_tableData.length,...WorkListdata);
	ElMessage({type: 'warning',message: '搜索内容不能为空' })
	return;
  }
  // 如果没有以"DC"开头，自动补充添加DC 
  if (!add_searchInfo.value.startsWith('DC')) {
	add_searchInfo.value = 'DC' + add_searchInfo.value;  
  }
  
	  sizeDatas.length = 0;
	 _order.value = add_searchInfo.value;
	 //进度汇总表格数据
	 const getSpotLists = await getSpotList({order:_order.value,code:_code});
	 if(add_searchInfo.value === ''){
		 //光标跳转搜索框
		 _searchInput()
	 }else{
		 setTimeout(() => {
		 	  const inputElement = document.getElementById('scs1');
		 	  if (inputElement) {
		 		  inputElement.focus();		
		 	  }
		 }, 100);//100毫秒
	 }
	
	 sizeDatas.splice(0, getSpotLists.data.headers.length, ...getSpotLists.data.headers);
	 jdhz_tableData.splice(0, jdhz_tableData.length, ...getSpotLists.data.table);
	 bgjdhz_tableData.splice(0, bgjdhz_tableData.length, ...getSpotLists.data.bgtable);
	//xlsx附件
	const searchValue = add_searchInfo.value.split('-')[0];
	const jsOrderAttachments = await OrderAttachments({order:searchValue,desc:'技术附件'})
	const ddOrderAttachments = await OrderAttachments({order:searchValue,desc:'订单资料附件'})
	jstableData.splice(0,jsOrderAttachments.data.length,...jsOrderAttachments.data);
	ddtableData.splice(0,ddOrderAttachments.data.length,...ddOrderAttachments.data);
	_list.value = getSpotLists.data.list
	_UniqId.value = getSpotLists.data.list.UniqId
	
	const keys1 = ['cm1', 'cm2', 'cm3', 'cm4','cm5','cm6','cm7','cm8','cm9','cm10',];
	const keys2 = ['cmsl1', 'cmsl2', 'cmsl3', 'cmsl4','cmsl5','cmsl6','cmsl7','cmsl8','cmsl9','cmsl10','zdtotal',];
	if(_order.value.includes('-')){
		for (let key of keys1) {  
			if (getSpotLists.data.list.hasOwnProperty(key)) { // 确保键存在于对象中  
				cmformdata[key] = getSpotLists.data.list[key];  
			}  
		}  
    for (let key of keys2) {  
			if (getSpotLists.data.list.hasOwnProperty(key)) { // 确保键存在于对象中  
				cmslformdata[key] = getSpotLists.data.list[key];  
			}  
		} 
	}else{
		for (let key of keys1) {  
			cmformdata[key] = '';  
		}  
		for (let key of keys2) {  
			cmslformdata[key] = '';  
		}   
	}

};

  //总数量合计
  const getSummaries = (param) => {  
    const { columns, data } = param;  
    const sums = {};  
    const summableLabels = [...sizeDatas, "实裁总数"];
    columns.forEach((column, index) => {  
        if (index === 1) {  
            sums[index] = '总数量合计';  
            return;  
        }  
        if (summableLabels.includes(column.label)) {  
            const values = data.map(item => Number(item[column.property]));  
            // 检查数组中是否所有值都是 NaN  
            if (!values.every(value => isNaN(value))) {  
                sums[index] = values.reduce((prev, curr) => {  
                    const value = Number(curr);  
                    if (!isNaN(value)) {  
                        return prev + value; 
                    }  
                    return prev;  
                }, 0);  
                // 如果需要，可以在这里添加单位  
                // sums[index] += ' 件';  
            } else {  
                 sums[index] = '';  
            }  
        }  
    });  
    return sums;  
};  


//表格行点击
const tableRowClick = async (row)=>{
  add_searchInfo.value = row.子订单编号
	_order.value = row.子订单编号
}


//复选框选择
const ckSelection = ref('')
const handleSelectionChange = (selection, type) => {
  const ids = selection.map(item => {
    return item.子订单编号
  })
  ckSelection.value = ids.join(',')
  console.log(ckSelection.value)
}
const _searchInput = async ()=>{
	setTimeout(() => {
		const inputElement = document.getElementById('searchInput');
			if (inputElement) {
				inputElement.focus();		
			}
	}, 100);
}

//子订单详情页
const cp_gdprintonClick = async () => {
	if(add_searchInfo.value === '' || add_searchInfo.value === null){
		ElMessage({ type: 'warning', message: '请扫描子订单（条码）后再查看' });
		return false;
	}
	SubOrderPageRef.value.open(add_searchInfo.value,add_formData['工序']) 
}
	
	
//报工
const add_Dialog = async ()=>{
	if(add_formData['机台号'] === '测试机台'){
		ElMessage({ type: 'warning', message: '测试机台禁止报工' });
		return;
	}
	if (!add_formData['机台号']) {
	    ElMessage({ type: 'warning', message: '未获取到机台' });
	    return false;
	}
	if (!_order.value) {
	    ElMessage({ type: 'warning', message: '请扫描子订单（条码）后，在进行报工' });
	    return;
	}
	if (!add_searchInfo.value) {
	    ElMessage({ type: 'warning', message: '请扫描子订单（条码）后，在进行报工' });
	    return;
	}
	// 检查新增实裁数是否都为空
	const isAllEmpty = Array.from({ length: 10 }, (_, i) => scsformdata[`scs${i + 1}`]).every(value => !value);
	if (isAllEmpty) {
	    ElMessage({ type: 'warning', message: '请至少填写一个报工数据' });
	    return;
	}
	
	//尺码
	let cmArray = [cmformdata.cm1, cmformdata.cm2, cmformdata.cm3, cmformdata.cm4, cmformdata.cm5, cmformdata
		.cm6, cmformdata.cm7, cmformdata.cm8, cmformdata.cm9, cmformdata.cm10
	];
	//制单数
	let zdsl1Array = [cmslformdata.cmsl1, cmslformdata.cmsl2, cmslformdata.cmsl3, cmslformdata.cmsl4,
		cmslformdata.cmsl5, cmslformdata.cmsl6, cmslformdata.cmsl7, cmslformdata.cmsl8, cmslformdata
		.cmsl9, cmslformdata.cmsl10
	];
	//上报数量
	let scArray = [scsformdata.scs1, scsformdata.scs2, scsformdata.scs3, scsformdata.scs4, scsformdata.scs5, scsformdata.scs6, scsformdata.scs7, scsformdata.scs8, scsformdata.scs9, scsformdata.scs10
	];
	let resultArrays = [];
	for (let i = 0; i < scArray.length; i++) {
		// 创建一个新数组来存储当前索引下的所有值  
		let currentValues = [add_formData['机台号'], cmArray[i], zdsl1Array[i], scArray[i]];
		// 添加到结果数组中  
		resultArrays.push(currentValues);
	}
	let paramsList = []; 
	for (let i = 0; i < resultArrays.length; i++) {
		if (scArray[i]) {
			let params = {};
			params.order_id = add_searchInfo.value;
			params.sczl_jtbh = add_formData['机台号'];
			params.gxmc = add_formData['工序'];
			params.sys_id = add_formData['人员'];
			params.sczl_bh = add_formData['组别'];
			params.cm = resultArrays[i][1];
			params.sl = resultArrays[i][3];
			params.sys_rq = currentDates;
			params.code = _code;
			paramsList.push(params);
		}
	}
	if (paramsList.length === 0) {
		ElMessage({type: 'info',message: '请填写实裁数'});
		return;
	}
	let allSuccess = true;
	for (let i = 0; i < paramsList.length; i++) {
		const cf_gettab = await search(paramsList[i]);
		console.log('新增产量计酬返回信息',cf_gettab)
		if (cf_gettab.code !== 0) {
			allSuccess = false;
			break; 
		}
	}
	  
	//报工修改印件资料一条数据
	if (_order.value.indexOf('-') !== -1) {
	    let params = {}
		params.scsl1 = scsformdata.scs1
		params.scsl2 = scsformdata.scs2
		params.scsl3 = scsformdata.scs3
		params.scsl4 = scsformdata.scs4
		params.scsl5 = scsformdata.scs5
		params.scsl6 = scsformdata.scs6
		params.scsl7 = scsformdata.scs7
		params.scsl8 = scsformdata.scs8
		params.scsl9 = scsformdata.scs9
		params.scsl10 = scsformdata.scs10
		params.sctotal = scsformdata['sctotal']
		params.order_id = add_searchInfo.value;//子订单编号
		params.rq = currentDates;//时间
		params.UniqId = _UniqId.value
	    console.log(params)
	    const baogong_getInfo = await getInfo(params);
	   if (baogong_getInfo.code === 0) {
	           ElMessage({ type: 'success', message: '报工成功' });
			   //查询更新数据
			   add_onSubmit()
			   //光标跳转input
			   _searchInput()
			//     // 清空搜索信息
			//    add_searchInfo.value = '';
			   
			   // 批量清空新增实裁数input数据
	           if (scsformdata) {
	               for (let i = 1; i <= 10; i++) {
	                   scsformdata[`scs${i}`] = '';
	               }
	               scsformdata.sctotal = '';
	           } else {
	               console.error('scsformdata 未定义');
	           }
	       } else {
	           ElMessage({ type: 'error', message: '报工失败' });
	       }
	}
}

const gd_yulan = () => {
  if(add_searchInfo.value === '' || add_searchInfo.value === null){
    ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能'})
    return false;
  }else{
    const order = add_searchInfo.value.split('-')[0]
      printPageRef.value.open(order) 
  }
}
//报工删除
const delall = ref(true)
const Selection = ref('')
const selectionChange = (selection, type) => {
	const ids = selection.map(item => {
		return item.UniqId
	})
	Selection.value = ids.join(',')
	console.log(Selection.value)
}
const del_delclick = async () => {
	console.log(Selection.value)
	console.log(add_formData['组别'])
	const res1 = await spotcheckdel({UniqId:Selection.value,sys_id:add_formData['组别']})
	res1.code === 0 && ElMessage.success('删除成功')
	add_onSubmit()
}

const _orderid = ref('')//订单子编号
const _kh = ref('')//生产款号

//===========报工==========
const res_bomdialogFormVisible = ref(false)
const resbomtableData = ref([]);
const ddhformData = reactive({
  ddh: '',
  kh:''
});
const resbom_tableColumns = ref(
    [
      { label: '物料名称', prop: '物料名称', width: '200' },
      { label: '计划用料', prop: '计划用料', width: '110' },
	  { label: '定额用料', prop: '定额用料', width: '90' },
	  { label: '裁床实际用料', prop: '裁床实际用料', width: '120' },
	  { label: '裁床领用面料', prop: '裁床领用面料', width: '120' },
	  { label: '裁床退回仓库面料', prop: '裁床退回仓库面料', width: '160' },
	  { label: '退还', prop: '退还', width: '110' },
	  // { label: '备注', prop: '备注', width: '120' },
	  { label: '投料单位', prop: '投料单位', width: '100' },
	  // { label: 'UNIQID', prop: 'UNIQID', width: '80' },
    ]
)
//退还按钮
const return_Dialog = async ()=>{
	_orderid.value = add_searchInfo.value.split('-')[0]
	if(_orderid.value === '' || _orderid.value === null){
		ElMessage({type: 'warning',message: '请扫描订单后，再操作此功能'})
	}else{
		const orderSearchdata = await orderSearch({search:_orderid.value});
		console.log(orderSearchdata)
		_kh.value = orderSearchdata.data[0].生产款号
		res_bomdialogFormVisible.value = true
		ddhformData.ddh = _orderid.value
		ddhformData.kh = _kh.value
		const orderBomListlsit = await orderBomList({order:_orderid.value});
		console.log(orderBomListlsit)
		_TestCoefficient();
	}
}
//bom数据获取
const _TestCoefficient = async ()=>{
  try {
    const orderBomListdata = await orderBomList({order:_orderid.value});
	console.log(orderBomListdata)
	resbomtableData.value = orderBomListdata.data;
    const formattedData = orderBomListdata.data.map(item=>{
      item.物料名称 = item.物料名称;
      item.计划用料 = item.计划用料;
	  item.定额用料 = item.定额用料;
	  item.裁床实际用料 = item.裁床实际用料;
	  item.裁床领用面料 = item.裁床领用面料;
	  item.裁床退回仓库面料 = item.裁床退回仓库面料;
	  item.备注 = item.备注;
	  item.UNIQID = item.UNIQID;
	  item.领用 = '';
      return item
    });
  } catch (error) {
    console.error(error);
  }
}
const resbom_handleKeyDown = (event, x, y, prop) => {
  const currentElement = document.getElementById(`input${x}${y}`);
  if (currentElement === null && currentElement === undefined) return
  let move = 0
  switch (event.keyCode) {
    case 13: // Enter
    case 40: // 向下箭头
      if (y < resbomtableData.value.length )
        document.getElementById(`input${x}${y + 1}`).focus();
      break;
    case 38: // 向上箭头
      if ( y > 0) {
        document.getElementById(`input${x}${y - 1}`).focus();
      }
      break;
    case 39: // 向左箭头
      if (x >= 0 && x <=6) {
        move = x + 1
      }
      document.getElementById(`input${move}${y}`).focus();
      break;
    case 37: // 向右箭头
      if (x = 0  && x <=6) {
        move = x - 1
      }
      document.getElementById(`input${move}${y}`).focus();
      break;
    default:
      break;
  }
}
//质检废品系数颜色
const scfjfpxsCellClass = ({row, column, rowIndex, columnIndex}) =>{
  if (column.label === '退还') {
    return 'background-plan-usage-low';
  }
}

// 确定
const res_bomenterDialog = async() => {
	const rawValueArray = resbomtableData._rawValue;
	const formattedData = rawValueArray.map(item => {
	  return {
	    order_id: ddhformData.ddh,
	    款号: ddhformData.kh,
	    物料名称: item.物料名称 !== null ? item.物料名称 : "",
	    number: item.退还 !== null ? item.退还 : "",
	    rq: currentDate,
	    name: "退还",
		sys_id: _username.value
	  }
	});
	console.log(formattedData);
	const add_outReport = await outReport(formattedData);
	if (add_outReport.code === 0) {
		res_bomdialogFormVisible.value = false;
		ElMessage({type: 'success',message: '退还成功'})
	} else {
		ElMessage({ type: 'error',message: '退还失败'})
	}
}

// 取消
const res_bomcloseDialog = () => {
	res_bomdialogFormVisible.value = false;
}

// =========== 分页 ===========
// 分页相关的响应式变量
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
// 分页
const handleCurrentChange = (val) => {
  page.value = val;
  _getStaffList();
};

// 修改页面容量 点击多少条/页
const handleSizeChange = (val) => {
  page.value = 10;//默认显示
  pageSize.value = val;
  _getStaffList();
};
</script>

<style scoped>
.form-container {
  display: flex;
  flex-wrap: wrap;
}

.form-column {
  /*flex: 1;*/
  margin-right: 15px; /* 调整列之间的间距 */
}

/* 左侧输入框宽度调整 */
.form-column .el-form-item .el-input {
  width: 150px; /* 调整左侧输入框的宽度 */
}

/* 媒体查询，根据需要调整断点 */
@media screen and (max-width: 768px) {
  .form-column {
    flex: 1 0 100%; /* 在小屏幕下变成单列布局 */
    margin-right: 0;
  }
}
/*:deep(.el-table td .cell) {*/
/*  line-height: 30px !important;*/
/*}*/
.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;
}
/* 图片上传 */
.upload-box {
  width: 200px;
  height: 200px;
  border: 2px dashed #e2e2e2;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  cursor: pointer;
}
.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.upload-icon {
  font-size: 40px;
  color: #c0c4cc;
}
.file-input {
  display: none;
}
.el-table .warning-row {
  background: oldlace;
}

/*bom参数背景*/
:deep(.el-table__body .background-plan-usage-low div div div) {
  background: #80FA80 !important;
}
/* 选中某行时的背景色 */
:deep(.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;
	margin-left: -10px !important;
}
.mab{
  margin-bottom: 5px;
}

/* 搜索样式 */
::v-deep .el-input__wrapper #searchInput {  
  font-size: 16px; 
} 
::v-deep .el-input__wrapper #jitaihao {  
  font-size: 18px; 
}  
::v-deep .el-input__wrapper #gongxu {  
  font-size: 18px; 
}  
::v-deep .el-input__wrapper #zubie {  
  font-size: 18px; 
}  
::v-deep .el-input__wrapper #renyuan {  
  font-size: 18px; 
} 
::v-deep .el-input__wrapper #shuliang {  
  font-size: 18px; 
  color: red;
} 
::v-deep .el-input__wrapper #chima {  
  font-size: 18px; 
} 

/* 尺码/制单数合计样式 */
::v-deep .el-input__wrapper  #cm1{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm2{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm3{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm4{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm5{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm6{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm7{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm8{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm9{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm10{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm11{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cm12{
	font-size: 20px; 
}
::v-deep .el-input__wrapper  #cmtotal{
	font-size: 20px; 
}
/* 本次实裁新增样式 */
::v-deep .el-input__wrapper  #cmsl1{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl2{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl3{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl4{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl5{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl6{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl7{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl8{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl9{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl10{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl11{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #cmsl12{
	font-size: 20px; 
	color: red !important;
}
::v-deep .el-input__wrapper  #zdtotal{
	font-size: 20px; 
  color: red !important;
}
/* 表格复选框大小调整 */
:deep(.el-checkbox.el-checkbox--small .el-checkbox__inner) {
	width: 30px;
	/* 复选框宽度 */
	height: 20px;
	/* 复选框高度 */
}
:deep(.el-checkbox.el-checkbox--small.is-checked .el-checkbox__inner::after) {
	transform: scale(1.2) rotate(45deg);
	/* 调整选中后的对勾大小 */
	top: 5%;
	/* 调整对勾位置 */
	left: 40%;
	/* 调整对勾位置 */
	width: 5px;
	/* 调整对勾宽度 */
	height: 9px;
	/* 调整对勾高度 */
}

</style>
