<template>
  <div>
    <layout>
      <layout-header>
        <div class="">
          <!--按钮部分-->
          <el-form ref="elSearchFormRef"  class="demo-form-inline"  >
            <el-form-item>
              <el-input v-model="searchInfo"  placeholder="搜索订单编号" style="width: 180px;" @keyup.enter="onSubmit()"></el-input>
              <el-button type="primary" icon="search" @click="onSubmit" title="搜索"  ></el-button>
              <el-button type="primary" class="bt" icon="edit"  @click="jsfjClick">附件上传</el-button>
              <el-button type="primary" icon="edit"   @click="addgd_onclick"   class="bt"   title="新增工单资料">新增订单资料</el-button>
              <el-button type="primary" icon="edit"   @click="addgdyj_onclick"   class="bt" title="新增颜色资料">新增颜色资料</el-button>
              <el-button type="primary" icon="edit"   @click="addgdgy_onclick"   class="bt" title="新增工序资料" >新增工序资料</el-button>
              <el-button type="primary" icon="edit"   @click="cp_gdprintonClick" class="bt" title="打印生产订单" >订单打印</el-button>
              <el-button type="primary" icon="edit"   @click="del_ddzlClick" v-if="table_del=== true" :disabled="table_Selection === ''"  class="bt" title="删除订单资料"  >删除订单资料</el-button>
              <el-button type="primary" icon="edit"   @click="delgd_delclick" v-if="delall=== true" :disabled="ysSelection === '' && gySelection === ''"  class="bt" title="选择批量删除（颜色资料或工艺资料）"  >删除颜色工艺资料</el-button>
            </el-form-item>
          </el-form>
        </div> 
      </layout-header>
      <layout>

        <!-- 左侧树形结构 -->
        <layout-sider :resize-directions="['right']" :width="190" style="margin-right: 10px;">
          <div class="JKWTree-tree" style="height: 200px">
            <h3>客户编号</h3>
            <el-tree :data="treeData" class="treecolor" @node-click="handleNodeClick"></el-tree>
          </div>
        </layout-sider>

        <!-- 右侧内容区域 -->
        <layout-content >
          <el-main>
            <!-- 工单表格列表 -->
            <div class="gva-table-box">
              <el-table ref="multipleTable"
                        style="width: 100%;height: 28vh"
                        :row-style="{ height: '20px' }"
                        :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                        :header-cell-style="{ padding: '0px' }"
                        border
                        tooltip-effect="dark"
                        :data="tableData" row-key="ID"
                        @row-click="tableRowClick"
                        highlight-current-row="true"
                        :cell-class-name="tableDataCellClass"
                        @row-dblclick="updateCompanyFunc"
                        @selection-change="handleSelectionChange"
                        :show-overflow-tooltip="true">
                <el-table-column align="center" type="selection" width="30"/>
                <el-table-column align="left" sortable label="订单编号"     	prop="订单编号" 	width="110" />
				<el-table-column align="left" sortable label="客户"      	prop="客户编号" 		width="80" />
                <el-table-column align="left" sortable label="生产款号"   	prop="生产款号"  width="110" />
                <el-table-column align="left" sortable label="款式"       	prop="款式"   	width="100"/>
				<el-table-column align="left" sortable label="订单数量"    	prop="订单数量" 	width="105" />
				<el-table-column align="left" sortable label="单位"    		prop="单位" 		width="80" />
				<el-table-column align="left" sortable label="落货日期"   	prop="落货日期" 	width="120" />
				<el-table-column align="left" sortable label="船样合计"    	prop="船样合计" 	width="105" />
				<el-table-column align="left" sortable label="船样描述"    	prop="船样描述" 	width="140" />
                <el-table-column align="left" sortable label="面料"       	prop="面料" 		width="130" />
                <el-table-column align="left" sortable label="要求"       	prop="要求" 		width="130" />
                <el-table-column align="left" sortable label="粘衬"        	prop="粘衬"		width="80" />
				<el-table-column align="left" sortable label="箱唛要求"   	prop="箱唛要求" 	width="110" />
                <el-table-column align="left" sortable label="审核"    		prop="审核" 		width="80" />
                <el-table-column align="left" sortable label="审核日期"    	prop="审核日期" 	width="110" />
              </el-table>
              <!-- 分页 -->
              <div class="gva-pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[10, 30, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
              </div>
            </div>

            <!-- 颜色资料列表、工艺资料列表、BOM资料列表  -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="颜色资料"  @click="showTable('颜色资料')"  name="first">
                <el-table ref="multipleTable"
                          :row-style="{ height: '20px' }"
                          :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                          :header-cell-style="{ padding: '0px' }"
                          :show-overflow-tooltip="true"
                          highlight-current-row="true"
                          @row-dblclick="ysupdateCompanyFunc"
                          @selection-change="selectionChange($event, '颜色资料')"
                          style="width: 100%;height: 36vh" border show-summary
                          :summary-method="getSummaries" tooltip-effect="dark" :data="ystableData" row-key="ID" >
                  <el-table-column type="selection" width="55" />
                  <!-- <el-table-column align="left" sortable label="序号" prop="序号"  width="100"/> -->
                  <el-table-column align="left" sortable label="订单子编号" prop="子订单编号"  width="180"/>
                  <el-table-column align="left" sortable label="色系名称" prop="颜色"  width="110"/>
                  <el-table-column align="left" sortable label="船样" prop="船样"  width="80"/>
                  <template v-for="item in sizeDatas">
                    <el-table-column align="left" sortable :label=item :prop=item  width="80"/> 
                  </template>
                  <el-table-column align="left" sortable label="制单总数" prop="zdtotal"  width="110"/>
                  <el-table-column align="left" sortable label="建档用户" prop="Sys_id"  width="110"/>
                  <el-table-column align="left" sortable label="建档时间" prop="Sys_rq"  width="110"/>
                  <el-table-column align="left" sortable label="更新时间" prop="更新时间"  width="110"/>
                </el-table>
              </el-tab-pane>

              <el-tab-pane label="工艺资料" @click="showTable('工艺资料')" name="second">
                <el-table ref="multipleTable"
                          :row-style="{ height: '20px' }"
                          :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                          :header-cell-style="{ padding: '0px' }"
                          highlight-current-row="true"
                          :show-overflow-tooltip="true"
                          size="small"
                          :cell-class-name="gysatusCellClass"
                          @row-dblclick="gdgyupdateCompanyFunc"
                          @row-click="clickybupdate2"
                          :row-class-name="rowClassStyle2"
                          @selection-change="selectionChange($event, '工艺资料')"
                          style="width: 100%;height: 36vh" border tooltip-effect="dark" :data="gytableData" row-key="ID">
                  <el-table-column type="selection" width="30" />
                  <el-table-column align="left" label="完工状态" prop="完工状态"  width="75"/>
                  <el-table-column align="left" label="工序名称" prop="工序名称"  width="280"/>
                  <el-table-column align="left" label="计划产量" prop="计划产量"  width="80"/>
                  <el-table-column align="left" label="建档用户" prop="建档用户"  width="90"/>
                  <el-table-column align="left" label="建档日期" prop="建档日期"  width="150"/>
                  <el-table-column align="left" label="更新时间" prop="更新时间"  width="150"/>
                </el-table>
              </el-tab-pane>

              <el-tab-pane label="订单资料附件" @click="showTable('订单资料附件')" name="third">
                <el-table ref="multipleTable"
                          :row-style="{ height: '20px' }"
                          :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                          :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="handleSelectionChange">
                  <!-- <el-table-column type="selection" width="30" /> -->
                  <!-- <el-table-column align="left" label="序号" prop="序号"  width="70"/> -->
                  <el-table-column align="left" label="备注" prop="附件备注"  width="110"/>
                  <el-table-column align="left" label="文件类型" prop="附件类型"  width="90"/>
                  <el-table-column align="left" label="关联产品" prop="关联编号"  width="105"/>
                  <el-table-column align="left" label="建档用户" prop="sys_id"  width="90"/>
                  <el-table-column align="left" label="建档时间" prop="sys_rq"  width="115"/>
                  <el-table-column align="left" label="更新时间" prop="mod_rq"  width="115"/>
                  <!-- <el-table-column align="left" label="操作" prop="操作"  width="70" /> -->
                </el-table>
              </el-tab-pane> 

			  <el-tab-pane label="技术附件" @click="showTable('技术附件')" name="fourth">
			  	<el-table ref="multipleTable"
					  :row-style="{ height: '20px' }"
					  :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
					  :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="70"/> -->
                  <el-table-column align="left" label="备注" prop="附件备注"  width="85"/>
                  <el-table-column align="left" label="文件类型" prop="附件类型"  width="90"/>
                  <el-table-column align="left" label="关联产品" prop="关联编号"  width="105"/>
                  <el-table-column align="left" label="建档用户" prop="sys_id"  width="90"/>
                  <el-table-column align="left" label="建档时间" prop="sys_rq"  width="115"/>
                  <el-table-column align="left" label="更新时间" prop="mod_rq"  width="115"/>
			      </el-table>
			    </el-tab-pane>
            </el-tabs>

          <!-- 双击订单资料修改弹窗 -->
		  <el-dialog
		      v-model="ddzl_dialogFormVisible" 
		      :before-close="dd_closeDialog"  
		      title="修改订单资料" 
		      width="60%" top="4%"
		      destroy-on-close>
            <el-row :gutter="24" class="form-row" type="flex">
              <el-col :span="10">
                <el-form-item label="订单编号" class="mab" label-width="110px">
                  <el-input v-model="edit_ddformData['订单编号']" disabled style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="客户编号" class="mab" label-width="150px">
                  <el-input v-model="edit_ddformData['客户编号']" disabled style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="生产款号" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['生产款号']" style="width: 100%;" id="生产款号" @keydown="add_gdzlent($event, '订单编号', '生产款号', '款式')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="款式" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['款式']" style="width: 100%;" id="款式" @keydown="add_gdzlent($event, '生产款号', '款式', '客户编号')" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="落货日期" prop="deliveryDate" class="mab" label-width="150">
                  <el-date-picker v-model="edit_ddformData['落货日期']" type="date" style="width: 100%;" id="落货日期" @keydown="add_gdzlent($event, '客户编号', '落货日期', '面料')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row class="form-row">
              <el-col :span="20">
                <el-form-item label="面料" prop="customerCode" class="mab" label-width="110">
                  <el-input type="textarea" v-model="edit_ddformData['面料']" rows="2" resize="none" id="面料" @keydown="add_gdzlent($event, '落货日期', '面料', '要求')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row class="form-row">
              <el-col :span="20">
                <el-form-item label="要求" prop="customerCode" class="mab" label-width="110">
                  <el-input type="textarea" v-model="edit_ddformData['要求']" rows="2" resize="none" id="要求" @keydown="add_gdzlent($event, '面料', '要求', '船样描述')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="船样描述" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['船样描述']" style="width: 100%;" id="船样描述" @keydown="add_gdzlent($event, '要求', '船样描述', '船样合计')" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="船样合计" prop="customerCode" class="mab" label-width="150">
                  <el-input v-model="edit_ddformData['船样合计']" style="width: 100%;" id="船样合计" @keydown="add_gdzlent($event, '船样描述', '船样合计', '箱唛要求')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="箱唛要求" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['箱唛要求']" style="width: 100%;" id="箱唛要求" @keydown="add_gdzlent($event, '船样合计', '箱唛要求', '粘衬')" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="粘衬" prop="customerCode" class="mab" label-width="150">
                  <el-input v-model="edit_ddformData['粘衬']" style="width: 100%;" id="粘衬" @keydown="add_gdzlent($event, '箱唛要求', '粘衬', '订单数量')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="订单数量" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['订单数量']" style="width: 100%;" id="订单数量" @keydown="add_gdzlent($event, '粘衬', '订单数量', '单位')" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="单位" prop="customerCode" class="mab" label-width="150">
                  <el-input v-model="edit_ddformData['单位']" style="width: 100%;" id="单位" @keydown="add_gdzlent($event, '订单数量', '单位', '制单人')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <el-row :gutter="24" class="form-row">
              <el-col :span="10">
                <el-form-item label="制单人" prop="customerCode" class="mab" label-width="110">
                  <el-input v-model="edit_ddformData['Sys_id']" disabled style="width: 100%;" id="制单人" @keydown="add_gdzlent($event, '单位', '制单人', '制单日期')" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="制单日期" prop="deliveryDate" class="mab" label-width="150">
                  <el-date-picker v-model="edit_ddformData['接单日期']" disabled type="date" style="width: 100%;" id="制单日期" @keydown="add_gdzlent($event, '制单人', '制单日期', '审核人')" />
                </el-form-item>
              </el-col>
            </el-row>
          
            <template #footer>
              <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
                <el-button @click="dd_closeDialog">取 消</el-button>
                <el-button type="primary" @click="dd_edit_Dialog">确 定</el-button>
              </div>
            </template>
          </el-dialog>


         <!-- 双击颜色资料修改弹窗 -->
         <el-dialog v-model="dialogFormVisible" :before-close="edit_closeDialog" title="颜色资料修改" destroy-on-close style="width: 85%; max-height: 80vh; overflow-y: auto;">
             <el-row :gutter="24" class="form-row">
                 <el-col :span="10">
                     <div style="display: flex; gap: 0px;">
                         <h3 style="color:red;font-size: 24px;margin:-5px 0px 8px 12px;">订单号&nbsp;&nbsp;&nbsp;{{_ddhval}}</h3>
                     </div>
                 </el-col>
                 <el-col :span="10">
                     <div style="display: flex; gap: 0px;">
                         <el-form-item label="订单子编号:" class="mab" prop="keyOrder" label-width='110'>
                             <el-input v-model="edit_formData['子订单编号']" disabled style="width: 250px;" id="订单子编号" />
                         </el-form-item>
                     </div>
                 </el-col>
             </el-row>
         
             <el-row :gutter="24">
                 <el-col :span="10">
                     <div style="display: flex; gap: 0px;">
                         <el-form-item label="色系名称:" class="mab" prop="keyOrder" label-width='110'>
                             <el-select v-model="edit_formData['颜色']" style="width: 150px;" id="尺码规格" @keydown="add_gdzlent($event, '款号', '尺码规格', '是否船样')">
                                 <el-option label="红色系" @click="sxhandleSizeChange('红色系')"></el-option>
                                 <el-option label="黄色系" @click="sxhandleSizeChange('黄色系')"></el-option>
                                 <el-option label="蓝色系" @click="sxhandleSizeChange('蓝色系')"></el-option>
                                 <el-option label="绿色系" @click="sxhandleSizeChange('绿色系')"></el-option>
                                 <el-option label="紫色系" @click="sxhandleSizeChange('紫色系')"></el-option>
                                 <el-option label="灰色系" @click="sxhandleSizeChange('灰色系')"></el-option>
                                 <el-option label="咖啡色系" @click="sxhandleSizeChange('咖啡色系')"></el-option>
                                 <el-option label="黑白色系" @click="sxhandleSizeChange('黑白色系')"></el-option>
                                 <el-option label="经典色系" @click="sxhandleSizeChange('经典色系')"></el-option>
                             </el-select>
                         </el-form-item>
                     </div>
                 </el-col>
         
                 <el-col :span="10">
                     <el-form-item label="生产款号:" prop="deliveryDate" class="mab" label-width="110px" style="">
                         <el-input v-model="edit_formData['款号']" style="width: 250px;" id="生产款号" />
                     </el-form-item>
                 </el-col>
             </el-row>
         
             <el-row :gutter="24">
                 <el-col :span="10">
                     <div style="display: flex; gap: 0px;">
                         <el-form-item label="是否船样:" prop="joinDate" label-width='110'>
                             <el-select v-model="edit_formData['船样']" style="width: 150px;" id="是否船样" @keydown="add_gdzlent($event, '尺码规格', '是否船样', 'zds1')">
                                 <el-option label="是" value="是"></el-option>
                                 <el-option label="否" value="否"></el-option>
                             </el-select>
                         </el-form-item>
                     </div>
                 </el-col>
             </el-row>
         
             <el-row class="form-row">
                 <el-col :span="20">
                     <div style="display: flex; gap: 0px;">
                         <el-form-item label="尺码:" class="mab" prop="keyOrder" label-width='110'>
                             <el-input v-model="edit_cmformdata.cm1" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm2" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm3" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm4" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm5" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm6" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm7" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm8" readonly style="width: 80px;" />
                             <el-input v-model="edit_cmformdata.cm9" readonly style="width: 80px;" />
                         </el-form-item>
                     </div>
                 </el-col>
             </el-row>
         
             <el-row class="form-row">
                 <el-col :span="20">
                     <div style="display: flex; gap: 0px;">
                         <el-form-item label="制单数:" class="mab" prop="keyOrder" label-width='110'>
                             <el-input v-model="edit_zdsformdata.zds1" @input="updateTotal" style="width: 80px;" id="zds1" @keydown="add_gdzlent($event, '是否船样', 'zds1', 'zds2')" />
                             <el-input v-model="edit_zdsformdata.zds2" @input="updateTotal" style="width: 80px;" id="zds2" @keydown="add_gdzlent($event, 'zds1', 'zds2', 'zds3')" />
                             <el-input v-model="edit_zdsformdata.zds3" @input="updateTotal" style="width: 80px;" id="zds3" @keydown="add_gdzlent($event, 'zds2', 'zds3', 'zds4')" />
                             <el-input v-model="edit_zdsformdata.zds4" @input="updateTotal" style="width: 80px;" id="zds4" @keydown="add_gdzlent($event, 'zds3', 'zds4', 'zds5')" />
                             <el-input v-model="edit_zdsformdata.zds5" @input="updateTotal" style="width: 80px;" id="zds5" @keydown="add_gdzlent($event, 'zds4', 'zds5', 'zds6')" />
                             <el-input v-model="edit_zdsformdata.zds6" @input="updateTotal" style="width: 80px;" id="zds6" @keydown="add_gdzlent($event, 'zds5', 'zds6', 'zds7')" />
                             <el-input v-model="edit_zdsformdata.zds7" @input="updateTotal" style="width: 80px;" id="zds7" @keydown="add_gdzlent($event, 'zds6', 'zds7', 'zds8')" />
                             <el-input v-model="edit_zdsformdata.zds8" @input="updateTotal" style="width: 80px;" id="zds8" @keydown="add_gdzlent($event, 'zds7', 'zds8', 'zds9')" />
                             <el-input v-model="edit_zdsformdata.zds9" readonly style="width: 80px;" id="zds9" @keydown="add_gdzlent($event, 'zds8', 'zds9', '订单子编号')" />
                         </el-form-item>
                     </div>
                 </el-col>
             </el-row>
             
             <template #footer>
                 <div class="dialog-footer" style="display: flex; justify-content: flex-end; margin-top: 20px;">
                     <el-button @click="ys_edit_closeDialog" style="margin-left: 10px;">取消</el-button>
                     <el-button type="primary" @click="ys_edit_Dialog" style="margin-left: 10px;">确认</el-button>
                 </div>
             </template>

         </el-dialog>
      
			
			<!-- 新增订单资料弹窗 -->
            <el-dialog  v-model="add_gddialogFormVisible"  :before-close="add_gdcloseDialog"  
                title="新增订单资料" width="60%" top="4%" destroy-on-close>
			  <el-row :gutter="24" class="form-row" type="flex">
			    <el-col :span="10">
			      <el-form-item label="订单编号" class="mab" label-width="110px">
			        <el-input v-model="add_gdscgdformData.订单编号" disabled style="width: 100%;" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="客户编号" class="mab" label-width="150px">
			        <el-input v-model="add_gdscgdformData.客户编号" disabled style="width: 100%;" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="生产款号" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="add_gdscgdformData['生产款号']" style="width: 100%;" id="生产款号" @keydown="add_gdzlent($event, '订单编号', '生产款号', '款式')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="款式" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="add_gdscgdformData['款式']" style="width: 100%;" id="款式" @keydown="add_gdzlent($event, '生产款号', '款式', '客户编号')" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="落货日期" prop="deliveryDate" class="mab" label-width="150">
			        <el-date-picker v-model="add_gdscgdformData['落货日期']" type="date" style="width: 100%;" id="落货日期" @keydown="add_gdzlent($event, '客户编号', '落货日期', '面料')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row class="form-row">
			    <el-col :span="20">
			      <el-form-item label="面料" prop="customerCode" class="mab" label-width="110">
			        <el-input type="textarea" v-model="add_gdscgdformData['面料']" rows="2" resize="none" id="面料" @keydown="add_gdzlent($event, '落货日期', '面料', '要求')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row class="form-row">
			    <el-col :span="20">
			      <el-form-item label="要求" prop="customerCode" class="mab" label-width="110">
			        <el-input type="textarea" v-model="add_gdscgdformData['要求']" rows="2" resize="none" id="要求" @keydown="add_gdzlent($event, '面料', '要求', '船样描述')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="船样描述" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="add_gdscgdformData['船样描述']" style="width: 100%;" id="船样描述" @keydown="add_gdzlent($event, '要求', '船样描述', '船样合计')" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="船样合计" prop="customerCode" class="mab" label-width="150">
			        <el-input v-model="add_gdscgdformData['船样合计']" style="width: 100%;" id="船样合计" @keydown="add_gdzlent($event, '船样描述', '船样合计', '箱唛要求')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="箱唛要求" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="add_gdscgdformData['箱唛要求']" style="width: 100%;" id="箱唛要求" @keydown="add_gdzlent($event, '船样合计', '箱唛要求', '粘衬')" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="粘衬" prop="customerCode" class="mab" label-width="150">
			        <el-input v-model="add_gdscgdformData['粘衬']" style="width: 100%;" id="粘衬" @keydown="add_gdzlent($event, '箱唛要求', '粘衬', '订单数量')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="订单数量" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="add_gdscgdformData['订单数量']" style="width: 100%;" id="订单数量" @keydown="add_gdzlent($event, '粘衬', '订单数量', '单位')" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="单位" prop="customerCode" class="mab" label-width="150">
			        <el-input v-model="add_gdscgdformData['单位']" style="width: 100%;" id="单位" @keydown="add_gdzlent($event, '订单数量', '单位', '制单人')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			            
			  <el-row :gutter="24" class="form-row">
			    <el-col :span="10">
			      <el-form-item label="制单人" prop="customerCode" class="mab" label-width="110">
			        <el-input v-model="edit_ddformData['Sys_id']" disabled style="width: 100%;" id="制单人" @keydown="add_gdzlent($event, '单位', '制单人', '制单日期')" />
			      </el-form-item>
			    </el-col>
			    <el-col :span="10">
			      <el-form-item label="制单日期" prop="deliveryDate" class="mab" label-width="150">
			        <el-date-picker v-model="edit_ddformData['接单日期']" disabled type="date" style="width: 100%;" id="制单日期" @keydown="add_gdzlent($event, '制单人', '制单日期', '审核人')" />
			      </el-form-item>
			    </el-col>
			  </el-row>
			  
			<template #footer>
			  <div class="dialog-footer" style="text-align: right;">
				<el-button @click="add_gdcloseDialog">取 消</el-button>
				<el-button type="primary" @click="add_gdenterDialog">确 定</el-button>
			  </div>
			</template>
		  </el-dialog> 

            
         <el-dialog
            v-model="add_gdyjdialogFormVisible"
            :before-close="add_gdyjcloseDialog"
            style="width: 70%; max-height: 80%; overflow-y: auto; margin-top: 4%;"
            :title="'新增颜色资料'"
            destroy-on-close>
            
            <el-form label-width="100px" :model="add_yszlformdata">
              <el-row :gutter="24" class="form-row">
                <el-col :span="10">
                  <div style="display: flex; gap: 0px;">
                    <h3 style="color:red;font-size: 24px;margin:-5px 0px 8px 12px;">订单号&nbsp;&nbsp;&nbsp;{{_ddhval}}</h3>
                  </div>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="订单子编号:" class="mab" prop="keyOrder" label-width='110'>
                    <el-input v-model="add_yszlformdata.ddzbh" disabled style="width: 250px;" />
                  </el-form-item>
                </el-col>
              </el-row>
        
              <el-row :gutter="24" class="form-row">
                <el-col :span="10">
                  <el-form-item label="色系名称:" class="mab" prop="keyOrder" label-width='110'>
                    <el-select v-model="add_yszlformdata.sxmc" style="width: 150px;" @keydown="add_gdzlent($event, '款号', '尺码规格', '是否船样')">
                      <el-option label="红色系" @click="sxhandleSizeChange('红色系')" ></el-option>
                      <el-option label="黄色系" @click="sxhandleSizeChange('黄色系')" ></el-option>
                      <el-option label="蓝色系" @click="sxhandleSizeChange('蓝色系')" ></el-option>
                      <el-option label="绿色系" @click="sxhandleSizeChange('绿色系')" ></el-option>
                      <el-option label="紫色系" @click="sxhandleSizeChange('紫色系')" ></el-option>
                      <el-option label="灰色系" @click="sxhandleSizeChange('灰色系')" ></el-option>
                      <el-option label="咖啡色系" @click="sxhandleSizeChange('咖啡色系')" ></el-option>
                      <el-option label="黑白色系" @click="sxhandleSizeChange('黑白色系')" ></el-option>
                      <el-option label="经典色系" @click="sxhandleSizeChange('经典色系')" ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="生产款号:" class="mab" prop="keyOrder" label-width="110">
                    <el-input v-model="add_yszlformdata.kh" style="width: 250px;" @keydown="add_gdzlent($event, '开单员', '款号', '尺码规格')"/>
                  </el-form-item>
                </el-col>
              </el-row>
        
              <el-row :gutter="24" class="form-row">
                <el-col :span="10">
                  <el-form-item label="尺码规格:" prop="joinDate" label-width='110'>
                    <el-select v-model="add_yszlformdata.cmgg" style="width: 150px;" @keydown="add_gdzlent($event, '款号', '尺码规格', '是否船样')">
                      <el-option label="32~46" @click="cmhandleSizeChange('尺码数')"></el-option>
                      <el-option label="S~XXL" @click="cmhandleSizeChange('尺码')"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="是否船样:" prop="joinDate" label-width='110'>
                    <el-select v-model="add_yszlformdata.sfcy" style="width: 150px;" @keydown="add_gdzlent($event, '尺码规格', '是否船样', 'zds1')">
                      <el-option label="是" value="是" @click="cyChange('是')"></el-option>
                      <el-option label="否" value="否" @click="cyChange('否')"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
        
              <el-row :gutter="24" class="form-row">
                <el-col :span="24">
                  <el-form-item label="尺码:" class="mab" prop="keyOrder" label-width='110'>
                    <el-input v-model="cmformdata.cm1"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm2"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm3"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm4"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm5"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm6"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm7"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm8"  style="width: 80px;"/>
                    <el-input v-model="cmformdata.cm9"  style="width: 80px;"/>
                  </el-form-item>
                </el-col>
              </el-row>
        
              <el-row :gutter="24" class="form-row">
                <el-col :span="24">
                  <el-form-item label="制单数:" class="mab" prop="keyOrder" label-width='110'>
                    <el-input v-model="zdsformdata.zds1" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, '是否船样', 'zds1', 'zds2')"/>
                    <el-input v-model="zdsformdata.zds2" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds1', 'zds2', 'zds3')"/>
                    <el-input v-model="zdsformdata.zds3" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds2', 'zds3', 'zds4')"/>
                    <el-input v-model="zdsformdata.zds4" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds3', 'zds4', 'zds5')"/>
                    <el-input v-model="zdsformdata.zds5" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds4', 'zds5', 'zds6')"/>
                    <el-input v-model="zdsformdata.zds6" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds5', 'zds6', 'zds7')"/>
                    <el-input v-model="zdsformdata.zds7" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds6', 'zds7', 'zds8')"/>
                    <el-input v-model="zdsformdata.zds8" @input="updateTotal" style="width: 80px;" @keydown="add_gdzlent($event, 'zds7', 'zds8', 'zds9')"/>
                    <el-input v-model="zdsformdata.zds9" readonly style="width: 80px;" @keydown="add_gdzlent($event, 'zds8', 'zds9', '订单子编号')"/>
                  </el-form-item>
                </el-col>
              </el-row>
        
              <el-row class="form-row" style="width: 50%; margin: 20px auto; position: relative;">
                <el-upload  
                  ref="uploadRef"  
                  class="upload-demo"
                  list-type="picture"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-upload="beforeUpload"
                  :auto-upload="true"
                  :on-success="handleSuccess">
                  <i class="el-icon-upload"></i>
                  <el-button size="small" type="primary">点击上传</el-button>  
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>  
              </el-row>
        
            </el-form>
        
            <template #footer>
              <div class="dialog-footer" style="display: flex; justify-content: flex-end; padding: 10px;">
                <el-button type="primary" @click="add_dyjcloseDialog">取消</el-button>
                <el-button type="primary" @click="add_gdyjenterDialog">确定</el-button>
              </div>
            </template>
            
          </el-dialog>
            
        <!-- 新增工序资料-->
        <el-dialog v-model="visible" :before-close="()=> visible = false" style="width: 25%;margin: 10% auto" :title="'新增工序资料'" destroy-on-close>
    <el-form>
      <div>
        <div style="display: flex; gap: 0px;">
          <h3 style="color:red;font-size: 24px;margin:0px 0px 0px 15px;">订单号&nbsp;&nbsp;&nbsp;{{_ddhval}}</h3>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="仓库出库："  class="mab" prop="isBanciSelected" label-width="110">
        <el-checkbox v-model="form['仓库出库']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="裁切："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['裁切']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="车缝："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['车缝']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="后道收样："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['后道收样']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="大烫："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['大烫']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="总检："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['总检']"></el-checkbox>
          </el-form-item>
        </div>

        <div style="display: flex; gap: 0px;">
          <el-form-item label="包装："  class="mab" prop="isBanciSelected" label-width="110">
          <el-checkbox v-model="form['包装']"></el-checkbox>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="text-align: right;top: auto;">
      <el-button @click="add_gxcloseDialog">取 消</el-button>
      <el-button type="primary"  @click="add_gxenterDialog">确 定</el-button>
      </div>
    </template>
        </el-dialog>

        <!-- 技术附件 -->
        <el-dialog v-model="jsfjdialogFormVisible" :before-close="jsfjcloseDialog" :title="产品技术附件资料" 
		style="margin-top: 40px" height="500px" width="700px" destroy-on-close>
			  <el-form :model="jsfjformdata" label-position="right" ref="elFormRef" :rules="rule" label-width="90px">
				<el-row :gutter="24">
					<el-col :span="8">
					  <el-form-item label="关联编号:" prop="address" class="mab" >
						<el-input v-model="jsfjformdata.关联编号" disabled  id="关联编号" />
					  </el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">  
				  <el-col :span="24">  
					<el-form-item label="附件备注:" prop="address" class="mab">  
					  <el-select v-model="jsfjformdata.附件备注" placeholder="请选择附件类型" id="附件备注">  
						<el-option label="订单资料附件" value="订单资料附件"></el-option>
						<el-option label="技术附件" value="技术附件"></el-option>
					  </el-select>  
					</el-form-item>  
				  </el-col>  
				</el-row> 
				<el-row :gutter="24">
					<el-col :span="8">
						<br>
						<p>附件文件类型必须是"XLSX"格式</p> 
					</el-col>
					<el-col :span="12">
						<br>
						<input style="font-size:16px;" type="file" @change="uploadExcel" >
					</el-col>
					<el-col :span="4">
						<br>
						<el-button @click="yulan">预览</el-button>
					</el-col>
				</el-row>
			  </el-form>
			  <template #footer>
				  <br>
				<div class="dialog-footer">
				  <el-button @click="jsfjcloseDialog">取 消</el-button>
				  <el-button type="primary"  @click="jsfjenterDialog">确 定</el-button>
				</div>
			  </template>
			</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>

          </el-main>
        </layout-content>
      </layout>
    </layout>

    <PrintPage ref="printPageRef" />

  </div>
