<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">


      <el-form-item label="送货单" prop="poNo">
        <el-input
          v-model="queryParams.poNo"
          placeholder="请输入仓库"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购单" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入仓库"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

			<el-form-item label="仓库" prop="whCode">
				<el-input
					v-model="queryParams.whCode"
					placeholder="请输入仓库"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="库区" prop="waCode">
				<el-input
					v-model="queryParams.waCode"
					placeholder="请输入库区"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
<!--			<el-form-item label="库位" prop="wlCode">-->
<!--				<el-input-->
<!--					v-model="queryParams.wlCode"-->
<!--					placeholder="请输入库位"-->
<!--					clearable-->
<!--					@keyup.enter.native="handleQuery"-->
<!--				/>-->
<!--			</el-form-item>-->

			<el-form-item label="物料号" prop="materialCode">
				<el-input
					v-model="queryParams.materialCode"
					placeholder="请输入物料号"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="物料描述" prop="materialDesc">
				<el-input
					v-model="queryParams.materialDesc"
					placeholder="请输入物料描述"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>

<!--			<el-form-item label="数量" prop="amount">-->
<!--				<el-input-->
<!--					v-model="queryParams.amount"-->
<!--					placeholder="请输入数量"-->
<!--					clearable-->
<!--					@keyup.enter.native="handleQuery"-->
<!--				/>-->
<!--			</el-form-item>-->




			<el-form-item label="送货时间" prop="gmtCreate">
				<el-date-picker clearable
					v-model="queryParams.gmtCreate"
					type="date"
					value-format="yyyy-MM-dd"
					placeholder="请选择创建时间">
				</el-date-picker>
			</el-form-item>
<!--			<el-form-item label="工厂号" prop="factoryCode">-->
<!--				<el-input-->
<!--					v-model="queryParams.factoryCode"-->
<!--					placeholder="请输入工厂号"-->
<!--					clearable-->
<!--					@keyup.enter.native="handleQuery"-->
<!--				/>-->
<!--			</el-form-item>-->

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate">打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['wms:outorder:add']">补打</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-remove"
          size="mini"
          :disabled="batchSingle"
          @click="handleRemoveBatch(row)"
          v-hasPermi="['mes:pro:workorder:edit']"
        >删除
        </el-button>
      </el-col>

			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="matetowsnList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="唯一序列号" align="center" prop="mateOrderInSnId"  v-if="false" />
      <el-table-column label="送货时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="送货单" align="center" prop="poNo"  width="100"/>
      <el-table-column label="采购单" align="center" prop="orderNo" width="100"/>
			<el-table-column label="标识卡" align="center" prop="wlCode" width="300"/>
      <el-table-column label="物料号" align="center" prop="materialCode" width="200">
        <template slot-scope="scope">
          <span>{{ formatProductCode(scope.row.materialCode) }}</span>
        </template>
      </el-table-column>
			<el-table-column label="物料描述" align="center" prop="materialDesc" width="300"/>
      <el-table-column label="入库数量" align="center" prop="amount" />
      <el-table-column label="出库数量" align="center" prop="outNumber" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.outNumber === 0 || scope.row.outNumber === null">入库</span>
          <span v-else-if="scope.row.amount - scope.row.outNumber > 0 && (scope.row.outNumber !== 0 && scope.row.outNumber !== null)">部分出库</span>
          <span v-else>出库完成</span>
        </template>
      </el-table-column>
<!--			<el-table-column label="托盘号" align="center" prop="sn" />-->
      <el-table-column label="仓库" align="center" prop="whCode" />
      <el-table-column label="库区" align="center" prop="waCode" />
			<el-table-column label="备用1" align="center" prop="userDefined1" v-if="false" />
			<el-table-column label="备用2" align="center" prop="userDefined2"  v-if="false" />
			<el-table-column label="备用3" align="center" prop="userDefined3"  v-if="false" />
			<el-table-column label="备用4" align="center" prop="userDefined4"  v-if="false" />
			<el-table-column label="备用5" align="center" prop="userDefined5"  v-if="false" />
			<el-table-column label="备用6" align="center" prop="userDefined6"  v-if="false" />
			<el-table-column label="备用7" align="center" prop="userDefined7"  v-if="false" />
			<el-table-column label="备用8" align="center" prop="userDefined8"  v-if="false" />
			<el-table-column label="备用9" align="center" prop="userDefined9"  v-if="false" />
			<el-table-column label="备用10" align="center" prop="userDefined10"  v-if="false" />
			<el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
