<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: 30px;margin-left: 90px;">尺 码</el-text></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm1" id="cm1" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm2" id="cm2" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm3" id="cm3" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm4" id="cm4" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm5" id="cm5" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm6" id="cm6" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm7" id="cm7" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm8" id="cm8" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm9" id="cm9" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmformdata.cm10" id="cm10" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1"><el-input v-model="cmformdata.cm11" id="cm11" readonly style="width: 65px;height: 40px;" /></el-col>
					</el-row>
					

					<el-row :gutter="0">
						<el-col :span="2.5"><el-text style="font-size: 30px;margin-left: 70px;">制单数</el-text></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl1" id="zdsc1" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl2" id="zdsc2" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl3" id="zdsc3" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl4" id="zdsc4" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl5" id="zdsc5" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl6" id="zdsc6" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl7" id="zdsc7" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl8" id="zdsc8" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl9" id="zdsc9" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="cmslformdata.cmsl10" id="zdsc10" readonly style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1"><el-input v-model="cmslformdata.zdtotal" id="zdtotal" readonly style="width: 65px;height: 40px;" /></el-col>
					</el-row>
					
					<el-row :gutter="0">
						<el-col :span="2.5"><el-text style="font-size: 30px;margin-left: 10px;">新增实裁数</el-text></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs1" @input="updateTotal" id="scs1"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs2" @input="updateTotal" id="scs2"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs3" @input="updateTotal" id="scs3"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs4" @input="updateTotal" id="scs4"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs5" @input="updateTotal" id="scs5"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs6" @input="updateTotal" id="scs6"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs7" @input="updateTotal" id="scs7"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs8" @input="updateTotal" id="scs8"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs9" @input="updateTotal" id="scs9"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1" style="padding-right: 5px;margin-right: 11px;"><el-input v-model="scsformdata.scs10" @input="updateTotal" id="scs10"  style="width: 65px;height: 40px;" /></el-col>
						<el-col :span="1"><el-input v-model="scsformdata.sctotal" id="sctotal" readonly style="width: 65px;height: 40px;" /></el-col>
						
						<el-button type="primary" @click="add_Dialog"
							style="width: 100px;height: 60px;font-size: 20px;margin: 0px 0 0 20px">报工</el-button>
						<el-button type="primary" @click="gd_yulan"
							style="width: 100px;height: 60px;font-size: 20px;margin: 0px 0 0 15px">工单预览</el-button>
					</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="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 type="selection" width="55" /> -->
									  <!-- <el-table-column  sortable  align="center" label="订单编号" prop="订单编号" width="120"/> -->
									  <el-table-column   align="left" label="订单子编号" prop="子订单编号"  width="130"/>
									  <!-- <el-table-column  sortable  align="left" label="客户编号" prop="客户编号" width="120"/> -->
									  <el-table-column    align="left" label="款号" prop="款号" width="140" />
									  <!-- <el-table-column  sortable  align="left" label="款式" prop="款式" width="100" /> -->
									  <el-table-column    align="left" label="色系名称" prop="颜色" width="100" />
									  <!-- <el-table-column  sortable  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  sortable  align="left" label="制单总数" prop="制单数" width="108" /> -->
									  <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>
						</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="handleSelectionChange">
						  <!-- <el-table-column type="selection" width="55" /> -->
					      <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>
					    </el-tab-pane>
					</el-tabs>
				</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="luckyexcelVisible" :before-close="luckyexcelCloseDialog" width="100%" top="0vh">
					<div id="luckyexcel" style="width: 100%;height: 100vh;"></div>
				</el-dialog>
				
        </layout-content>
      </layout>

    <PrintPage ref="printPageRef" />
		  <!-- </el-main> -->
	</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} 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 { useUserStore } from '@/pinia/modules/user';
defineOptions({name: 'Company'})
//获取登录用户信息
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 printPageRef = ref()
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地址或与管理员联系'
		})
		return;
	}
	// console.log(data)
	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()



//技术附件


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:'合计',
});

// 制单数
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); // 使用 || 0 来处理可能的 NaN 或 undefined/null  
  scsformdata.sctotal = values.reduce((sum, value) => sum + value, 0);  
}  

//进度汇总表格数据
const add_tableData = reactive([]);
const jdhz_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(getSpotLists.data.total === 0){
	   ElMessage({type: 'warning',message: '此订单未出库，请先出库' })
	   return false
	 }
	 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);
	
	//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] = '';  
		}   
	}

  
  // getSummaries();
};


//合计
  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;  
};  