</template>
<script>
//点击按钮显示下方表格
export default {
  data() {
    return {
      currentTable: '', // 当前展示的表格
      activeName: 'first',
      _ddhval:'',

    };
  },
  methods: {
    showTable(tableName) {
      this.currentTable = tableName;
    },
    showTableChange() {
      // 处理表格选中事件
    },
  }
};
</script>
<script setup>
// 全量引入格式化工具 请按需保留
import $script from 'scriptjs'
import $ from 'jquery';
import LuckyExcel from 'luckyexcel';
import { Layout, LayoutSider, LayoutContent } from '@arco-design/web-vue';
import { ElMessage, ElMessageBox,ElUpload, ElButton } from 'element-plus'
import { ref, reactive, computed, nextTick, watch,onMounted,onBeforeUnmount } from 'vue'
import { useUserStore } from '@/pinia/modules/user'
import axios from 'axios';
import * as XLSX from 'xlsx';
import jsPDF from 'jspdf';
import {Datalist,WorkOrderList,WorkOrderAdd,PrintListData,printDetailAdd,PrintDetailDel,orderDataDel,getWorkOrder,getSuborder,PrintDataEdit,WorkOrderEdit,gdAnnexAdd,upload,OrderAttachments} from '@/api/mes/job'
import PrintPage from './components/print.vue'
import AddGongYi from './components/addGongYi.vue'  
defineOptions({name: 'Company'})
const printPageRef = ref()
const userStore = useUserStore()
const _username = ref('')
_username.value = userStore.userInfo.userName + '/' + userStore.userInfo.nickName