<!--			<el-table-column label="更新人" align="center" prop="lastModifiedBy" />-->
<!--			<el-table-column label="更新时间" align="center" prop="gmtModified" width="180">-->
<!--				<template slot-scope="scope">-->
<!--					<span>{{ parseTime(scope.row.gmtModified, '{y}-{m}-{d}') }}</span>-->
<!--				</template>-->
<!--			</el-table-column>-->
			<el-table-column label="有效标记" align="center" prop="activeFlag"v-if="false" />
			<el-table-column label="工厂号" align="center" prop="factoryCode" />

		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

<!--		&lt;!&ndash; 添加或修改包材库存明细表对话框 &ndash;&gt;-->
<!--		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--			<el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--				<el-form-item label="仓库编码" prop="whCode">-->
<!--					<el-input v-model="form.whCode" placeholder="请输入仓库编码" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="库区编码" prop="waCode">-->
<!--					<el-input v-model="form.waCode" placeholder="请输入库区编码" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="标识卡" prop="wlCode">-->
<!--					<el-input v-model="form.wlCode" placeholder="请输入标识卡" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="入库单号" prop="orderNo">-->
<!--					<el-input v-model="form.orderNo" placeholder="请输入入库单号" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="采购订单号" prop="poNo">-->
<!--					<el-input v-model="form.poNo" placeholder="请输入采购订单号" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="采购订单行项目" prop="poLine">-->
<!--					<el-input v-model="form.poLine" placeholder="请输入采购订单行项目" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="物料号" prop="materialCode">-->
<!--					<el-input v-model="form.materialCode" placeholder="请输入物料号" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="物料描述" prop="materialDesc">-->
<!--					<el-input v-model="form.materialDesc" placeholder="请输入物料描述" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="托盘号" prop="sn">-->
<!--					<el-input v-model="form.sn" placeholder="请输入托盘号" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="条码" prop="barCode">-->
<!--					<el-input v-model="form.barCode" placeholder="请输入条码" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="数量" prop="amount">-->
<!--					<el-input v-model="form.amount" placeholder="请输入数量" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用1" prop="userDefined1">-->
<!--					<el-input v-model="form.userDefined1" placeholder="请输入备用1" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用2" prop="userDefined2">-->
<!--					<el-input v-model="form.userDefined2" placeholder="请输入备用2" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用3" prop="userDefined3">-->
<!--					<el-input v-model="form.userDefined3" placeholder="请输入备用3" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用4" prop="userDefined4">-->
<!--					<el-input v-model="form.userDefined4" placeholder="请输入备用4" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用5" prop="userDefined5">-->
<!--					<el-input v-model="form.userDefined5" placeholder="请输入备用5" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用6" prop="userDefined6">-->
<!--					<el-input v-model="form.userDefined6" placeholder="请输入备用6" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用7" prop="userDefined7">-->
<!--					<el-input v-model="form.userDefined7" placeholder="请输入备用7" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用8" prop="userDefined8">-->
<!--					<el-input v-model="form.userDefined8" placeholder="请输入备用8" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用9" prop="userDefined9">-->
<!--					<el-input v-model="form.userDefined9" placeholder="请输入备用9" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="备用10" prop="userDefined10">-->
<!--					<el-input v-model="form.userDefined10" placeholder="请输入备用10" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="创建时间" prop="gmtCreate">-->
<!--					<el-date-picker clearable-->
<!--						v-model="form.gmtCreate"-->
<!--						type="date"-->
<!--						value-format="yyyy-MM-dd"-->
<!--						placeholder="请选择创建时间">-->
<!--					</el-date-picker>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="最后更新人" prop="lastModifiedBy">-->
<!--					<el-input v-model="form.lastModifiedBy" placeholder="请输入最后更新人" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="最后更新时间" prop="gmtModified">-->
<!--					<el-date-picker clearable-->
<!--						v-model="form.gmtModified"-->
<!--						type="date"-->
<!--						value-format="yyyy-MM-dd"-->
<!--						placeholder="请选择最后更新时间">-->
<!--					</el-date-picker>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="有效标记" prop="activeFlag">-->
<!--					<el-input v-model="form.activeFlag" placeholder="请输入有效标记" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="工厂号" prop="factoryCode">-->
<!--					<el-input v-model="form.factoryCode" placeholder="请输入工厂号" />-->
<!--				</el-form-item>-->
<!--				<el-form-item label="SAP工厂号" prop="sapFactoryCode">-->
<!--					<el-input v-model="form.sapFactoryCode" placeholder="请输入SAP工厂号" />-->
<!--				</el-form-item>-->
<!--			</el-form>-->
<!--			<div slot="footer" class="dialog-footer">-->
<!--				<el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--				<el-button @click="cancel">取 消</el-button>-->
<!--			</div>-->
<!--		</el-dialog>-->












    <!-- 生成出库单弹窗-->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form :model="queryParams1" label-width="120px">
        <!-- 表单内容 -->
        <el-row :gutter="10" class="mb8">

          <el-col :span="6">
            <el-form-item label="仓库编码">
              <el-select v-model="queryParams1.warehouseNo" placeholder="请选择仓库编码" @change="forceUpdate()" clearable
                         filterable style="width: 100%;">
                <el-option v-for="item in Optionlistck" :key="item.warehouseCode" :label="item.warehouseName"
                           :value="item.warehouseCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="6">
            <el-form-item label="库区">
              <el-input v-model="queryParams1.waCode" placeholder="库区"></el-input>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handlequeryform">查询</el-button>
          </el-col>
        </el-row>

        <el-table :data="addoutorderList" @selection-change="handleSelectionChange1">
          <el-table-column type="selection" width="55" align="center" :index="indexMethod" />
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="物料描述" align="center" prop="materialDesc" width="255"/>
          <el-table-column label="物料编码" align="center" prop="materialCode" width="150">
            <template slot-scope="scope">
              <span>{{ formatProductCode(scope.row.materialCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="userDefined1" />
          <el-table-column label="数量" align="center" width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.planNumber" @change="handleQtyChange(scope.row, $event)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="deleteOutOrder(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 确认和取消按钮 -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 物料信息弹窗 -->
    <el-dialog :title="'物料信息'" :visible.sync="showMaterialDialog" width="600px">
      <div>
        <!-- 查询条件 -->
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="物料号">
            <el-input v-model="queryParams.materialCode" placeholder="请输入物料号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchMaterials">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="materialList" @selection-change="handleMaterialSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="ID" align="center" prop="ID" v-if="false" />
          <el-table-column label="物料描述" prop="materialDesc" width="250"/>
          <el-table-column label="物料编码" align="center" prop="materialCode" width="150">
            <template slot-scope="scope">
              <span>{{ formatProductCode(scope.row.materialCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="userDefined1" width="100"/>

        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalMaterials"
          layout="total, prev, pager, next, jumper"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmMaterialSelection">确 定</el-button>
          <el-button @click="showMaterialDialog = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>





  </div>
</template>

<script>
import { listMatetowsn,cardDy, cardBD,Removecard,getMatetowsn, delMatetowsn, addMatetowsn, updateMatetowsn } from "@/api/wms/matetowsn";
import {
  listOutorder,
  getOutorder,
  delOutorder,
  PurchaseOrderOutboundPda,
  addPurchaseOrderOutbound,
  getlistCK,
  listReturnBC,
  OutboundPostingSAP,
  OutboundPostingzcSAP,
  listOutorderZC,
  listProduct,
  listckTS,
  addOdsProcureOutOrderTS,
  getIdCardListTH,
  listReturnDY,
  listOutorderZU
} from '@/api/wms/outorderfc'
export default {
	name: "Matetowsn",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
      batchSingle: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,

			// 总条数
			total: 0,
			// 包材库存明细表表格数据
			matetowsnList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
      showMaterialDialog: false, // 领料单信息弹窗状态
			// 查询参数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      totalMaterials: 0, // 领料单总数
      Optionlistck: [],
      addoutorderList: [],
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        produceCode: '',
        warehouseNo: '',
        planDateMax: '',
        accountingSubject: '', // 总账科目编号
        receiver: '', // 收货方
        productionDate: '', // 生产日期
        shelfLifeExpiryDate: '' ,// 货架寿命到期日
        planDateMin: '',
        materialCode:'',
        costCenter: '' // 新增成本中心字段
      },
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				whCode: null,
				waCode: null,
				wlCode: null,
				orderNo: null,
				poNo: null,
				poLine: null,
				materialCode: null,
				materialDesc: null,
				sn: null,
				barCode: null,
				amount: null,
				userDefined1: null,
				userDefined2: null,
				userDefined3: null,
				userDefined4: null,
				userDefined5: null,
				userDefined6: null,
				userDefined7: null,
				userDefined8: null,
				userDefined9: null,
				userDefined10: null,
				gmtCreate: null,
				lastModifiedBy: null,
				gmtModified: null,
				activeFlag: null,
				factoryCode: null,
				sapFactoryCode: null
			},
      materialList: [], // 领料单数据
			// 表单参数
			form: {},
			// 表单校验
			rules: {
			}
		};
	},
	created() {
		this.getList();
	},
	methods: {
		/** 查询包材库存明细表列表 */
		getList() {
			this.loading = true;
			listMatetowsn(this.queryParams).then(response => {
				this.matetowsnList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
    indexMethod(index) {
      return index + 1;
    },
    /** 过账按钮操作 */
    handleUpdate(row) {
      const ids = row.id || this.ids;
      let postData = this.ids.map(id => ({ mateOrderInSnId: id }));
      console.log(postData)
      this.$modal.confirm('是否进行打印').then(function() {
        return cardDy(JSON.stringify(postData));
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("打印完成");
      }).catch(() => {});
    },
    formatProductCode(code) {
      // 检查是否有效，去掉前7个零
      if (!code) return code; // 处理 null 或 undefined 情况
      return code.replace(/^0{1,7}/, ''); // 替换前1到7个0
    },
    handlequeryform() {
      this.showMaterialDialog = true; // 显示领料单信息弹窗
      this.fetchMaterials(); // 加载领料单数据
      // this.queryParams1.pageNum = 1;
      // this.getList1();
    },
    deleteOutOrder(row) {
      // 确认删除操作
      this.$confirm('确认删除该出库单吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 从 addoutorderList 中删除选定的行
        this.addoutorderList = this.addoutorderList.filter(item => item !== row);
        this.$message.success('删除成功!');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleSelectionChange1(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedRows = selection;
    },
    handleQtyChange(row, event) {
      // 在这里处理输入变化，你可以更新 row 对象中的 qty 属性
      row.planNumber = event;
      // 或者调用后端接口保存数据
      // this.saveQtyToServer(row.id, event);
    },
    handleMaterialSelectionChange(selection) {
      this.selectedMaterials = selection; // 记录选中的领料单
    },
    handleCurrentChange(page) {
      this.currentPage = page; // 更新当前页码
      this.fetchMaterials(page); // 重新加载材料数据
    },
    async confirmMaterialSelection() {
      const materialsToAdd = []; // 临时存储待添加的材料信息

      for (const material of this.selectedMaterials) {
        let queryParams = {
          produceCode: material.produceCode,
          materialCode: material.materialCode
        };

        try {
          const response = await listReturnBC(queryParams);
          console.log("Response:", response);

          const batches = response.rows || []; // 从响应中提取批次数据

          materialsToAdd.push({
            produceCode: material.produceCode,
            materialDesc: material.materialDesc,
            userDefined1: material.userDefined1,
            materialCode: material.materialCode,
            planNumber: material.planNumber, // 数量
            outNumber: material.outNumber,   // 出库数量
            bgnumber: material.bgnumber,     // 报工数量
            returnQty: material.planNumber - material.outNumber, // 出库数量
            qty: 0, // 默认数量为0
          });
        } catch (error) {
          console.error('Error fetching batches:', error);
        }
      }

      // 将待添加的材料一次性添加到 addoutorderList 中
      this.addoutorderList = this.addoutorderList.concat(materialsToAdd);
      console.log("Materials processed");
      this.showMaterialDialog = false; // 关闭领料单弹窗
    },
    handleRemoveBatch(row) {

      this.$modal.confirm('是否确认删除标识卡编号为"' + wlCode + '"的数据项？').then(function() {
        return Removecard();
      }).then(() => {
        this.editBatch();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 重置按钮操作 */
    async fetchMaterials(pageNum = 1) { // 这里的参数名称为 pageNum
      this.loading = true; // 显示加载状态
      try {
        const response = await listProduct({
          ...this.queryParams, // 假设 queryParams 包含其他查询条件
          pageNum: pageNum,    // 将当前页码传递给后端
          pageSize: this.pageSize // 确保将每页显示的数量传递给后端
        });

        // 更新物料列表，并计算索引
        this.materialList = response.rows.map((item, index) => {
          item.index = (pageNum - 1) * this.pageSize + index + 1; // 更新索引
          return item;
        });

        this.totalMaterials = response.total; // 更新总条目数
      } catch (error) {
        console.error('获取物料信息失败:', error);
        this.$message.error('加载物料信息失败，请稍后重试。');
      } finally {
        this.loading = false; // 隐藏加载状态
      }
    },
		// 表单重置
		reset() {
			this.form = {
				mateOrderInSnId: null,
				whCode: null,
				waCode: null,
				wlCode: null,
				orderNo: null,
				poNo: null,
				poLine: null,
				materialCode: null,
				materialDesc: null,
				sn: null,
				barCode: null,
				amount: null,
				userDefined1: null,
				userDefined2: null,
				userDefined3: null,
				userDefined4: null,
				userDefined5: null,
				userDefined6: null,
				userDefined7: null,
				userDefined8: null,
				userDefined9: null,
				userDefined10: null,
				createBy: null,
				gmtCreate: null,
				lastModifiedBy: null,
				gmtModified: null,
				activeFlag: null,
				factoryCode: null,
				sapFactoryCode: null
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.mateOrderInSnId)
			this.single = selection.length!==1
			this.multiple = !selection.length
		},
    forceUpdate(selection) {
      console.log(selection)
    },
		/** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "补打";
      this.queryParams1 = {}
      this.addoutorderList = []
      let factoryCode = localStorage.getItem('USER_POOL_NAME_CURRENT').substring(3)
      let params = { factoryCode: factoryCode }; // 构造一个包含工厂代码的对象
      let paramsJSON = JSON.stringify(params); // 将对象转换为JSON字符串
      console.log(factoryCode)
      getlistCK(paramsJSON).then(response => {
        this.Optionlistck = response.data
        console.log(this.Optionlistck)


      });
    },

		/** 提交按钮 */
    async submitForm() {
      const payload = this.addoutorderList.map(item => ({
        qty: item.qty,  // 计划数量
        userDefined6: this.selectedOrderType,  // 订单类型
        produceCode: item.produceCode,  // 生产代码
        materialDesc: item.materialDesc,  // 物料描述
        materialCode: item.materialCode,  // 物料编码
        unit: item.userDefined1,
        // 注意：根据您的描述，可能没有 unit 字段，请确认是否需要
        // unit: item.unit,
        planNumber: item.planNumber,  // 计划数量
        locCode: this.queryParams1.warehouseNo,  // 仓库编码
        waCode: this.queryParams1.waCode,  // 仓库编码
        userDefined2: this.queryParams1.accountingSubject,  // 总账科目编号
        userDefined4: this.queryParams1.receiver,  // 收货方
        planDate: this.queryParams1.productionDate,  // 生产日期
        userDefined5: this.queryParams1.shelfLifeExpiryDate,  // 货架寿命到期日
        userDefined3: this.queryParams1.costCenter,  // 成本中心（如果订单类型是成本中心）
      }));

      console.log("payload:", payload); // 使用逗号分隔符来打印对象

      try {
        await this.$confirm('确认提交补打吗?', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        });

        // 调用接口提交数据
        const response = await cardBD(payload);
        this.$message.success('补打提交成功');
        this.open = false; // 关闭对话框
        this.addoutorderList = []; // 清空列表或根据需求更新
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消提交');
        } else {
          console.error('提交失败:', error);
          this.$message.error('提交失败，请重试');
        }
      }
      this.getList();
    },
		/** 删除按钮操作 */
		handleDelete(row) {
			const mateOrderInSnIds = row.mateOrderInSnId || this.ids;
			this.$modal.confirm('是否确认删除包材库存明细表编号为"' + mateOrderInSnIds + '"的数据项？').then(function() {
				return delMatetowsn(mateOrderInSnIds);
			}).then(() => {
				this.getList();
				this.$modal.msgSuccess("删除成功");
			}).catch(() => {});
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download('wms/matetowsn/export', {
				...this.queryParams
			}, `matetowsn_${new Date().getTime()}.xlsx`)
		}
	}
};
</script>