//订单资料excel展示
const gdbomupdateCompanyFunc = (row) =>{
	// 加载插件和样式
	const loadScriptsAndStyles = () => {
	    $.getScript('/luckysheet/plugins/js/plugin.js', () => {
	        $script('/luckysheet/luckysheet.umd.js', () => {
	            initializeLuckysheet();
	        });
	    });
	
	    const styles = [
	        '/luckysheet/plugins/css/pluginsCss.css',
	        '/luckysheet/plugins/plugins.css',
	        '/luckysheet/css/luckysheet.css',
	        '/luckysheet/assets/iconfont/iconfont.css'
	    ];
	
	    styles.forEach(style => {
	        $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', style));
	    });
	};
	
	// 初始化 Luckysheet
	const initializeLuckysheet = () => {
	    const callback = (exportJson, luckysheetfile) => {
	        if (!exportJson.sheets || exportJson.sheets.length === 0) {
	            alert("Failed to read the content of the excel file, currently does not support xls files!");
	            return;
	        }
	        if (luckyExcel) luckyExcel.destroy();
	        luckysheet.create({
	            container: 'luckyexcel',
	            data: exportJson.sheets,
	            title: exportJson.info.name,
	            lang: "zh",
	            showtoolbar: false,
	            showinfobar: false,
	            allowEdit: false,
	            enableAddRow: false,
	            enableAddCol: false,
	            userInfo: false,
	            showRowBar: false,
	            showColumnBar: false,
	            sheetFormulaBar: false,
	            enableAddBackTop: false,
	        });
	        luckyExcel = luckysheet;
	    };
	
	    if (row['url'] === null || row['url'] === '') {
	        const blob = dataURLtoBlob(row.附件内容);
	        luckyexcelVisible.value = true;
	        LuckyExcel.transformExcelToLucky(blob, callback);
	    } else {
	        const excelPath = `/${row.url.replace(/\\/g, "/")}`;
	        const excelName = excelPath.split('/').pop();
	        luckyexcelVisible.value = true;
	        LuckyExcel.transformExcelToLuckyByUrl(excelPath, excelName, callback);
	    }
	};
	
	// Data URL 转 Blob
	const dataURLtoBlob = (dataUrl) => {
	    const byteString = atob(dataUrl.split(',')[1]);
	    const ab = new ArrayBuffer(byteString.length);
	    const ia = new Uint8Array(ab);
	
	    for (let i = 0; i < byteString.length; i++) {
	        ia[i] = byteString.charCodeAt(i);
	    }
	
	    return new Blob([ab], { type: 'application/octet-stream' });
	};
	
	loadScriptsAndStyles();
}
//技术资料excel展示
const ExcelShow = (row) =>{
	// 加载插件和样式
	const loadScriptsAndStyles = () => {
	    $.getScript('/luckysheet/plugins/js/plugin.js', () => {
	        $script('/luckysheet/luckysheet.umd.js', () => {
	            initializeLuckysheet();
	        });
	    });
	
	    const styles = [
	        '/luckysheet/plugins/css/pluginsCss.css',
	        '/luckysheet/plugins/plugins.css',
	        '/luckysheet/css/luckysheet.css',
	        '/luckysheet/assets/iconfont/iconfont.css'
	    ];
	
	    styles.forEach(style => {
	        $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', style));
	    });
	};
	
	// 初始化 Luckysheet
	const initializeLuckysheet = () => {
	    const callback = (exportJson, luckysheetfile) => {
	        if (!exportJson.sheets || exportJson.sheets.length === 0) {
	            alert("Failed to read the content of the excel file, currently does not support xls files!");
	            return;
	        }
	        if (luckyExcel) luckyExcel.destroy();
	        luckysheet.create({
	            container: 'luckyexcel',
	            data: exportJson.sheets,
	            title: exportJson.info.name,
	            lang: "zh",
	            showtoolbar: false,
	            showinfobar: false,
	            allowEdit: false,
	            enableAddRow: false,
	            enableAddCol: false,
	            userInfo: false,
	            showRowBar: false,
	            showColumnBar: false,
	            sheetFormulaBar: false,
	            enableAddBackTop: false,
	        });
	        luckyExcel = luckysheet;
	    };
	
	    if (row['url'] === null || row['url'] === '') {
	        const blob = dataURLtoBlob(row.附件内容);
	        luckyexcelVisible.value = true;
	        LuckyExcel.transformExcelToLucky(blob, callback);
	    } else {
	        const excelPath = `/${row.url.replace(/\\/g, "/")}`;
	        const excelName = excelPath.split('/').pop();
	        luckyexcelVisible.value = true;
	        LuckyExcel.transformExcelToLuckyByUrl(excelPath, excelName, callback);
	    }
	};
	
	// Data URL 转 Blob
	const dataURLtoBlob = (dataUrl) => {
	    const byteString = atob(dataUrl.split(',')[1]);
	    const ab = new ArrayBuffer(byteString.length);
	    const ia = new Uint8Array(ab);
	
	    for (let i = 0; i < byteString.length; i++) {
	        ia[i] = byteString.charCodeAt(i);
	    }
	
	    return new Blob([ab], { type: 'application/octet-stream' });
	};
	
	loadScriptsAndStyles();
}
let luckyExcel = null

const luckyexcelVisible = ref(false)
const luckyexcelCloseDialog = () => {
  luckyexcelVisible.value = false
}


//表格行点击
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 add_Dialog = async ()=>{
	if (!add_formData['机台号']) {
	    ElMessage({ type: 'warning', message: '未获取到机台' });
	    return false;
	}
	if (!_order.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) {
			// ElMessage({ type: 'error', message: '报工失败' });  
			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 = _order.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 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;
}

/* 选中某行时的背景色 */
: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  #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  #zdtotal{
	font-size: 20px; 
  color: red !important;
}


</style>