// =========== 左侧树侧形结构 =========== 
const treeData = ref([])
const tableData = ref([])
const _Gd_khdh = ref(null)
const defaultProps = {  
      children: 'children',  
      label: 'label'  
    };  
const Datalistdata = async () => {
  try {
    const Datalists = await Datalist();
  Datalists.data.forEach(id => {  
    treeData.value.push({  
      label: id,
    });  
  }); 
  } catch (error) {
    console.error(error);
  }
};
Datalistdata();

//点击左侧树形获取编号
const handleNodeClick = async (node) => {
  // console.log(node.label);

  // 取消所有节点的颜色
  const allNodes = document.querySelectorAll('.treecolor .el-tree-node');
  allNodes.forEach(node => {
    node.querySelector('.el-tree-node__label').style.color = '';
  });
  // 获取点击的节点 给当前点击的节点改变颜色【红色】
  const clickedNodeId = node['$treeNodeId'];
  const clickedNode = document.querySelector(`.treecolor .el-tree-node[data-key="${clickedNodeId}"]`);
  if (clickedNode) {
    clickedNode.querySelector('.el-tree-node__label').style.color = 'red';
  }
  ystableData.length = 0
  searchInfo.value = '';
  // if (node.label === '客户编号') {
  //   // console.log('点击了客户编号')
  // }else{
    _Gd_khdh.value = node.label;
    _WorkList_page();
  // } 
};

