<template>
    <div>
      <layout>
          <el-row :gutter="24" style="margin-bottom: 6px;">
                <!-- <el-input v-model="records_searchInfo" placeholder="请搜索退还单号、订单编号或生产款号进行查询相关退还记录"  @input="records_handleInput"
                  @keyup.enter="records_onSubmit" id="searchInput"  style="width: 460px;height: 50px;margin-left: 10px;">
                </el-input> -->
                <el-button type="primary" @click="Reporting_onSubmit" style="height: 50px;font-size: 20px;margin-left: 20px;">面料退还</el-button>
                <!-- <el-button type="danger"  @click="deldetail_delclick" style="width: 80px;height: 50px;"	v-if="del_details=== true" :disabled="details_Selection === '' "  class="bt"   >删除</el-button> -->
          </el-row>
        <layout>
            
          <layout-content >
            <div class="gva-table-box">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="退还记录"  @click="showTable('退还记录')"  name="first">
                  <el-table ref="multipleTable"
                            :row-style="{ height: '30px' }" :header-cell-style="{ padding: '0px' }"
                            :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                            :show-overflow-tooltip="true" highlight-current-row="true"
                            @row-click="Recordclicks" @row-dblclick="Doubleclickrecord"
                            @selection-change="detailSelectionChange" style="width: 100%;height: 65vh" border
                            :summary-method="getSummaries" tooltip-effect="dark" :data="recordtableData" row-key="ID" >
                    <!-- <el-table-column   align="center" type="selection" width="40"//> -->
                    <el-table-column align="left"  label="退还单" prop="出库单"  width="170"/>
                    <!-- <el-table-column align="left"  label="订单编号" prop="订单编号"  width="150"/> -->
                    <!-- <el-table-column align="left"  label="款号" prop="款号"  width="150"/> -->
                    <!-- <el-table-column align="left"  label="物料名称" prop="物料名称"  width="150"/> -->
                    <el-table-column align="left"  label="单号类型" prop="单号类型"  width="150"/>
                    <el-table-column align="left"  label="退还总数" prop="总数"  width="110"/>
                    <el-table-column align="left"  label="退还人员" prop="操作机台"  width="110"/>
                    <el-table-column align="left"  label="退还日期" prop="日期"  width="160"/>
                    
                    <el-table-column fixed="right" label="操作" width="130">
                      <template #default="{ row, $index }">
                        <el-button @click="record_deleteRow(row,$index)" type="success" size="small" 
                        style="font-size: 16px;padding: 0px;width: 90px;">
                          退还明细
                        </el-button>
                      </template>
                    </el-table-column>
                    
                  </el-table>
                </el-tab-pane>
             </el-tabs>
              <div class="dialog-footer" style="text-align: left;margin-right: 60px;">
              </div>
            </div>
        </layout-content>
        </layout>
      </layout>
    </div>
    
    <!-- 明细数据 -->
    <el-dialog v-model="recorddialogFormVisible" :before-close="record_bomcloseDialog"  width="100%" style="height: 100%;margin: 0%;padding: 0px 10px 0px 10px;"  destroy-on-close>
        <el-button type="primary" @click="record_closeDialog"  style="width: 100px;height: 50px;margin-left: 10px;">关 闭</el-button>
        <div class="gva-table-box">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="退还明细"  name="first">
                <el-table ref="multipleTable"
                          :row-style="{ height: '30px' }" :header-cell-style="{ padding: '0px' }"
                          :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                          :show-overflow-tooltip="true" highlight-current-row="true"
                        @row-click="detailsclicks" @row-dblclick="Doubleclickdetails"
                        @selection-change="detailSelectionChange" style="width: 100%;height: 75vh" border
                          :summary-method="getSummaries" tooltip-effect="dark" :data="rdetailstableData" row-key="ID" >
                <!-- <el-table-column   align="center" type="selection" width="40"/> -->
                <el-table-column align="left"  label="退还单号" prop="出库单据编号"  width="140"/>
                <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="客户编号"  width="70"/>
                <el-table-column align="left"  label="生产款号" prop="款号"  width="140"/>
                <el-table-column align="left"  label="款式" prop="款式"  width="120"/>
                <el-table-column align="left"  label="物料编码" prop="物料编码"  width="150"/>
                <el-table-column align="left"  label="物料名称" prop="物料名称"  width="150"/>
                <el-table-column align="left"  label="颜色" prop="颜色"  width="120"/>
                <!-- <el-table-column align="left"  label="计划用料" prop="计划用料"  width="90"/> -->
                <!-- <el-table-column align="left"  label="计划门幅" prop="计划门幅"  width="90"/> -->
                <el-table-column align="left"  label="定额用料" prop="定额用料"  width="90"/>
                <el-table-column align="left"  label="定额门幅" prop="定额门幅"  width="90"/>
                <el-table-column align="left"  label="退还数量" prop="入仓总量"  width="90"/>
                <el-table-column align="left"  label="库存总量" prop="库存数量"  width="90"/>
                <el-table-column align="left"  label="面料结余" prop="面料结余"  width="90"/>
                <el-table-column align="left"  label="投料单位" prop="单位"  width="90"/>
                <el-table-column align="left"  label="退还人员" prop="操作机台"  width="100"/>
                <el-table-column align="left"  label="退还日期" prop="日期"  width="160"/>
                </el-table>
            </el-tab-pane>
           </el-tabs>
            <div class="dialog-footer" style="text-align: left;margin-right: 60px;">
          </div>
      </div>
    </el-dialog>
    
    <!-- 选择退还弹窗 -->
    <el-dialog v-model="res_bomdialogFormVisible" :before-close="res_bomcloseDialog" style="width: 100%;height: 100%;margin: 0px;padding: 0px;"  destroy-on-close>
      <div class="dialog-footer" style="margin: 0px;">
          <el-button type="primary" @click="res_bomcloseDialog"  style="width: 100px;height: 50px;margin-left: 10px;">关 闭</el-button>
          <el-button type="primary" @click="dj_Dialog"  style="width: 120px; height: 50px;">
            添加面料
          </el-button>
          <el-button type="primary"  @click="res_bomenterDialog"  style="width: 100px;height: 50px;">一键退还</el-button>
      </div>
  
       <el-divider style='margin: 10px 0px 10px 0px;'><span class="print-title" style="font-size: 18px;">面料退还明细</span></el-divider>
  
       <div style="display: flex; gap: 20px; align-items: center;">
          <!-- 左部分 -->
          <div style="">
              <el-input v-model="add_searchInfo" placeholder="请扫描订单编号或输入生产款号查询"  @input="handleInput"
                  @keyup.enter="add_onSubmit" id="details_searchInput"  style="width: 470px;height: 50px;margin-left: 10px;">
                </el-input>
              <el-table ref="multipleTable" style="width: 100%;height: 40vh" tooltip-effect="dark"
                        :row-style="{ height: '40px' }"  :header-cell-style="{ padding: '0px' }"
                        :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                        :data="restableData"  border row-key="ID" size="small"  
                        :cell-class-name="tableDataCellClass"
                        highlight-current-row="true"  @row-dblclick="updateCompanyFunc"
                        @row-click="tableRowClick" :show-overflow-tooltip="true"
                        @selection-change="handleSelectionChange">
                <el-table-column  align="left" label="关联编号" prop="关联编号" width="90" />
                <el-table-column  align="left" label="订单编号" prop="订单编号" width="110" />
                <el-table-column  align="left" label="生产款号" prop="生产款号" width="110" />
                <el-table-column  align="left" label="物料名称" prop="物料名称" width="120" />	 
                <el-table-column  align="left" label="颜色" prop="颜色" width="100" />
              </el-table>
          </div>
  
          <!-- 右部分 -->
          <div style="position: relative;width: 1300px;height: 310px;">
              <el-descriptions class="margin-top" :column="1" :size="size" border>
                  <el-descriptions-item label="关联订单">{{ mianliaotabData.关联订单 }}</el-descriptions-item>
              </el-descriptions>
            <el-descriptions class="margin-top" :column="4" :size="size" border>
              <el-descriptions-item label="批次号">{{ mianliaotabData.批次号 }}</el-descriptions-item>
              <el-descriptions-item label="关联号">{{ mianliaotabData.关联号 }}</el-descriptions-item>
              <el-descriptions-item label="订单编号">{{ mianliaotabData.订单编号 }}</el-descriptions-item>
              <el-descriptions-item label="客户">{{ mianliaotabData.客户编号 }}</el-descriptions-item>
              <!-- <el-descriptions-item label="款式">{{ ddhformData['ks'] }}</el-descriptions-item> -->
              <el-descriptions-item label="物料编号">{{ mianliaotabData.物料编号 }}</el-descriptions-item>
              <el-descriptions-item label="生产款号">{{ mianliaotabData.生产款号 }}</el-descriptions-item>
              <el-descriptions-item label="颜色">{{ mianliaotabData.颜色 }}</el-descriptions-item>
              <el-descriptions-item label="物料名称">{{ mianliaotabData.物料名称 }}</el-descriptions-item>
              <!-- <el-descriptions-item label="计划用料">{{ mianliaotabData.计划用料 }}</el-descriptions-item> -->
              <!-- <el-descriptions-item label="计划门幅">{{ mianliaotabData.计划门幅 }}</el-descriptions-item> -->
              <!-- <el-descriptions-item label="单位">{{ mianliaotabData.单位 }}</el-descriptions-item> -->
              <el-descriptions-item label="单位">{{ mianliaotabData.单位 }}</el-descriptions-item>
              <el-descriptions-item label="库存数量">{{ mianliaotabData.库存数量 }}</el-descriptions-item>
              <el-descriptions-item label="累计退还数量">{{ mianliaotabData.入仓总数量 }}</el-descriptions-item>
              <!-- <el-descriptions-item label="领用数量">{{ mianliaotabData.领用数量 }}</el-descriptions-item> -->
            </el-descriptions>
            
          <el-descriptions class="margin-top" :column="4" :size="size" border>
              <el-descriptions-item label="定额用料">{{ mianliaotabData.定额用料 }}</el-descriptions-item>
              <el-descriptions-item label="定额门幅">{{ mianliaotabData.定额门幅 }}</el-descriptions-item>
			  <el-descriptions-item label="实际门幅">{{ mianliaotabData.实际门幅 }}</el-descriptions-item>
            <!--  <el-descriptions-item label="实际门幅">
                <el-input v-model="mianliaotabData.实际门幅" placeholder="" style="margin: 0; width: 100px;"/>
              </el-descriptions-item> -->
              <el-descriptions-item label="退还数量">
                <el-input v-model="mianliaotabData.退还数量" id='rksl' placeholder="" style="margin: 0; width: 100px;"/>
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions class="margin-top" :column="2" :size="size" border>
            <el-descriptions-item label="退还类型">
                <el-radio v-model="radio1" label="退面料" border>退面料</el-radio>
                <el-radio v-model="radio1" label="退厂商" border>退厂商</el-radio>
                <el-radio v-model="radio1" label="退次品" border>退次品</el-radio>
              </el-descriptions-item>
          </el-descriptions>
          <!-- <el-button type="primary" @click="dj_Dialog" style="width: 120px; height: 50px; position: absolute; bottom: 0px; right: 10px;">
            添加面料
          </el-button> -->
          </div>
      </div>
          <el-divider><span class="print-title" style="font-size: 18px;">面料退还单</span></el-divider>
          <el-descriptions class="margin-top" :column="3"  :size="size" border>
              <el-descriptions-item label="退还单号">{{danhao}}</el-descriptions-item>
              <el-descriptions-item label="退还日期">{{riqi}}</el-descriptions-item>
              <el-descriptions-item label="退还人员">{{chukuren}}</el-descriptions-item>
          </el-descriptions>
          <br>
            <div>
              <el-table ref="multipleTable" style="width: 100%;height: 25vh" tooltip-effect="dark"
                        :row-style="{ height: '40px' }"  :header-cell-style="{ padding: '0px' }"
                        :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                        :data="danjutableData"  border row-key="ID" size="small"  
                        :cell-class-name="danju_tableDataCellClass"
                        highlight-current-row="true"  :show-overflow-tooltip="true">
                      <!-- <el-table-column type="selection" width="80" /> -->
                  <el-table-column  align="left" label="批次号" prop="批次号" width="90"/>
                  <el-table-column  align="left" label="关联号" prop="关联号" width="90"/>
                  <el-table-column  align="left" label="物料编号" prop="物料编号" width="160" />	 
                  <el-table-column  align="left" label="物料名称" prop="物料名称" width="130" />
                  <el-table-column  align="left" label="颜色" prop="颜色" width="90"/>
                  <!-- <el-table-column  align="left" label="计划用料" prop="计划用料" width="90"/> -->
                  <!-- <el-table-column  align="left" label="计划门幅" prop="计划门幅" width="90" />	 -->
                  <el-table-column  align="left" label="定额用料" prop="定额用料" width="90" />	 
                  <el-table-column  align="left" label="定额门幅" prop="定额门幅" width="90" />
                  <!-- <el-table-column  align="left" label="实际门幅" prop="实际门幅" width="90"/> -->
                  <el-table-column  align="left" label="退还数量" prop="退还数量" width="90"/>
				  <el-table-column  align="left" label="退还类型" prop="退还类型" width="90"/>
                  <!-- <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="90"/> -->
                  <el-table-column  align="left" label="单位" prop="单位" width="60"/>
                  <el-table-column  align="left" label="关联订单" prop="关联订单" width="300"/>
                  <el-table-column fixed="right" label="操作" width="120">
                      <template #default="{ row, $index }">
                        <el-button @click="deleteRow($index)" type="text" size="small">
                          移除
                        </el-button>
                      </template>
                    </el-table-column>
              </el-table>
          <br>
          <br>
        </div>
    </el-dialog>
    
  
    <!--单号详情记录 -->
    <el-dialog v-model="details_pickingaddvisible" :before-close="()=> details_pickingaddvisible = false" style="width: 100%; margin: 0% auto; height: 100%;" :title="单据详情"
      destroy-on-close>
         <div class="dialog-footer" style="bottom: 10px; right: 10px; width: 100%;">
           <el-button  type="primary" @click="details_ckth_closeDialog" style="width: 80px;height: 40px;">关 闭</el-button>
         </div>
         <br>
          <div>
              <el-table ref="multipleTable"
                        :row-style="{ height: '30px' }" :header-cell-style="{ padding: '0px' }"
                        :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                        :show-overflow-tooltip="true" highlight-current-row="true"
                        @row-click="tableclick" @row-dblclick="ysupdateCompanyFunc"
                        @selection-change="detailSelectionChange" style="width: 100%;height: 65vh" border
                        :summary-method="getSummaries" tooltip-effect="dark" :data="ruku_detailstableData" row-key="ID" >
                <el-table-column   align="center" type="selection" width="40"/>
                <el-table-column align="left"  label="订单编号" prop="订单编号"  width="110"/>
                <el-table-column align="left"  label="生产款号" prop="生产款号"  width="140"/>
                <el-table-column align="left"  label="物料名称" prop="物料名称"  width="140"/>
                <el-table-column align="left"  label="计划用料" prop="计划用料"  width="100"/>
                <el-table-column align="left"  label="定额用料" prop="定额用料"  width="100"/>
                <el-table-column align="left"  label="计划门幅" prop="计划门幅"  width="100"/>
                <el-table-column align="left"  label="定额门幅" prop="定额门幅"  width="100"/>
                <el-table-column align="left"  label="裁床实际用料" prop="裁床实际用料"  width="110"/>
                <el-table-column align="left"  label="裁床领用面料" prop="裁床领用面料"  width="110"/>
                <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="面料结余"  width="100"/>
                <el-table-column align="left"  label="退还数量" prop="退还数量"  width="100"/>
                <el-table-column align="left"  label="投料单位" prop="投料单位"  width="90"/>
                <el-table-column align="left"  label="退还人员" prop="退还人员"  width="120"/>
                <el-table-column align="left"  label="退还时间" prop="退还时间"  width="160"/>
                <el-table-column align="left"  label="款式" prop="款式"  width="140"/>
                <el-table-column align="left"  label="客户" prop="客户编号"  width="80"/>
              </el-table>
          </div>
    </el-dialog>
    
  </template>
  <script>
  //点击按钮显示下方表格
  export default {
    data() {
      return {
        currentTable: '', // 当前展示的表格
        activeName: 'first',
        _ddhval:'',
        add_gddialogFormVisible: true,
      };
    },
    methods: {
      
    }
  };
  </script>
  <script setup>
  // 全量引入格式化工具 请按需保留
  import { Layout, LayoutSider, LayoutContent } from '@arco-design/web-vue';
  import {ref, reactive} from 'vue'
  import {getInputDetail,
  TuihuoReport,
  OutOrderSearch,outReport,FabricDetail,gitReceiptNumber,FabricDetaillist,FabricDetaildel,ReceiptList,ReceiptDetail} from '@/api/mes/job'
  import { ElMessage, ElMessageBox,ElUpload, ElButton } from 'element-plus';
  import { useUserStore } from '@/pinia/modules/user'
  // import { get } from 'scriptjs';
  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}`;
  //自动聚焦光标input
  // const getMachineMacdata = async () => {
  // 	setTimeout(() => {
  // 		const inputElement = document.getElementById('searchInput');
  // 		if (inputElement) {
  // 			inputElement.focus();		
  // 		}
  // 	}, 100); // 延迟100毫秒
  // }
  // getMachineMacdata();
  
  //全局调用参数
  const danhao = ref('')
  const riqi = ref('')
  const chukuren = ref('')
  const add_searchInfo = ref('')//搜索
  const records_searchInfo = ref('')//历史记录搜索
  const add_lysearchInfo = ref('')//搜索
  const restableData = reactive([])//表格
  const _orderid = ref('')//订单子编号
  const _kh = ref('')//生产款号
  const radio1 = ref('退面料')

  //input实时调用
  const handleInput = async ()=>{
      restableData.splice(0, restableData.length);//清空表格
      //订单信息数据查询【接口】
      const orderSearchdata = await OutOrderSearch({search:add_searchInfo.value});
      if(orderSearchdata.data.length === 1){
          _orderid.value = orderSearchdata.data[0]['订单编号']
          add_searchInfo.value = orderSearchdata.data[0]['订单编号']
          ddhformData.ddh = orderSearchdata.data[0]['订单编号']
          ddhformData.kh = orderSearchdata.data[0]['客户编号']
          ddhformData.sckh = orderSearchdata.data[0]['生产款号']
          ddhformData.ks = orderSearchdata.data[0]['款式']
          add_lysearchInfo.value = add_searchInfo.value
          
          const gitReceiptNumberdata = await gitReceiptNumber({number:'TH'});
          danhao.value = gitReceiptNumberdata.data.number
          chukuren.value = userStore.userInfo.nickName
          riqi.value = currentDates 
      }else{
          restableData.splice(0,orderSearchdata.length,...orderSearchdata.data);
      }
  }
  
  //input回车事件
  const add_onSubmit = async ()=>{
      //清空表格
      restableData.splice(0, restableData.length);
      const orderSearchdata = await OutOrderSearch({search:add_searchInfo.value});
      if(orderSearchdata.data.length === 1){
          res_bomdialogFormVisible.value = true
          _orderid.value = orderSearchdata.data[0]['订单编号']
          add_searchInfo.value = orderSearchdata.data[0]['订单编号']
          ddhformData.ddh = orderSearchdata.data[0]['订单编号']
          ddhformData.kh = orderSearchdata.data[0]['客户编号']
          ddhformData.sckh = orderSearchdata.data[0]['生产款号']
          ddhformData.ks = orderSearchdata.data[0]['款式']
          add_lysearchInfo.value = add_searchInfo.value
          
          const gitReceiptNumberdata = await gitReceiptNumber({number:'TH'});
          console.log(gitReceiptNumberdata)
          danhao.value = gitReceiptNumberdata.data.number
          chukuren.value = userStore.userInfo.nickName
          riqi.value = currentDates
      }else{
          restableData.splice(0,orderSearchdata.length,...orderSearchdata.data);
      }
  };
  
  
  const mianliaotabData = ref({
      物料编号: '',
      物料名称: '',
      关联号: '',
      批次号: '',
      计划用料: '',
      计划门幅: '',
      定额用料: '',
      定额门幅: '',
      退还数量: '',
      入仓总数量: '',
      库存数量: '',
      领用数量: '',
      关联订单: '',
      颜色: '',
      单位: ''
  });
  
  //表格行点击
  const tableRowClick = async (row) => {
      setTimeout(() => {
            const inputElement = document.getElementById('rksl');
            if (inputElement) {
                inputElement.focus();		
            }
      }, 100);//100毫秒
      
      add_searchInfo.value = row.订单编号;
      _orderid.value = row.订单编号;
      _kh.value = row.生产款号;
  
      ddhformData.glbh = row['关联编号'];
      ddhformData.ddh = row['订单编号'];
      ddhformData.kh = row['客户编号'];
      ddhformData.sckh = row['生产款号'];
      ddhformData.wlbh = row['物料编码'];
      ddhformData.ks = row['款式'];
  
      // 获取详情数据
      const Detailres = await getInputDetail({
          关联编号: row.关联编号,
          订单编号: row.订单编号,
          物料编码: row.物料编码
      });
  
      console.log(Detailres);
  
      // 将 Detailres.data 中的数据赋值给 mianliaotabData
      if (Detailres.code === 0 && Detailres.data) {
          mianliaotabData.value = {
              订单编号: row.订单编号,
              客户编号: row.客户编号,
              生产款号: row.生产款号,
              款式: row.款式,
              物料编号: Detailres.data.BOM_物料编码,
              物料名称: Detailres.data.BOM_物料名称,
              关联号: Detailres.data.关联编号,
              批次号: Detailres.data.批次号,
              计划用料: Detailres.data.计划用料,
              计划门幅: Detailres.data.BOM_计划门幅,
              定额用料: Detailres.data.定额用料,
              定额门幅: Detailres.data.BOM_定额门幅,
              退还数量: Detailres.data.退还数量,
              入仓总数量: Detailres.data.退还数量?Detailres.data.退还数量:0,
              库存数量: Detailres.data.库存数量?Detailres.data.库存数量:0,
              领用数量: Detailres.data.领用数量,
              关联订单: Detailres.data.关联订单,
              颜色: Detailres.data.BOM_颜色,
              单位:'米',
              实际门幅:Detailres.data.实际门幅
          };
           // 计算 danjutableData 中相同物料名称和颜色的退还数量总和
			const { 物料名称, 颜色 } = mianliaotabData.value;
			
			// 计算退还的总数量
			const totalOutbound = danjutableData.value
			  .filter((item) => item.物料名称 === 物料名称 && item.颜色 === 颜色)
			  .reduce((sum, item) => sum + Number(item.退还数量), 0);
			
			// 根据退还类型更新库存数量
			if (danjutableData.value.退还类型 === '退面料') {
			  // 退面料，增加库存数量
			  mianliaotabData.value.库存数量 += totalOutbound;
			} else if (danjutableData.value.退还类型 === '退厂商') {
			  // 退厂商，减少库存数量
			  mianliaotabData.value.库存数量 -= totalOutbound;
			} else {
			  // 其他退还类型可以根据需要加入处理逻辑
			  console.log('未知的退还类型');
			}
			  // mianliaotabData.value.库存数量 -= totalOutbound;
      } else {
          console.error('获取详情数据失败:', Detailres.msg);
      }
  };
  
  
const danjutableData = ref([]); // 使用 ref 定义响应式数组
  
//添加按钮
const dj_Dialog = () => {
  // 确保 mianliaotabData 和 mianliaotabData.value 存在
  if (!mianliaotabData || !mianliaotabData.value) {
    console.error('mianliaotabData 为空，无法添加到 danjutableData');
    return;
  }

  // 检查退还数量是否为空或无效
  if (
    mianliaotabData.value.退还数量 === '' ||
    mianliaotabData.value.退还数量 === undefined ||
    mianliaotabData.value.退还数量 === '0'
  ) {
    ElMessage({ type: 'warning', message: '请填写退还数量' });
    return;
  }

  // 获取 mianliaotabData 的物料名称和颜色
  const { 物料名称, 颜色, 退还数量, 库存数量 } = mianliaotabData.value;

  // 计算 danjutableData 中相同物料名称和颜色的退还数量总和
  const totalOutbound = danjutableData.value
    .filter(
      (item) =>
        item.物料名称 === 物料名称 && item.颜色 === 颜色
    )
    .reduce((sum, item) => sum + Number(item.退还数量), 0);

  // 计算总退还数量（danjutableData 中的总和 + mianliaotabData 中的退还数量）
  const totalOutboundQuantity = totalOutbound + Number(退还数量);

  // 判断总退还数量是否大于库存数量
  if (totalOutboundQuantity > 库存数量) {
    ElMessage({ type: 'warning', message: '退还数量不能大于库存数量' });
    return;
  }

  // 如果通过检查，将数据添加到 danjutableData
  danjutableData.value.push({
    ...mianliaotabData.value,
    实际门幅: mianliaotabData.value.实际门幅 || mianliaotabData.value.定额门幅,
	退还类型:radio1.value
  });
  mianliaotabData.value.退还数量 = '';
  if(radio1.value === '退面料'){
	  // 更新 mianliaotabData 的库存数量
	 mianliaotabData.value.库存数量 = mianliaotabData.value.库存数量 + Number(退还数量);
  }else if(radio1.value === '退厂商'){
	  // 更新 mianliaotabData 的库存数量
	 mianliaotabData.value.库存数量 = mianliaotabData.value.库存数量 - Number(退还数量);
  }
  // mianliaotabData.value.库存数量 = mianliaotabData.value.库存数量 - Number(退还数量);
};
  
  //操作移除按钮
  const deleteRow = (index) => {
      //当前点击索引值
      console.log(index)
      //移除当前行
      danjutableData.value.splice(index, 1);
  }
  
  //选择退还弹窗
  const res_bomdialogFormVisible = ref(false)
  const resbomtableData = ref([]);
  const ddhformData = reactive({
    glbh: '',
    ddh: '',
    kh:'',
    sckh:'',
    ks:'',
    wlbh:'',
  });
  const resbom_tableColumns = ref(
      [
            { label: '物料编号', prop: '物料编号', width: '160' },
			{ label: '物料名称', prop: '物料名称', width: '100' },
            { label: '计划用料', prop: '计划用料', width: '90' },
            { label: '计划门幅', prop: 'BOM_计划门幅', width: '90' },
            { label: '定额用料', prop: '定额用料', width: '90' },
            { label: '定额门幅', prop: 'BOM_定额门幅', width: '90' },
            { label: '实际门幅', prop: '实际门幅', width: '100' },
            { label: '退还数量', prop: '退还数量', width: '90' },
            { label: '入仓总数量', prop: '入仓总量', width: '100' },
            { label: '库存数量', prop: '库存数量', width: '90' },
            { label: '领用数量', prop: '领用数量', width: '100' },
            { label: '批次号', prop: '批次号', width: '80' },
            { label: '关联号', prop: '关联号', width: '80' },
            { label: '颜色', prop: 'BOM_颜色', width: '100' },
            { label: '关联订单', prop: '关联订单', width: '160' },
            { label: '单位', prop: '单位', width: '90' },
      ]
  )
  
  //选择退还
  const Reporting_onSubmit = async ()=>{
      ddhformData.value = []
      mianliaotabData.value = []	
      // if(_orderid.value === '' || _orderid.value === null){
      // 	ElMessage({type: 'warning',message: '请扫描订单后，再操作此功能'})
      // }else{
          //打开选择退还弹窗
          res_bomdialogFormVisible.value = true
          
          setTimeout(() => {
                const inputElement = document.getElementById('details_searchInput');
                if (inputElement) {
                    inputElement.focus();		
                }
          }, 100);//100毫秒
          
          //获取单据编号接口
          const gitReceiptNumberdata = await gitReceiptNumber({number:'TH'});
          danhao.value = gitReceiptNumberdata.data.number
          chukuren.value = userStore.userInfo.nickName
          riqi.value = currentDates
          _TestCoefficient();
      // }
  }
  //调用接口【获取退还面料信息】
  const _TestCoefficient = async () => {
    try {
      const Detailres = await getInputDetail({
        关联编号: ddhformData.glbh,
        订单编号: ddhformData.ddh,
        物料编码: ddhformData.wlbh
      });
      console.log(Detailres);
  
      // 如果接口返回的data是单条数据（对象），可以直接赋值
      if (Detailres.code === 0 && Detailres.data) {
        resbomtableData.value = [Detailres.data];  // 将单条数据包装为数组，便于表格渲染
      }
    } catch (error) {
      console.error(error);
    }
  }
  
  const resbom_handleKeyDown = (event, x, y, prop) => {
    const currentElement = document.getElementById(`input${x}${y}`);
    if (currentElement === null && currentElement === undefined) return
    let move = 0
    switch (event.keyCode) {
      case 13: // Enter
      case 40: // 向下箭头
        if (y < resbomtableData.value.length )
          document.getElementById(`input${x}${y + 1}`).focus();
        break;
      case 38: // 向上箭头
        if ( y > 0) {
          document.getElementById(`input${x}${y - 1}`).focus();
        }
        break;
      case 39: // 向左箭头
        if (x >= 0 && x <=6) {
          move = x + 1
        }
        document.getElementById(`input${move}${y}`).focus();
        break;
      case 37: // 向右箭头
        if (x = 0  && x <=6) {
          move = x - 1
        }
        document.getElementById(`input${move}${y}`).focus();
        break;
      default:
        break;
    }
  }
  const scfjfpxsCellClass = ({row, column, rowIndex, columnIndex}) =>{
    if (column.label === '退还数量' ||column.label === '实际门幅') {
      return 'background-plan-usage-low';
    }
  }
  
  // 确定
  const res_bomenterDialog = async () => {
      console.log(danjutableData);
      if(danjutableData.value[0]['退还数量'] === ''|| danjutableData.value[0]['退还数量'] === undefined){
          ElMessage({type: 'warning',message: '退还数量不能为空'})
          return
      }
   // 构造一个包含所有数据的数组
   const formattedDataArray = danjutableData.value.map(item => ({
      order_id: ddhformData.ddh,
      款号: ddhformData.sckh,
      物料编码: item['物料编号'],
      物料名称: item['物料名称'],
      number: item['退还数量'],
      name: "退还",
      sys_id: userStore.userInfo.nickName,
      receipt_number: danhao.value,
      客户编号: ddhformData.kh,
      款式: ddhformData.ks,
      rq: currentDate,
      批次号: item['批次号'],
      关联编号: item['关联号'],
      // 实际门幅: item['实际门幅'],
      type: radio1.value,
    }));
    console.log(formattedDataArray);
    try {
      // 异步调用输入数据的接口
      const add_TuihuoReport = await TuihuoReport(formattedDataArray);
      // 根据返回的 code 进行提示
      if (add_TuihuoReport.code === 0) {
        res_bomdialogFormVisible.value = false;
        ElMessage({ type: 'success', message: '退还成功' });
        danjutableData.value.splice(0, danjutableData.value.length); // 清空表格数据
        records_onSubmit();
      } else {
        ElMessage({ type: 'error', message: '退还失败' });
      }
    } catch (error) {
      console.error('出库失败:', error);
      ElMessage({ type: 'error', message: '退还失败' });
    }
  }
  
  // 取消
  const res_bomcloseDialog = () => {
      _orderid.value =  '';
      add_searchInfo.value = '';
      restableData.splice(0, restableData.length);
      res_bomdialogFormVisible.value = false;
      //自动获取光标
      getMachineMacdata();
  }
  // 输入框只能输入数字和小数点
  const handleInput2 = (value, row, prop) => {
      if(prop != "物料名称" && prop != "备注" ){
          // 使用正则表达式过滤非数字和小数点的字符
          let filteredValue = value.replace(/[^\d.]/g, '');
          // 不允许以 . 开头
          if (filteredValue.startsWith('.')) {
          filteredValue = filteredValue.slice(1); // 去掉开头的 .
          }
          // 确保只有一个小数点
          const parts = filteredValue.split('.');
          if (parts.length > 2) {
          // 如果超过一个小数点，只保留第一个
          row[prop] = `${parts[0]}.${parts.slice(1).join('')}`;
          } else {
          // 否则直接赋值
          row[prop] = filteredValue;
          }
      }
  };
  
  //表格
  const recordtableData = reactive([])
  const records_onSubmit = async () => {
    // 清空数组
    recordtableData.splice(0, recordtableData.length);
    // 获取退还单数据
    const ReceiptList_res = await ReceiptList({ mouth: '', search: '', page: 1, limit: 50 });
    if (ReceiptList_res && ReceiptList_res.data && Array.isArray(ReceiptList_res.data.table)) {
      const filteredData = ReceiptList_res.data.table.filter(item => item.单号类型 === '退还');
      // 更新数据
      recordtableData.splice(0, 0, ...filteredData);
    } else {
      console.error("数据获取失败");
    }
  };
  records_onSubmit();
  
  
  const recorddialogFormVisible = ref(false)
  const rdetailstableData = reactive([])
  //查看明细
  const record_deleteRow = async (row) => {
      console.log(row)
      recorddialogFormVisible.value = true
      rdetailstableData.splice(0,rdetailstableData.length);
      
      const FabricDetaillists = await ReceiptDetail({receipt:row['出库单']});
      rdetailstableData.splice(0,FabricDetaillists.length,...FabricDetaillists.data);
  }
  
  
  const record_closeDialog = async (row) => {
      console.log(row)
      recorddialogFormVisible.value = false
  }
  
  
  
  
  
  
  
  const details_pickingaddvisible = ref(false)
  const ruku_detailstableData = reactive([])
  const rukuupdateCompanyFunc = async (row)=>{
      details_pickingaddvisible.value = true
      ruku_detailstableData.splice(0,ruku_detailstableData.length);
      const FabricDetaillistdata = await FabricDetaillist({order:row.订单编号});
      ruku_detailstableData.splice(0,FabricDetaillistdata.length,...FabricDetaillistdata.data['退还记录']);
      console.log(FabricDetaillistdata)
  }
  const thupdateCompanyFunc = async (row)=>{
      dh.value = row.单号
      type.value = 'th'
      details_pickingaddvisible.value = true
      console.log(row)
      const FabricDetaillistdata = await FabricDetaillist({order:row.单号,search:'退还'});
      console.log(FabricDetaillistdata)
  }
  //详情页取消
  const details_ckth_closeDialog = async ()=>{
      details_pickingaddvisible.value = false
      //自动聚焦光标input
      getMachineMacdata();
  }
  
  //表格复选框
  const del_details = ref(true)//删除BOM资料
  const details_Selection = ref('')//存储选中Uniqid
  const detailSelectionChange = (selection, type) => {
    const ids = selection.map(item => {
      return item.id
    })
    details_Selection.value = ids.join(',')
    console.log("复选框",details_Selection.value)
  }
  
  // // 删除详情按钮
  // const deldetail_delclick = async () => {
  //   try {
  //     // 弹出确认框
  //     await ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     });
  //     // 用户点击“确定”后执行以下逻辑
  //     const params = {
  // 		id: details_Selection._value,
  // 		Mod_id: userStore.userInfo.nickName,
  //     };
  //     console.log('删除参数:', params);
  //     // 调用删除接口
  //     const res1 = await FabricDetaildel(params);
  //     if (res1.code === 0) {
  //       ElMessage.success('删除成功');
  //     } else {
  //       ElMessage.error('删除失败');
  //       return; // 如果删除失败，直接返回
  //     }
  //     // 重新获取BOM列表数据
  // 	rukutableData.splice(0,ruku_detailstableData.length);
  // 	const FabricDetaillists = await FabricDetaillist({order:records_searchInfo.value});
  // 	rukutableData.splice(0,FabricDetaillists.length,...FabricDetaillists.data['退还记录']);
  //   } catch (error) {
  //     // 用户点击“取消”或弹框关闭
  //     console.log('用户取消删除操作');
  //   }
  // };
  // =========== 分页 ===========
  // 分页相关的响应式变量
  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>
  /* 根据出库状态文字颜色 */
  :deep(.status-plan-usage-low div) {
    color: #8c939d  !important;
  }
  :deep(.statusy-plan-usage-low div) {
    color: blue !important;
  }
  .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;
    }
  }
  .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;
  }
  /* 表格复选框大小调整 */
  :deep(.el-checkbox.el-checkbox--small .el-checkbox__inner) {
      width: 45px; /* 复选框宽度 */
      height: 23px; /* 复选框高度 */
  }
  /*bom参数背景*/
  :deep(.el-table__body .background-plan-usage-low div div div) {
    background: #80FA80 !important;
  }
  /* 选中某行时的背景色 */
  :deep(.el-table__body tr.current-row) > td {
    background: #ff80ff !important;
  }
  :deep(.el-checkbox.el-checkbox--small.is-checked .el-checkbox__inner::after) {
      transform: scale(1.2) rotate(45deg); /* 调整选中后的对勾大小 */
      top: 5%; /* 调整对勾位置 */
      left: 40%; /* 调整对勾位置 */
      width: 5px; /* 调整对勾宽度 */
      height: 9px; /* 调整对勾高度 */
  }
  /* 选中某行时的背景色 */
  :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: 5px !important;
  }
  .mab{
    margin-bottom: 5px;
  }
  /* 搜索样式 */
  ::v-deep .el-input__wrapper #searchInput {  
    font-size: 16px; 
  }  
  ::v-deep(.el-descriptions__table tbody tr .is-bordered-label){
      width: 60px;
  }
  ::v-deep(.el-descriptions__table tbody tr .el-descriptions__content){
      width: 120px;
  }
  :deep(.el-descriptions__content) {
    width: 120px !important;
    min-width: 120px !important;
    max-width: 120px !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
  }
  </style>
  