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

			<el-form-item label="出库单号" prop="produceCode">
				<el-input v-model="queryParams.produceCode" placeholder="请输入出库单号" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>

			<el-form-item label="物料编码" prop="materialCode">
				<el-input v-model="queryParams.userDefined1" 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="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="success" plain icon="el-icon-edit" size="mini" @click="handleSAP">过账</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="success"
          plain
          :disabled="single"
          icon="el-icon-download"
          size="mini"
          @click="showPrint"
          v-hasPermi="['mes:prepare:export']"
        >打印出库单</el-button>
      </el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['wms:outorder:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>
		<el-table v-loading="loading" :data="outorderList" @selection-change="handleSelectionChange"
			:tree-props="{ children: 'list', hasChildren: 'hasChildren' }" row-key="id" border :default-expand-all="false">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="序号" type="index"  v-if="false" />
			<el-table-column label="工厂编码" align="center" prop="siteCode" v-if="false" />
			<el-table-column label="id" align="center" prop="id" v-if="false" />

      <el-table-column label="出库单号" align="center" prop="produceCode" width="250"/>
      <el-table-column label="批次" align="center" prop="userDefined5" width="250"/>
      <el-table-column label="物料编码" align="center" prop="materialCode" width="250">
        <template slot-scope="scope">
          <span>{{ formatProductCode(scope.row.materialCode) }}</span>
        </template>
      </el-table-column>
			<el-table-column label="物料名称" align="center" prop="materialDesc" width="250"/>
			<el-table-column label="单位" align="center" prop="userDefined1" v-if="false" />
			<el-table-column label="计划数量" align="center" prop="planNumber" />
			<el-table-column label="出库数量" align="center" prop="outNumber" />
			<el-table-column label="状态" align="center" prop="orderStatus">
				<template slot-scope="scope">
					<span v-if="scope.row.orderStatus === '1'">未进行</span>
					<span v-else-if="scope.row.orderStatus === '2'">进行中</span>
					<span v-else-if="scope.row.orderStatus === '3'">完成</span>
				</template>
			</el-table-column>

			<el-table-column label="类型" align="center" prop="userDefined3" />

			<el-table-column label="sap过账状态" align="center" prop="userDefined10">
				<template slot-scope="scope">
					<span v-if="scope.row.userDefined10 === '1'">未过账</span>
					<span v-else-if="scope.row.userDefined10 === '2'">过账成功</span>
					<span v-else-if="scope.row.userDefined10 === '3'">过账失败</span>
				</template>
			</el-table-column>
      <el-table-column label="过账凭证" align="center" prop="userDefined9" width="250"/>

      <el-table-column label="sap订单过账信息" align="center" prop="userDefined11" />

			<el-table-column label="操作人" align="center" prop="createBy" />
			<el-table-column label="操作时间" align="center" prop="createDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
				</template>
			</el-table-column>

		</el-table>

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

		<!-- 生成出库单弹窗-->
    <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="selectedOrderType" placeholder="选择订单类型" @change="handleOrderTypeChange">
                <el-option
                  v-for="type in orderTypes"
                  :key="type"
                  :label="type"
                  :value="type">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <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.accountingSubject" placeholder="总账科目编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货方">
              <el-input v-model="queryParams1.receiver" placeholder="收货方"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期">
              <el-date-picker v-model="queryParams1.productionDate" placeholder="选择生产日期" type="date" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货架寿命到期日">
              <el-date-picker v-model="queryParams1.shelfLifeExpiryDate" placeholder="货架寿命到期日" type="date" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 条件渲染成本中心输入框 -->
        <el-row v-if="selectedOrderType === '成本中心'" :gutter="10" class="mb8">
          <el-col :span="6">
            <el-form-item label="成本中心">
              <el-input v-model="queryParams1.costCenter" 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>










    <!-- 打印预览弹出层(生产物料) -->
    <el-dialog
      title="退料单打印"
      :visible.sync="printDialogVisible"
      :width="shengchan?'861px':'871px'"
    >
      <div id="printFrom" class="my-print-box">

        <el-form :model="form">
          <!-- 表头-工单信息 -->
          <!-- 导航栏 -->
          <el-row class="my-print-nav">
            <el-col :span="24">
              <div style="display: flex; justify-content: flex-end;">
                <div class="my-print-barcode" :width="shengchan ? '631px' : '621px'">
                  <svg id="barcode"></svg>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 主数据 -->

            <!-- 表头-工单信息 -->
            <el-row>
              <div class="my-print-head">
                <el-col :span="24" style="text-align: center;">
                  <h3 style="margin: 0;">普通领料/退料单</h3>
                  <div style="margin-top: 10px;">
                    <span>领料</span>
                    <span style="margin-left: 20px;">退料 <span style="color: green;">✓</span></span>
                  </div>
                </el-col>
              </div>
            </el-row>
            <!-- 导航栏 -->
            <el-row class="my-print-nav">
              <el-col :span="6">领料单:{{printData.factory}}</el-col>
              <el-col :span="6">工厂编码:{{printData.factory}}</el-col>
              <el-col :span="6">库存地点:</el-col>
              <el-col :span="6">发料日期:</el-col>
              <el-col :span="6">打印日期:{{printData.printDate}}</el-col>
            </el-row>
            <el-row class="my-print-nav">
              <el-col :span="6">成本中心编码:</el-col>
              <el-col :span="6">成本中心:</el-col>
              <el-col :span="6">移动类型:</el-col>
              <el-col :span="6">物料凭证:</el-col>
            </el-row>
            <el-table
              v-if="refreshNewWorkerTable" v-loading="newWorkerLoading" class="my-print-table" :data="printData.workTable"
              border style="width: 1000px;padding-bottom: 1px;">
              <el-table-column prop="materialCode" label="物料编码" :width="150" :formatter="productCodeFormate"></el-table-column>
              <el-table-column prop="materialDesc" label="物料描述" :width="200"></el-table-column>
              <el-table-column prop="userDefined1" width="55" label="单位"></el-table-column>
              <el-table-column prop="userDefined5" width="165" label="批号"></el-table-column>
              <el-table-column prop="quantity" label="计划数量"  width="100"></el-table-column>
              <el-table-column prop="planNumber" width="75" label="实发数量"></el-table-column>
              <el-table-column prop="routeCode" width="75" label="备注"></el-table-column>
            </el-table>
            <!-- 底部 -->
            <el-row class="my-print-foot0">
              <el-col :offset="2" :span="3">白色:车间联</el-col>
              <el-col :offset="1" :span="3">蓝色:仓库联</el-col>
              <el-col :offset="1" :span="3">红色:财务联</el-col>
            </el-row>
            <el-row class="my-print-foot">
              <el-col :offset="1" :span="3">品管员审批:</el-col>
              <el-col :offset="2" :span="3">领料人:{{printData.createBy}}</el-col>
              <el-col :offset="2" :span="3">仓管员:</el-col>
            </el-row>
            <div class="fy" v-if="index!=printData.workTable.length-1"></div>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePrint(printData)">打 印</el-button>
      </span>
    </el-dialog>
	</div>
</template>

<script>
import {
  listOutorder,
  getOutorder,
  delOutorder,
  PurchaseOrderOutboundPda,
  addPurchaseOrderOutbound,
  getlistCK,
  listReturnBC,
  OutboundPostingSAP,
  OutboundPostingzcSAP,
  listOutorderZC,
  listProduct,
  listckTS,
  addOdsProcureOutOrderTS,
  getIdCardListTH,
  listReturnDY,
  listOutorderZU
} from '@/api/wms/outorderfc'
import moment from "moment/moment";
import JsBarcode from "jsbarcode";

export default {
	name: "Outorder",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组id
			ids: [],
			//选中数组
			selectabletrows:[],
			// 非单个禁用
			single: true,
      selectedOrderType: '', // 用于存储选中的订单类型
      orderTypes: ['内部订单', '成本中心'], // 静态定义订单类型
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
      newWorkerLoading: false,
      refreshNewWorkerTable:true,
			// 总条数
			total: 0,
      selectedWarehouse: "0004",
      warehouseList: [],
      // 打印
      printData: {
        printable: 'printFrom',
        pageNo:1,
        ignore: ['no-print'],
        workCenter: "暂无数据",
        SAPNo: null,
        manufacture: null,
        auditor: null,
        produceCode:"",
        printDate: null,
        createBy:"",
        factory: null,
        productDate: null,
        workTable: [],
        barcode:null,//打印生产物料和反冲物料的条码
      },
      printDialogVisible: false,
      shengchan:true,
			// 包材出库单表格数据
			outorderList: [
			],

			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
      showMaterialDialog: false, // 领料单信息弹窗状态
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				siteCode: null,
				produceCode: null,
				materialCode: null,
				materialDesc: null,
				planDate: null,
				planNumber: null,
				qty: null,
				Unit: null,
				outNumber: null,
        bgnumber: null,
				locCode: null,
				locDesc: null,
				productionLineDesc: null,
				productionLineCode: null,
				orderStatus: null,
				userDefined1: null,
				userDefined2: null,
				userDefined3: null,
				userDefined4: null,
				userDefined5: null,
				userDefined6: null,
				userDefined7: null,
				userDefined8: null,
				userDefined9: null,
				userDefined10: null,
				userDefined11: null,
				supplierCode: null,
				supplierName: null,
				createBy: null,
				createDate: null,
				lastUpdateBy: null,
				lastUpdateDate: null,
				Active: null,
				enterpriseId: null,
				enterpriseCode: null
			},
			queryParams1: {
				pageNum: 1,
				pageSize: 10,
				produceCode: '',
				warehouseNo: '',
        planDateMax: '',
        accountingSubject: '', // 总账科目编号
        receiver: '', // 收货方
        productionDate: '', // 生产日期
        shelfLifeExpiryDate: '' ,// 货架寿命到期日
        planDateMin: '',
        materialCode:'',
        costCenter: '' // 新增成本中心字段
			},

			queryParams2: {
				orderNo: '',
				ken: '',
				warehouseNo: '',
				list: [],
			},
			queryParams3: {
				ID: '',
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
			},
      batchData: {}, // 存储每个物料的批次数据
			formadd: {},
			rulesadd: {
				produceCode: [
					{ required: true, message: "领料单号不能为空", trigger: "blur" }
				],
				warehouseNo: [
					{ required: true, message: "仓库编码不能为空", trigger: "blur" }
				],
			},
			Optionlistck: [],
			Packagingline: [
				{
					stationNo: 'XL01',
					stationname: '包装线01',
				},
				{
					stationNo: 'XL02',
					stationname: '包装线02',
				},
				{
					stationNo: 'XL03',
					stationname: '包装线03',
				},
				{
					stationNo: 'XL04',
					stationname: '包装线04',
				},
				{
					stationNo: 'XL05',
					stationname: '包装线05',
				},
				{
					stationNo: 'XL06',
					stationname: '包装线06',
				},
				{
					stationNo: 'XL07',
					stationname: '包装线07',
				},
				{
					stationNo: 'XL08',
					stationname: '包装线08',
				},
        {
          stationNo: 'XL09',
          stationname: '包装线09',
        },
        {
          stationNo: 'XL10',
          stationname: '包装线10',
        },
        {
          stationNo: 'XL11',
          stationname: '包装线11',
        },
        {
          stationNo: 'XL12',
          stationname: '包装线12',
        },
        {
          stationNo: 'XL13',
          stationname: '包装线13',
        },
        {
          stationNo: 'XL14',
          stationname: '包装线14',
        },
        {
          stationNo: 'XL15',
          stationname: '包装线15',
        },
			],
			selectedRows: [],
			stationNo: '',
			addoutorderList: [],
      materialList: [], // 领料单数据
      selectedMaterials: [], // 选中的领料单
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      totalMaterials: 0, // 领料单总数
      produceCodeTEM:  '',
      selectedBatch: null, // 用于存储选中的批次
      batches: []
		};
	},
	created() {
		this.getList();
		this.getselect()
	},
	methods: {
		/** 查询包材出库单列表 */
		indexMethod(index) {
			return index + 1;
		},
		getList() {
			this.loading = true;
			// this.outorderList.forEach((item, index) => {
			// 	item.index = index + 1
			// });
      listckTS(this.queryParams).then(response => {
				this.outorderList = response.rows;
				this.outorderList.forEach((item,index) => {
					item.index = index+1
				});
				this.total = response.total;
				this.loading = false;
			});
		},
		getList1() {
			this.loading = true;
      // 获取日期部分

			PurchaseOrderOutboundPda(this.queryParams1).then(response => {//000100220987
				this.addoutorderList = response.data.list;
        this.produceCodeTEM=response.data.produceCode;
				console.log(this.addoutorderList)
				// this.total = response.total;
				// this.loading = false;
			});
		},
		getselect() {
			//  config.headers['poolName'] = localStorage.getItem('USER_POOL_NAME_CURRENT');
			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)


			});
		},
		handleSelectionChange1(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
			this.selectedRows = selection;
		},
		change1(selection) {
			console.log(selection)
		},
		forceUpdate(selection) {
			console.log(selection)
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
			this.addoutorderList  = {}
		},
    handleOrderTypeChange(value) {
      console.log('选择的订单类型:', value);
      // 根据选择的订单类型进行其他操作，例如更新表单项
    },
		// 表单重置
		reset() {
			this.form = {
				siteCode: null,
				ID: null,
				produceCode: null,
				materialCode: null,
				materialDesc: null,
				planDate: null,
				planNumber: null,
				qty: null,
				Unit: null,
				outNumber: null,
        bgnumber: null,
				locCode: null,
				locDesc: null,
				productionLineDesc: null,
				productionLineCode: null,
				orderStatus: null,
				userDefined1: null,
				userDefined2: null,
				userDefined3: null,
				userDefined4: null,
				userDefined5: null,
				userDefined6: null,
				userDefined7: null,
				userDefined8: null,
				userDefined9: null,
				userDefined10: null,
				userDefined11: null,
				supplierCode: null,
				supplierName: null,
				createBy: null,
				createDate: null,
				lastUpdateBy: null,
				lastUpdateDate: null,
				Active: null,
				enterpriseId: null,
				enterpriseCode: null
			};
			this.resetForm("form");
		},
    formatProductCode(code) {
      // 检查是否有效，去掉前7个零
      if (!code) return code; // 处理 null 或 undefined 情况
      return code.replace(/^0{1,7}/, ''); // 替换前1到7个0
    },
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},

		handlequeryform() {
      this.showMaterialDialog = true; // 显示领料单信息弹窗
      this.fetchMaterials(); // 加载领料单数据
			// this.queryParams1.pageNum = 1;
			// this.getList1();
		},
		/** 重置按钮操作 */
    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; // 隐藏加载状态
      }
    }
 ,
    // 打印
    handlePrint(params) {
      printJS({
        printable: params.printable, // 'printFrom', // 标签元素id
        type: params.type || 'html',
        dpi: 360, // 清晰度
        //font_size: "",// 设置字体大小
        header: params.header, // '表单',
        targetStyles: ['*'],

        //没用//style:'body {margin: 2mm;padding: 0;}.fy{page-break-after: always;} table { width:100%;height:800px;border-collapse: collapse;} table, th, td { border: 2px solid black; white-space: pre-wrap; word-break: break-all;} .el-table .cell{padding-left:1px;padding-right:1px;border: 2px solid black;}',
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    printIdCard() {
      // 确保有选中的 ID
      if (this.ids.length === 0) {
        this.$modal.msgError("请先选择至少一条订单进行打印。");
        return;
      }

      // 获取所有选中的 ID
      const selectedIds = this.ids;

      // 批量获取身份证信息
      Promise.all(selectedIds.map(id => getIdCardListTH({ id })))
        .then(responses => {
          responses.forEach(response => {
            // 检查响应的状态
            if (response.code === 200 ) {
              this.$modal.msgSuccess(response.msg);
            }
            // 你可以在这里处理其他的业务逻辑，比如打印身份证信息等
          });
        })
        .catch(error => {

          this.$modal.msgError("打印失败: " + error.message);
        });
    },
    updatePaginatedMaterials() {
      const start = (this.currentPage - 1) * this.pageSize;
      this.paginatedMaterialList = this.materialList.slice(start, start + this.pageSize);
    },
    handleCurrentChange(page) {
      this.currentPage = page; // 更新当前页码
      this.fetchMaterials(page); // 重新加载材料数据
    },
    // 打印预览(生产物料)
    showPrint() {
      this.shengchan = true;
      // 清楚缓存
      this.printData.workCenter = "暂无数据";
      this.printData.pageNo =0 ;
      this.printData.printDate = null;
      this.printData.workTable = [];
      this.printData.factory = null;
      this.printData.productDate = null;

      // 打开工单信息对话框
      this.printDialogVisible = true;
      this.newWorkerLoading = true // 设置加载状态为true，表示正在加载
      this.refreshNewWorkerTable = false // 先将refreshProTable设置为false，隐藏表格
        let queryParams = {
          produceCode: this.outorderList[0].produceCode
      };
      listReturnDY(queryParams).then(response => {
        this.showWorkorderCode = true;
        this.printData.printTitle = '订单物料';
        this.printData.factory = response.data[0].siteCode
        //this.printData.productDate = response.data.mesPrepareDetailList[0].productDate
        this.printData.printDate = moment(new Date()).format('YYYY-MM-DD')
        this.printData.produceCode = response.data[0].produceCode
        this.printData.workTable = response.data;
        this.printData.pageNo = response.data.length;
        this.printData.createBy=     response.data[0].createBy;
        // let chunkedArray = [];
        // console.log(this.printData.workTable[0].produceCode)
        // //遍历this.printData.workTable
        // let chunkSize = (i === 0) ? this.fenyeNumber : this.fenyeNumberTwo;
        //
        // for (let i = 0; i < this.printData.workTable.length; i += chunkSize) {
        //   // 使用slice方法从当前索引i开始切割
        //   let chunk = this.printData.workTable.slice(i, i + chunkSize);
        //   // 将切割后的数组添加到chunkedArray中
        //   chunkedArray.push(chunk);
        // }
      //  this.printData.workTable = chunkedArray;
        console.log(this.printData.workTable[0].produceCode)
        this.printData.produceCode = response.data.produceCode
        this.refreshNewWorkerTable = true // 立即将refreshProTable设置为true，显示表格
        this.newWorkerLoading = false // 设置加载状态为false，表示加载完成

        this.generateBarcode(this.outorderList[0].produceCode); //条码 根据工单号生成
      })
    },
    //产品编码格式化
    productCodeFormate(row, column, cellValue){
      return cellValue.slice(7,18);  //返回值
    },

    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; // 关闭领料单弹窗
    },
    //打印条码
    generateBarcode(barcode){
      JsBarcode("#barcode", barcode, {
        format: "CODE128",
        height:35,
        width:1.5,
        displayValue: true,
      });
    },


    handleMaterialSelectionChange(selection) {
      this.selectedMaterials = selection; // 记录选中的领料单
    },
    resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.selectabletrows = selection;
			console.log('selectabletrows',this.selectabletrows);
			this.single = selection.length !== 1
			this.multiple = !selection.length

		},
		handleQtyChange(row, event) {
			// 在这里处理输入变化，你可以更新 row 对象中的 qty 属性
			row.planNumber = event;
			// 或者调用后端接口保存数据
			// this.saveQtyToServer(row.id, event);
		},
    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('已取消删除');
      });
    },

		/** 新增按钮操作 */
		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)


      });
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const ID = row.ID || this.ids
			getOutorder(ID).then(response => {
				this.form = response.data;
				this.open = true;
				this.title = "修改包材出库单";
			});
		},
    handlePlanDateMinChange(value) {
      this.queryParams1.planDateMin = this.formatDateToString(value);
      this.forceUpdate();
    },
    handlePlanDateMaxChange(value) {
      this.queryParams1.planDateMax = this.formatDateToString(value);
      this.forceUpdate();
    },
    formatDateToString(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    },
		handleSAP(row) {
			console.log(this.ids)
		//	let postData = this.selectabletrows.map(item => ({ id:this.ids[0] }));
      let postData = this.selectabletrows.map(item => ({ id: item.id }));
			//let postData = this.ids.map(id => ({ id: id }));
			console.log(postData)
      OutboundPostingzcSAP(JSON.stringify(postData)).then(response => {
				this.$modal.msgSuccess("操作完成");
			});
		},
    async submitForm() {
      const payload = this.addoutorderList.map(item => ({
        qty: item.qty,  // 计划数量
        userDefined6: item.selectedOrderType,  // 订单类型
        produceCode: item.produceCode,  // 生产代码
        materialDesc: item.materialDesc,  // 物料描述
        materialCode: item.materialCode,  // 物料编码
        // 注意：根据您的描述，可能没有 unit 字段，请确认是否需要
        // unit: item.unit,
        planNumber: item.planNumber,  // 计划数量
        locCode: this.queryParams1.warehouseNo,  // 仓库编码
        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 addOdsProcureOutOrderTS(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 IDs = row.ID || this.ids;
			this.$modal.confirm('是否确认删除包材出库单编号为"' + IDs + '"的数据项？').then(function () {
				return delOutorder(IDs);
			}).then(() => {
				this.getList();
				this.$modal.msgSuccess("删除成功");
			}).catch(() => { });
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download('wms/outorder/export', {
				...this.queryParams
			}, `outorder_${new Date().getTime()}.xlsx`)
		}
	}
};
</script>