// const processValue = (parts) => {  
//   const parts = value.split('-');  
    
//   // 检查'-'后面的第一个字符是否为'0'，如果是，则移除它  
//   // if (parts[1][0] === '0') {  
//   //   parts[1] = parts[1].slice(1); // 移除第一个字符  
//   // }  
    
//   // 重新组合字符串  
//   return parts.join('-');  
// };  
//调用工单资料接口

const _WorkList_page = async () => {
  // const processedValue = processValue(_Gd_khdh.value); 
  try {
    const WorkListdata = await WorkOrderList({search:_Gd_khdh.value,page:1,limit:15});
	  console.log("上方表格数据")
    // console.log(_Gd_khdh.value)
    tableData.value=WorkListdata.data.data
    console.log(tableData)
    // total.value =WorkListdata.data.total;//共多少条
  } catch (error) {
    console.error(error);
  }
};


//订单资料修改
const ddzl_dialogFormVisible = ref(false)
const edit_ddformData = ref({})
const updateCompanyFunc = async (row) => {
	ddzl_dialogFormVisible.value = true;
  Object.assign(edit_ddformData.value,row);

}
//订单资料修改确认
const dd_edit_Dialog = async () => {
	
	//日期转换
	let lhrq_formattedDeliveryDate = '';  
	if (edit_ddformData.value.落货日期) {  
	  const date = new Date(edit_ddformData.value.落货日期);  
	  lhrq_formattedDeliveryDate = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;  
	}  
	
  let params = {};
  params.订单编号 = edit_ddformData.value.订单编号
  params.生产款号 = edit_ddformData.value.生产款号
  params.客户编号 = edit_ddformData.value.客户编号
  params.款式 = edit_ddformData.value.款式
  params.箱唛要求 = edit_ddformData.value.箱唛要求
  params.面料 = edit_ddformData.value.面料
  params.要求 = edit_ddformData.value.要求
  params.船样描述 = edit_ddformData.value.船样描述  
  params.船样合计 = edit_ddformData.value.船样合计
  params.粘衬 = edit_ddformData.value.粘衬
  params.订单数量 = edit_ddformData.value.订单数量
  params.单位 = edit_ddformData.value.单位
  params.接单日期 = edit_ddformData.value.接单日期
  params.落货日期 = lhrq_formattedDeliveryDate
  params.Sys_id = edit_ddformData.value.Sys_id
  params.id = edit_ddformData.value.Uniqid
	
  console.log(params)

  const WorkOrderEdit_list = await WorkOrderEdit(params);
  if(WorkOrderEdit_list.code === 0){
    ddzl_dialogFormVisible.value = false;
    _WorkList_page()
    ElMessage({type: 'success',message: '修改成功'})
  }else{
    ElMessage({type: 'error',message: '修改失败'})
  }
  
}


//订单资料修改取消
const dd_closeDialog = async () => {
  ddzl_dialogFormVisible.value = false;
}


//颜色资料修改
const dialogFormVisible = ref(false)
const edit_cmformdata = reactive({
  cm1:'',
  cm2:'',
  cm3:'',
  cm4:'',
  cm5:'',
  cm6:'',
  cm7:'',
  cm8:'',
  cm9:'总计',
});
const edit_zdsformdata = reactive({
  zds1:'',
  zds2:'',
  zds3:'',
  zds4:'',
  zds5:'',
  zds6:'',
  zds7:'',
  zds8:'',
  zds9:'',
});
const edit_formData = ref({})

//颜色资料表格双击
const ysupdateCompanyFunc = async (row) => {
	dialogFormVisible.value = true;
	edit_formData.value = { ...row };

  let index = 1;  
  // 创建一个函数来构建尺码和数量的映射  
  function buildSizeQuantitiesMap(sizes, formData) {  
    const sizeQuantitiesMap = {};  
    sizes.forEach(size => {  
      // 使用逻辑或操作符确保所有尺码都有数量（默认为0，但如果有值则使用那个值）  
      const quantity = formData[size] || 0;  
      sizeQuantitiesMap[size] = quantity;  
    });  
    return sizeQuantitiesMap;  
  }  
  // 使用函数构建映射  
  let sizeQuantitiesMap = buildSizeQuantitiesMap(sizeDatas, edit_formData.value);  
  let edit_params = {};
  for (const [size, quantity] of Object.entries(sizeQuantitiesMap)) {  
      edit_params[`cm${index}`] = size;  
      edit_params[`cmsl${index++}`] = quantity;  
    }  
    console.log(edit_params)
    edit_cmformdata['cm1'] = edit_params['cm1']
    edit_cmformdata['cm2'] = edit_params['cm2']
    edit_cmformdata['cm3'] = edit_params['cm3']
    edit_cmformdata['cm4'] = edit_params['cm4']
    edit_cmformdata['cm5'] = edit_params['cm5']
    edit_cmformdata['cm6'] = edit_params['cm6']
    edit_cmformdata['cm7'] = edit_params['cm7']
    edit_cmformdata['cm8'] = edit_params['cm8']
    edit_zdsformdata['zds1'] = edit_params['cmsl1']
    edit_zdsformdata['zds2'] = edit_params['cmsl2']
    edit_zdsformdata['zds3'] = edit_params['cmsl3']
    edit_zdsformdata['zds4'] = edit_params['cmsl4']
    edit_zdsformdata['zds5'] = edit_params['cmsl5']
    edit_zdsformdata['zds6'] = edit_params['cmsl6']
    edit_zdsformdata['zds7'] = edit_params['cmsl7']
    edit_zdsformdata['zds8'] = edit_params['cmsl8']
    //updateTotal()计算尺码数量总数合计
    updateTotal()
};


// 修改确认
const ys_edit_Dialog = async () => {
//   console.log(sizeDatas)
//   console.log(edit_formData)
if (!edit_formData.value) return;
// 创建一个函数来构建尺码和数量的映射  
function buildSizeQuantitiesMap(sizes, formData) {  
    const sizeQuantitiesMap = {};  
    sizes.forEach(size => {  
      const quantity = formData[size] || 0; // 使用逻辑或操作符确保所有尺码都有数量  
      sizeQuantitiesMap[size] = quantity;  
    });  
    return sizeQuantitiesMap;  
  }  
  
  // 使用函数构建映射  
  const sizeQuantitiesMap = buildSizeQuantitiesMap(sizeDatas, edit_formData.value);  

  let index = 1;  
  const params = {  
    订单编号: edit_formData.value.订单编号,  
    子订单编号: edit_formData.value.子订单编号,  
    款号: edit_formData.value.款号,  
    船样: edit_formData.value.船样 === 1 ? '是' : '否', // 转换船样字段  
    颜色: edit_formData.value.颜色,  
    zdtotal: edit_formData.value.zdtotal,  
    Sys_id: edit_formData.value.Sys_id,  
    id: edit_formData.value.Uniqid,  
  };  
  // buildSizeQuantitiesMap()
  for (const [size, quantity] of Object.entries(sizeQuantitiesMap)) {  
    params[`cm${index}`] = size;  
    params[`cmsl${index}`] =+ edit_zdsformdata[`zds${index++}`];  
  }  
  console.log(params);
  const PrintDataEdit_list = await PrintDataEdit(params);
  if(PrintDataEdit_list.code === 0){
	  dialogFormVisible.value = false;
    ElMessage({type: 'success',message: '修改成功'})
    tableRowClick(params)
  }else{
    ElMessage({type: 'error',message: '修改失败'})
  }

  // console.log(edit_formData.value)
  // const PrintDataEdit_list = await PrintDataEdit();
	// dialogFormVisible.value = false;
  
};
// 修改取消
const ys_edit_closeDialog = async (row) => {
	dialogFormVisible.value = false;
};



// 分页
const page = ref(1)
const total = ref(0)
const pageSize = ref(50)
const handleCurrentChange = (val) => {
  page.value = val;
  _WorkList_page();
};

// 修改页面容量 点击多少条/页
const handleSizeChange = (val) => {
  // page.value = 10;
  pageSize.value = val;
  _WorkList_page();
};

// =========== 新增 ===========
// 获取当前日期
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_gdscgdformData = reactive({
  订单编号: '',
  生产款号: '',
  款式: '',
  客户编号: '',
  落货日期: '',
  箱唛要求: '',
  面料: '',
  要求: '',
  船样描述: '',
  船样合计: '',
  粘衬: '',
  订单数量: '',
  单位: '件',
  Sys_id: '',
  制单日期: '',
  // 审核人: '',
  审核日期: '',
});
//清空对象的属性值
const gd_clearFormData = () => {
  Object.keys(add_gdscgdformData).forEach(key => {
    add_gdscgdformData[key] = '';
  });
};

const add_gddialogFormVisible = ref(false)
//点击新增订单资料按钮
const addgd_onclick = async ()=>{
  console.log(_Gd_khdh.value)
  if(_Gd_khdh.value === '' ||  _Gd_khdh.value === null){
	  ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能' })
	  return false;
  }else{
    add_gddialogFormVisible.value = true
    const getWorkOrder_list = await getWorkOrder();
    // console.log(getWorkOrder_list)
    add_gdscgdformData['订单编号'] = getWorkOrder_list.data;
    add_gdscgdformData['客户编号'] = _Gd_khdh.value
    add_gdscgdformData['制单人'] = _username.value 

    add_gdscgdformData['生产款号'] = ''
    add_gdscgdformData['款式'] = ''
    add_gdscgdformData['落货日期'] = ''
    add_gdscgdformData['面料'] = ''
    add_gdscgdformData['要求'] = ''
    add_gdscgdformData['船样描述'] = ''
    add_gdscgdformData['船样合计'] = ''
    add_gdscgdformData['箱唛要求'] = ''
    add_gdscgdformData['粘衬'] = ''
    add_gdscgdformData['订单数量'] = ''
    add_gdscgdformData['制单日期'] = currentDates;


    
    // add_gdscgdformData['落货日期'] = '2024-07-28';
  }
  

}


//新增工单资料确定
const add_gdenterDialog = async ()=>{
	if(add_gdscgdformData['订单编号'] === '' ||  add_gdscgdformData['订单编号'] === undefined){
	  ElMessage({type: 'warning',message: '订单编号不能为空' })
	  return false;
	}
  if(add_gdscgdformData['客户编号'] === '' ||  add_gdscgdformData['客户编号'] === undefined){
	  ElMessage({type: 'warning',message: '客户编号不能为空' })
	  return false;
	}
  if(add_gdscgdformData['订单数量'] === '' ||  add_gdscgdformData['订单数量'] === undefined){
	  ElMessage({type: 'warning',message: '客户编号不能为空' })
	  return false;
	}
  if(add_gdscgdformData['制单日期'] === '' ||  add_gdscgdformData['制单日期'] === undefined){
	  ElMessage({type: 'warning',message: '制单日期不能为空' })
	  return false;
	}

  //日期转换
  let lhrq_formattedDeliveryDate = '';  
  if (add_gdscgdformData['落货日期']) {  
    const date = new Date(add_gdscgdformData['落货日期']);  
    lhrq_formattedDeliveryDate = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;  
  }  
  let zdrq_formattedDeliveryDate = '';  
  if (add_gdscgdformData['制单日期']) {  
    const date = new Date(add_gdscgdformData['制单日期']);  
    zdrq_formattedDeliveryDate = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;  
  }  

	const formattedData = {
		订单编号: add_gdscgdformData['订单编号'],
		生产款号: add_gdscgdformData['生产款号'],
		款式: add_gdscgdformData['款式'],
		客户编号: add_gdscgdformData['客户编号'],
		落货日期: lhrq_formattedDeliveryDate,
		箱唛要求: add_gdscgdformData['箱唛要求'],
		面料: add_gdscgdformData['面料'],
		要求: add_gdscgdformData['要求'],
		船样描述: add_gdscgdformData['船样描述'],
		船样合计: add_gdscgdformData['船样合计'],
		粘衬: add_gdscgdformData['粘衬'],
		订单数量: add_gdscgdformData['订单数量'],
		单位: add_gdscgdformData['单位'],
		Sys_id: add_gdscgdformData['制单人'],
		接单日期: zdrq_formattedDeliveryDate,
		// 审核人: add_gdscgdformData['审核人'],
		// 审核日期: add_gdscgdformData['审核日期']
	};
	console.log(formattedData)
	const edit_gdformdata_list = await WorkOrderAdd(formattedData);
	if (edit_gdformdata_list.code === 0) {
		add_gddialogFormVisible.value = false;
		ElMessage({type: 'success',message: '新增成功'})
    const WorkListdata = await WorkOrderList({search:_Gd_khdh.value,page:1,limit:15});
	  console.log("上方表格数据")
    tableData.value=WorkListdata.data.data
	} else {
		ElMessage({ type: 'error',message: '新增失败'})
	}
 
}
//新增工单资料取消
const add_gdcloseDialog = () => {
  add_gddialogFormVisible.value = false
}


// =========== 新增颜色资料 ===========
//默认弹窗关闭
const add_gdyjdialogFormVisible = ref(false)
const add_yszlformdata = reactive({
  ddh: '',
  ddzbh: '',
  sxmc: '',
  cmgg: '',
  sfcy: '',
});
const cmformdata = reactive({
  cm1:'32',
  cm2:'34',
  cm3:'36',
  cm4:'38',
  cm5:'40',
  cm6:'42',
  cm7:'44',
  cm8:'46',
  cm9:'总计',
});
const zdsformdata = reactive({
  zds1:'',
  zds2:'',
  zds3:'',
  zds4:'',
  zds5:'',
  zds6:'',
  zds7:'',
  zds8:'',
  zds9:'',
});
const sxhandleSizeChange = (value) => {
  // console.log(value)
  if (value === '红色系') {
    add_yszlformdata.sxmc = '红色系'
	} else if(value === '黄色系'){
    add_yszlformdata.sxmc = '黄色系'
  }else if(value === '蓝色系'){
    add_yszlformdata.sxmc = '蓝色系'
  }else if(value === '绿色系'){
    add_yszlformdata.sxmc = '绿色系'
  }else if(value === '紫色系'){
    add_yszlformdata.sxmc = '紫色系'
  }else if(value === '灰色系'){
    add_yszlformdata.sxmc = '灰色系'
  }else if(value === '咖啡色系'){
    add_yszlformdata.sxmc = '咖啡色系'
  }else if(value === '黑白色系'){
    add_yszlformdata.sxmc = '黑白色系'
  }else if(value === '经典色系'){
    add_yszlformdata.sxmc = '经典色系'
  }
};

const cmhandleSizeChange = (value) => {
  // console.log(value)
  if (value === '尺码数') {
	  cmformdata.cm1 = '32';
	  cmformdata.cm2 = '34';
	  cmformdata.cm3 = '36';
	  cmformdata.cm4 = '38';
	  cmformdata.cm5 = '40';
	  cmformdata.cm6 = '42';
	  cmformdata.cm7 = '44';
	  cmformdata.cm8 = '46';
	  cmformdata.cm9 = '总计';
	} else if (value === '尺码') {
	  cmformdata.cm1 = 'S';
	  cmformdata.cm2 = 'M';
	  cmformdata.cm3 = 'L';
	  cmformdata.cm4 = 'XL';
	  cmformdata.cm5 = 'XXL';
	  cmformdata.cm6 = '3XL';
	  cmformdata.cm7 = '4XL';
	  cmformdata.cm8 = '';
	  cmformdata.cm9 = '总计';
	}
};
//清空对象的属性值
const gdyj_clearFormData = () => {
  Object.keys(zdsformdata).forEach(key => {
    zdsformdata[key] = '';
  });

};

//自动计算制单数总计
function updateTotal() {  
  // 直接指定要累加的属性名  
  const relevantKeys = ['zds1', 'zds2', 'zds3', 'zds4', 'zds5', 'zds6', 'zds7', 'zds8'];  
  const values = relevantKeys.map(key => parseInt(zdsformdata[key], 10) || 0); // 使用 || 0 来处理可能的 NaN 或 undefined/null  
  zdsformdata.zds9 = values.reduce((sum, value) => sum + value, 0);  
  const valuess = relevantKeys.map(key => parseInt(edit_zdsformdata[key], 10) || 0); // 使用 || 0 来处理可能的 NaN 或 undefined/null  
  edit_zdsformdata.zds9 = valuess.reduce((sum, value) => sum + value, 0); 
}  

//
const cyChange = async (value) => {
  const getSuborders = await getSuborder({order:_Gd_gdbh.value});
  if (value === '是') {
    add_yszlformdata.ddzbh = _Gd_gdbh.value + '-99'
	}else if(value === '否'){
    add_yszlformdata.ddzbh = getSuborders.data
  }
};

//新增颜色资料按钮
const addgdyj_onclick = async  () => {
  if(_Gd_gdbh.value === '' || _Gd_gdbh.value === null){
    ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能'})
    return false;
  }else{
    const getSuborders = await getSuborder({order:_Gd_gdbh.value});
    add_gdyjdialogFormVisible.value = true
    add_yszlformdata['ddh'] = _Gd_gdbh.value;
    add_yszlformdata['ddzbh'] = getSuborders.data;
    add_yszlformdata['ys'] = '';
	add_yszlformdata['kh'] = '';
	add_yszlformdata['sxmc'] = '';
    add_yszlformdata['cmgg'] = '32~46';
    add_yszlformdata['sfcy'] = '否';
    add_yszlformdata['kdy'] = _username.value;
    gdyj_clearFormData();
  }
}

//新增颜色资料按钮确定
const add_gdyjenterDialog =  async  () => {
  let cy = '';
  if(add_yszlformdata['sfcy'] === '是'){
     cy = '1'
  }else if(add_yszlformdata['sfcy'] === '否'){
     cy = '0'
  }
  const addyszltable = {
    订单编号: add_yszlformdata['ddh'],
		子订单编号: add_yszlformdata['ddzbh'],
		颜色: add_yszlformdata['sxmc'],
    款号: add_yszlformdata['kh'],
		船样: cy,
    Sys_id:add_yszlformdata['kdy'],
    cm1: cmformdata['cm1'],
    cm2: cmformdata['cm2'],
    cm3: cmformdata['cm3'],
    cm4: cmformdata['cm4'],
    cm5: cmformdata['cm5'],
    cm6: cmformdata['cm6'],
    cm7: cmformdata['cm7'],
    cm8: cmformdata['cm8'],
    // 合计: zdsformdata['cm9'],
		cmsl1: zdsformdata['zds1'],
    cmsl2: zdsformdata['zds2'],
    cmsl3: zdsformdata['zds3'],
    cmsl4: zdsformdata['zds4'],
    cmsl5: zdsformdata['zds5'],
    cmsl6: zdsformdata['zds6'],
    cmsl7: zdsformdata['zds7'],
    cmsl8: zdsformdata['zds8'],
    zdtotal: zdsformdata['zds9'],

    // 图片:previewFiles['value']['0']['name']
	};
  // try {  
  //   // 检查 fileList 是否有文件需要上传  
  //   if (fileList.length > 0) {  
  //     // 手动触发上传  
  //     await new Promise((resolve, reject) => {  
  //       // 假设 submitUpload 返回一个 Promise，我们可以直接等待它  
  //       // 如果 submitUpload 不返回 Promise，则需要对其进行修改以支持异步操作  
  //       submitUpload().then(() => {  
  //         // 上传成功后继续执行  
  //         resolve();  
  //       }).catch((error) => {  
  //         // 上传失败，可以根据需要处理错误  
  //         ElMessage.error('图片上传失败，请重试！');  
  //         reject(error);  
  //       });  
  //     });  
  //   } else {  
  //     // 如果没有文件需要上传，则直接继续执行  
  //     console.log('没有文件需要上传');  
  //   }  
  // } catch (error) {  
  //   // 处理上传过程中的错误，可以阻止后续的新增逻辑  
  //   return; // 或者根据需求进行其他错误处理  
  // }   

  const printDetailAdds = await printDetailAdd(addyszltable);
  if (printDetailAdds.code === 0) {
		add_gdyjdialogFormVisible.value = false;
		ElMessage({type: 'success',message: '新增成功'})
  }
  const PrintListDatas = await PrintListData({order:_Gd_gdbh.value})
        if(PrintListDatas.data.列表.length === 0){
          ystableData.length = 0
        }else{
          sizeDatas.splice(0,PrintListDatas.data.型号.length,...PrintListDatas.data.型号);//型号数据
          ystableData.splice(0,PrintListDatas.data.列表.length,...PrintListDatas.data.列表);//表格数据
        }
  
}  

const fileList = reactive([]); // 存储已选择的文件列表  
const uploadRef = ref(null); // 上传组件的引用  
  
// 方法定义  
const handlePreview = (file) => {  
  console.log('预览文件:', file);  
  // 预览逻辑  
};  
  
const handleRemove = (file, fileList) => {  
  console.log('移除文件:', file, '剩余文件:', fileList);  
  // 由于 Element Plus/UI 会自动处理 fileList 的更新，这里通常不需要额外操作  
};  
  
const beforeUpload = (file) => {  
  const isImage = file.type.startsWith('image/');  
  const isLt500K = file.size / 1024 / 1024 < 0.5;  
  if (!isImage) {  
    ElMessage.error('上传文件只能是图片格式!');  
    return false;  
  }  
  if (!isLt500K) {  
    ElMessage.error('上传图片大小不能超过 500KB!');  
    return false;  
  }  
  return true; // 允许上传  
};  
  
const handleSuccess = (response, file, fileList) => {  
  console.log('上传成功:', response, file, fileList);  
  // 上传成功后的逻辑  
};  
  
// const submitUpload = () => {  
//   uploadRef.value.submit(); // 手动触发上传  
// };  
// const imageInput = ref(null);  // 通过 ref 获取文件输入 DOM

// const uploadFile = () => {
//   console.log('按钮被点击');
  
//   const file = imageInput.value.files[0];  // 获取选中的文件
//   if (!file) {
//     console.error('未选择文件');
//     return;
//   }
//   let data  = new FormData()
//   data.append('image',file)
//   for (let [key, value] of data.entries()) { 
//   console.log(key, value); 
// }

//   fetch('http://20.0.16.128:8082/index.php/api/work_order/ImgUpload', {  // 使用 fetch 发送文件
//     method: 'POST',
//     body: data,  // 直接将文件对象作为请求体
//     headers: {  
//     'x-token': userStore.token  // 添加自定义的 x-token 请求头  
//   },  
//   })
//   .then(response => response.json())
//   .then(data => {
//     console.log('上传成功:', data);
//   })
//   .catch(error => {
//     console.error('上传失败:', error);
//   });
// };




//新增颜色资料取消
const add_dyjcloseDialog = () => {
  add_gdyjdialogFormVisible.value = false
}
//新增工单资料弹窗 键盘input框跳转
const add_gdzlent = async (event,id1,id2,id3,idx) => {
  if(event.keyCode === 40){
    if(id3!=''){
      document.getElementById(id3).focus()
    }
  }else if (event.keyCode === 13) { // Enter 或向下箭头
    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()
    }
  }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()
    }
  }
}


// =========== 新增工序资料 ===========
const visible = ref(false)
const form = reactive({
  '仓库出库':true,
  '裁切':true,
  '车缝':true,
  '后道收样':true,
  '大烫':true,
  '总检':true,
  '包装':true,
})

//新增工序资料按钮
const addgdgy_onclick = () => {
  if(_Gd_gdbh.value === '' || _Gd_gdbh.value === null){
    ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能'})
    return false;
  }else{
    visible.value = true;
  }
}

//新增工序资料确定按钮
const add_gxenterDialog = () => {
	console.log(form)


	const formattedData = {
		ckck: form['仓库出库'],
		cq: form['裁切'],
		cf: form['车缝'],
		hdsy: form['后道收样'],
		dt: form['大烫'],
		zj: form['总检'],
		bz: form['包装']
	};
	// true 选择 fasle 未选择
	for (let key in formattedData) {
	    if (formattedData[key] === true) {
	        formattedData[key] = 1;
	    } else if (formattedData[key] === false) {
	        formattedData[key] = 2;
	    }
	}
  	console.log(formattedData)
  //1.2新增工序资接口
	// const add_gxformdata_list = await 新增工序资料(formattedData);
	// if (edit_gxformdata_list.code === 0) {
	// 	visible.value = false;
	// 	ElMessage({type: 'success',message: '新增成功'})
	// } else {
	// 	ElMessage({ type: 'error',message: '新增失败'})
	// }
}

//新增工序资料取消按钮
const add_gxcloseDialog = () => {
    visible.value = false;
}

// =========== 订单打印 ===========
const cp_gdprintonClick = () => {
  if(_Gd_gdbh.value === '' || _Gd_gdbh.value === null){
    ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能'})
    return false;
  }else{
    if(ystableData.length >=1){
      printPageRef.value.open(_Gd_gdbh.value) 
    }else{
      ElMessage({type: 'warning',message: '请新增颜色资料，再操作此功能'})
      return false;
    }
  }
}


//点击表格行获取下方表格数据列表
// =========== 颜色资料、工艺资料、技术资料附件 ===========
//全局调用订单号编号
const _Gd_gdbh = ref('')
const _ddhval = ref('')
//颜色资料
const ystableData = reactive([])
//尺寸列表
const sizeDatas = reactive([])
//工艺资料
const gytableData = reactive([])
//订单资料表
const ddtableData = reactive([])
//技术附件
const jstableData = reactive([])
// 点击订单资料行
const tableRowClick = async (row) => {
    console.log(row.订单编号)
    _Gd_gdbh.value = row.订单编号
    _ddhval.value = row.订单编号
    sizeDatas.length = 0
    try {
		//数据列表显示
        const PrintListDatas = await PrintListData({order:_Gd_gdbh.value})
        const jsOrderAttachments = await OrderAttachments({order:_Gd_gdbh.value,desc:'技术附件'})
        const ddOrderAttachments = await OrderAttachments({order:_Gd_gdbh.value,desc:'订单资料附件'})
		
		
		
		//颜色资料
        if(PrintListDatas.data.列表.length === 0 ){
          ystableData.length = 0
        }else{
          sizeDatas.splice(0,PrintListDatas.data.型号.length,...PrintListDatas.data.型号);//型号数据
          ystableData.splice(0,PrintListDatas.data.列表.length,...PrintListDatas.data.列表);//表格数据
          // 使用 map 方法创建一个新数组，并转换船样字段  
          const newData = PrintListDatas.data.列表.map(item => ({  
              ...item,  
              船样: item.船样 === 1 ? '是' : '否'  
          }));  
          // 将新数组赋值给 ystableData，这会触发视图更新，清空旧数据（可选，如果不需要保留旧数据的话）  
          ystableData.length = 0;  
          ystableData.push(...newData);
        }
		
		//技术附件
		if(jsOrderAttachments.data === ''){
		  const WorkListdata = [];
		  jstableData.splice(0,jstableData.length,...WorkListdata);
		}
		
        if(jsOrderAttachments.code === 0 && ddOrderAttachments.code === 0){
          jstableData.splice(0,jsOrderAttachments.data.length,...jsOrderAttachments.data);
          ddtableData.splice(0,ddOrderAttachments.data.length,...ddOrderAttachments.data);
        }
      } catch (error) {
        console.error(error);
    }
}

//pdf
const showPdfModal = ref(false);
const pdfContainer = ref(null);

const closeModal = () => {
  showPdfModal.value = false;
};

const fetchAndConvertFile = async () => {
  try {
    // 从后端获取 Base64 编码的 XLSX 文件数据
    const responses = await OrderAttachments({order:_Gd_gdbh.value,desc:'技术附件'});
    const response= responses.data[0].附件内容
    const base64Data = response.match(/base64,(.*)$/)?.[1]; 

if (!base64Data) {
  throw new Error('Invalid Base64 data');
}

const binaryString = atob(base64Data);
const binaryLen = binaryString.length;
const bytes = new Uint8Array(binaryLen);

for (let i = 0; i < binaryLen; i++) {
  bytes[i] = binaryString.charCodeAt(i);
}

       // 解析 XLSX 文件
       const workbook = XLSX.read(bytes, { type: 'array' });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    console.log(121212,worksheet)
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    generatePdf(jsonData);
  } catch (error) {
    console.error('Error fetching and converting file:', error);
  }
};

const generatePdf = (data) => {
  const doc = new jsPDF();

  let yPosition = 10;
  data.forEach((row) => {
    doc.text(10, yPosition, JSON.stringify(row));
    yPosition += 10;
  });

  const pdfBlob = doc.output('blob');

  previewPdf(pdfBlob);
  downloadPdf(pdfBlob);
};

const previewPdf = (blob) => {
  const fileURL = URL.createObjectURL(blob);

  // 通过 ref 引用 pdfContainer 来在指定容器中显示 PDF
  const iframe = document.createElement('iframe');
  iframe.src = fileURL;
  iframe.width = '100%';
  iframe.height = '600px';

  if (pdfContainer.value) {
    pdfContainer.value.innerHTML = ''; // 清空之前的内容
    pdfContainer.value.appendChild(iframe);
  }
};

// const downloadPdf = (blob) => {
//   const link = document.createElement('a');
//   const fileURL = URL.createObjectURL(blob);
//   link.href = fileURL;
//   link.download = 'file.pdf';
//   link.click();
// };

//表格复选框
const table_del = ref(true)//删除订单资料
const table_Selection = ref('')//存储选中Uniqid
const handleSelectionChange = (selection, type) => {
  const ids = selection.map(item => {
    return item.Uniqid
  })
  table_Selection.value = ids.join(',')
  console.log(table_Selection.value)
}

//删除按钮
const del_ddzlClick = async () => {
  console.log(table_Selection._value)
  let params = {};  
  params.Uniqid = table_Selection._value; 
  console.log(params)
  const res1 = await orderDataDel(params)
  res1.code === 0 && ElMessage.success('删除成功')
}


const delall = ref(true)
//颜色复选框
const ysSelection = ref('')
//工艺复选框
const gySelection = ref('')
// 颜色资料多选、工艺资料多选
const selectionChange = (selection, type) => {
  console.log(selection)
  const ids = selection.map(item => {
	  if(type === '颜色资料'){
		return type === '颜色资料' ? item.Uniqid: item.Uniqid
	  }
	  if(type === '工艺资料'){
	  return type === '工艺资料' ? item.Uniqid: item.Uniqid
	  } 
  })
  
  if (type === '颜色资料') {
    ysSelection.value = ids.join(',')
  }
  if (type === '工艺资料') {
    gySelection.value = ids.join(',')
  }
}

// ===========删除颜色资料、工艺资料 ===========
const delgd_delclick = async () => {
  console.log(ysSelection.value)
  console.log(gySelection.value)

  if (ysSelection.value !== '') {
    try {
      const res1 = await PrintDetailDel({UniqId: ysSelection.value})
      res1.code === 0 && ElMessage.success('颜色资料删除成功')
    } catch(err) {
      ElMessage.error(err)
    }
  }
  if (gySelection.value !== ''){
    try {
      const res2 = await PrintDetailDel({UniqId: gySelection.value})
      if(res2.code === 0){
        ElMessage.success('工艺资料删除成功')
        const PrintListDatas = await PrintListData({order:_Gd_gdbh.value})
        sizeDatas.splice(0,PrintListDatas.data.型号.length,...PrintListDatas.data.型号);//型号数据
        ystableData.splice(0,PrintListDatas.data.列表.length,...PrintListDatas.data.列表);//表格数据
      }else{
        console.log('?')
      }
    } catch(err) {
      ElMessage.error(err)
    }
  } 
}

  //合计
  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] = 'N/A';  
            }  
        }  
    });  
  
    return sums;  
};  




//=========查询========
const searchInfo = ref('')
//查询按钮
const onSubmit = async () => {
  if(searchInfo.value === ''){
    ElMessage({type: 'warning',message: '请输入搜索的订单编号'})
    return false;
  }else{
    const WorkListdata = await WorkOrderList({search:searchInfo.value,page:1,limit:15});
    tableData.value=WorkListdata.data.data
    console.log(searchInfo.value)
  }
};
//回车查询
const handleSearch = async (event) => {
  if(searchInfo.value === ''){
    ElMessage({type: 'warning',message: '请输入搜索的信息'})
    return false;
  }else{
    const WorkListdata = await WorkOrderList({search:searchInfo.value,page:1,limit:15});
    tableData.value=WorkListdata.data.data
    console.log("回车了");
  }

  // _cha_WorkList();
};
// 调用查询数据接口
const _cha_WorkList = async (node) => {
  if(searchInfo.value === ''){
    ElMessage({type: 'warning',message: '请输入搜索的信息'})
    return false;
  }
  const search = searchInfo.value;
  var regex = /^[a-zA-Z0-9]+$/;
  try {
    if (regex.test(search)) {
      // 符合条件，执行搜索操作
      console.log('搜索内容为纯数字加字母');
      // const WorkListdata = await WorkList({search:search,limit:100,page:1});//接口调用函数
      if(WorkListdata.data.total === 0){
        ElMessage({type: 'warning',message: '未搜索具体查询条件'})
      }
      tableData.splice(0,tableData.length,...WorkListdata.data.data);//表格数据
      total.value = WorkListdata.data.total;//共多少条
    } else {
      // 不符合条件，给出提示
      console.log('搜索内容包含非字母和数字的字符');
      // const WorkListdata = await WorkList({Gd_khdh:'',search:search,limit:100,page:1});//接口调用函数
      if(WorkListdata.data.total === 0){
        ElMessage({type: 'warning',message: '未搜索具体查询条件'})
      }
      tableData.splice(0,tableData.length,...WorkListdata.data.data);//表格数据
      total.value = WorkListdata.data.total;//共多少条
    }
  } catch (error) {
    console.error(error);
  }
};


//图片粘贴拖拽上传


// =========技术附件========
//点击技术附件按钮
const jsfjClick = () => {
  if(_Gd_gdbh.value === '' || _Gd_gdbh.value === null){
	  ElMessage({type: 'warning',message: '请选择具体的工单后，再操作此功能'})
	}else{
		jsfjdialogFormVisible.value = true
		initJsfjformdata();
		jsfjformdata.value.关联编号 = _Gd_gdbh.value
	}
}
//技术附件弹窗
const jsfjdialogFormVisible = ref(false)
const jsfjformdata = ref({
	sys_id: _username.value,
	附件备注: '',
	附件内容: '',
	附件类型: '',
	关联编号: '',
});
//技术附件弹窗取消
const initJsfjformdata = () => {
  jsfjformdata.value = {
	sys_id: _username.value,
	附件备注: '',
	附件内容: '',
	附件类型: '',
	关联编号: '',
  }
}
//技术附件弹窗取消
const jsfjcloseDialog = () => {
  jsfjdialogFormVisible.value = false
}
const uploadExcel = (event) =>{
	const files = event.target.files;
	let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
	// if(suffix!="xlsx"){
	// 	alert("Currently  only supports the import of xlsx files");
	// 	return;
	// }
	jsfjformdata.value.附件内容 = files[0]
	jsfjformdata.value.附件类型 = 'XLSX'
}
//技术附件预览
const yulan = (event) =>{
	if(!jsfjformdata.value.附件内容) return
	$.getScript('/luckysheet/plugins/js/plugin.js', () => {
			$script('/luckysheet/luckysheet.umd.js', () => {
			luckyexcelVisible.value = true
			LuckyExcel.transformExcelToLucky(jsfjformdata.value.附件内容, function(exportJson, luckysheetfile){
				if(exportJson.sheets==null || 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', //容器的ID
					data: exportJson.sheets,
					title: exportJson.info.name, // 工作簿名称
					lang: "zh", // 设定表格语言 国际化设置，允许设置表格的语言，支持中文("zh")和英文("en")
					showtoolbar: false, // 是否显示工具栏
					showinfobar: false, // 是否显示顶部信息栏
					allowEdit: false, // 是否允许前台编辑
					enableAddRow: false, // 允许增加行
					enableAddCol: false, // 允许增加列
					userInfo: false, // 右上角的用户信息展示样式
					showRowBar: false, // 是否显示行号区域
					showColumnBar: false, // 是否显示列号区域
					sheetFormulaBar: false, // 是否显示公式栏
					enableAddBackTop: false,//返回头部按钮
				});
				luckyExcel = luckysheet;
			})
		})
		})
		$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/plugins/css/pluginsCss.css'));
		$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/plugins/plugins.css'));
		$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/css/luckysheet.css'));
		$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/assets/iconfont/iconfont.css'));

}
const jsfj_del = (row) =>{
	ElMessageBox.confirm('确定要删除吗?', '提示', {
	    confirmButtonText: '确定',
	    cancelButtonText: '取消',
	    type: 'warning'
	}).then(() => {
		gdAnnexDel({'UniqId':row.UniqId,'gdbh':_Gd_gdbh.value}).then(response => {
			 if(response.code==0){
				 ElMessage({
				   type: 'success',
				   message: '删除成功',
				 })

				 let row = {
					 '订单编号':_Gd_gdbh.value,
					//  '产品代号':_Gd_cpdh.value,
					//  '产品名称':_Gd_cpmc.value,
				 }
				 tableRowClick (row)
			  }
		   })
	})

}

//技术附件弹窗确定
const jsfjenterDialog = () => {
	
	// console.log(jsfjformdata.value.附件类型)
	
	
	// return;
	if(jsfjformdata.value.附件备注==''){
		ElMessage({
			type: 'error',
			message: '请填写附件备注'
		});
		return;
	}
	if(jsfjformdata.value.附件内容==''){
		ElMessage({
			type: 'error',
			message: '请上传文件'
		});
		return;
	}
	if(jsfjformdata.value.关联编号==''){
		ElMessage({
			type: 'error',
			message: '请填写关联编号'
		});
		return;
	}
	//判断验证上传文件类型是否为 xlsx
	// if(){//不是此类型提示
		
	// }

	let fr = new FileReader();
	fr.readAsDataURL(jsfjformdata.value.附件内容);
	fr.onload = function () {
	  const restoredData = new FormData();
	  restoredData.append('sys_id', jsfjformdata.value.sys_id);
	  restoredData.append('附件备注', jsfjformdata.value.附件备注);
	  restoredData.append('附件内容', fr.result);
	  restoredData.append('附件类型', jsfjformdata.value.附件类型);
	  restoredData.append('关联编号', jsfjformdata.value.关联编号);

	   gdAnnexAdd(restoredData).then(response => {
		 if(response.code==0){
			 ElMessage({
			   type: 'success',
			   message: '新增成功',
			 })
			 jsfjdialogFormVisible.value = false
			 let row = {
				 '订单编号':_Gd_gdbh.value,
				//  '产品代号':_Gd_cpdh.value,
				//  '产品名称':_Gd_cpmc.value,
			 }
			 tableRowClick (row)
		 }
	   })
	}
}

//技术资料excel展示
const ExcelShow = (row) =>{
	console.log("技术资料excel展示")
	console.log(row)
	if(!row.附件内容) return
	$.getScript('/luckysheet/plugins/js/plugin.js', () => {
		$script('/luckysheet/luckysheet.umd.js', () => {
					function 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' });
					}

					const blob = dataURLtoBlob(row.附件内容);
					luckyexcelVisible.value = true
					LuckyExcel.transformExcelToLucky(blob, function(exportJson, luckysheetfile){
						if(exportJson.sheets==null || 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', //容器的ID
							data: exportJson.sheets,
							title: exportJson.info.name, // 工作簿名称
							lang: "zh", // 设定表格语言 国际化设置，允许设置表格的语言，支持中文("zh")和英文("en")
							showtoolbar: false, // 是否显示工具栏
							showinfobar: false, // 是否显示顶部信息栏
							allowEdit: false, // 是否允许前台编辑
							enableAddRow: false, // 允许增加行
							enableAddCol: false, // 允许增加列
							userInfo: false, // 右上角的用户信息展示样式
							showRowBar: false, // 是否显示行号区域
							showColumnBar: false, // 是否显示列号区域
							sheetFormulaBar: false, // 是否显示公式栏
							enableAddBackTop: false,//返回头部按钮
						});
						luckyExcel = luckysheet;
					})
		})
	})
	$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/plugins/css/pluginsCss.css'));
	$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/plugins/plugins.css'));
	$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/css/luckysheet.css'));
	$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/luckysheet/assets/iconfont/iconfont.css'));

}

let luckyExcel = null

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





</script>
<style scoped>
/* 在样式表中使用媒体查询 */
@media (max-width: 768px) {
  /* 在小屏幕下的样式设置 */
  .dialog-footer {
    text-align: center;
  }
}
/*背景颜色*/
/*印件背景颜色变黄*/
:deep(.el-table__body .warning-row) {
  background: #FFFF80 !important;
}
/*修正工单核算参数背景*/
: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;
}
:deep(.statusy-plan-usage-low div) {
  color: #8c939d !important;
}
/* 在样式表中添加以下样式 */
.el-input__textarea {
  resize: none; /* 禁止调整大小 */
}
.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-textarea textarea {
  resize: none !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;
}
.el-pagination{
  margin-top: 0px !important;
}
/* .upload-demo .el-upload {  
  border: 1px dashed #d9d9d9;  
  border-radius: 6px;  
  cursor: pointer;  
  position: relative;  
  overflow: hidden;  
}  
.upload-demo .el-upload:hover {  
  border-color: #409EFF;  
}   */

.mab{
  margin-bottom: 5px;
}
::v-deep(.input_style .el-input__inner) {  
  font-size: 18px; 
}  
::v-deep(.el-form-item__label) {  
  font-size: 18px; 
}

</style>
