<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 label="型号名称" prop="materialDesc">
				<el-input v-model="queryParams.materialDesc" 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="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['wms:outorder:remove']">删除</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="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="unit" 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="bgnumber" />
      <el-table-column label="需求时间" align="center" prop="planDate" width="250"/>
<!--      <el-table-column label="需求时间" align="center" prop="planDate" width="250"/>-->
<!--			<el-table-column label="仓库编号" align="center" prop="locCode" />-->
<!--			<el-table-column label="库位名称" align="center" prop="locDesc" v-if="false" />-->
<!--			<el-table-column label="产线名称" align="center" prop="productionLineDesc" v-if="false" />-->
<!--			<el-table-column label="产线" align="center" prop="productionLineCode" />-->
			<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 ref="queryParams1" :model="queryParams1" :inline="true" :rules="rulesadd" label-width="130px">
        <el-form-item label="物料编号" prop="materialCode">
          <el-input style="width: 230px"  v-model="queryParams1.materialCode"
                    placeholder="请输入物料编号" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="planDateMin">
          <el-date-picker
            v-model="queryParams1.planDateMin"
            type="date"
            placeholder="选择计划开始时间"
            style="width: 230px"
            @change="handlePlanDateMinChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planDateMax">
          <el-date-picker
            v-model="queryParams1.planDateMax"
            type="date"
            placeholder="选择计划结束时间"
            style="width: 230px"
            @change="handlePlanDateMaxChange"></el-date-picker>
        </el-form-item>

        <el-form-item label="仓库编码" prop="warehouseNo">
          <el-select v-model="queryParams1.warehouseNo" placeholder="请选择仓库编码" @change="forceUpdate()" clearable
                     filterable style="width: 230px">
            <el-option v-for="item in Optionlistck" :key="item.warehouseCode" :label="item.warehouseName"
                       :value="item.warehouseCode"></el-option>
          </el-select>
        </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="handlequeryform">查询</el-button>
				</el-col>
				<!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
			</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"   />

				<el-table-column label="单位" align="center" prop="unit" />
				<el-table-column label="数量" align="center" prop="planNumber" />
				<el-table-column label="出库数量" align="center" prop="outNumber" />
        <el-table-column label="需求时间" align="center" prop="userDefined5" />
        <el-table-column label="工厂号" align="center" prop="siteCode" />
				<el-table-column label="剩余数量" align="center">
					<template slot-scope="scope">
						{{ scope.row.planNumber - scope.row.outNumber }}
					</template>
				</el-table-column>
				<el-table-column label="操作数量" align="center" width="180">
					<template slot-scope="scope">
						<el-input v-model="scope.row.qty" @change="handleQtyChange(scope.row, $event)"></el-input>
					</template>
				</el-table-column>
<!--        <el-table-column label="反冲标识" align="center" prop="userDefined3" />-->

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

<script>
import {
  listOutorder,
  getOutorder,
  delOutorder,
  PurchaseOrderOutboundPda,
  addPurchaseOrderOutbound,
  getlistCK,
  OutboundPostingSAP,
  OutboundPostingzcSAP,
  listOutorderZC,
  listOutorderZU
} from '@/api/wms/outorderfc'

export default {
	name: "Outorder",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组id
			ids: [],
			//选中数组
			selectabletrows:[],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 包材出库单表格数据
			outorderList: [
			],
			// outorderListceshi: [
			// 	{
			// 		createBy: 'admin',
			// 		siteCode: '1000',
			// 		produceCode: '000100305998',
			// 		materialCode: '000000040000015127',
			// 		materialDesc: '榄菊蚊香小盘Ф134mm×H100mm 36圈内增高塑料筒（有字盖）(2201)',
			// 		planDate: '2023-12-25',
			// 		planNumber: 3000.0,
			// 		outNumber: 3000.0,
			// 		locCode: 'WH02',
			// 		productionLineCode: 'LJ8',
			// 		orderStatus: '3',
			// 		userDefined1: '20231225154549',
			// 		userDefined2: '00001',
			// 		userDefined3: '',
			// 		userDefined10: '1',
			// 		createDate: '2023-12-25',
			// 		id: '18d2af6969e0405ba202a5c09bc14f33',
			// 		active: '1',
			// 		unit: 'ST',
			// 		list: [
			// 			{
			// 				createBy: 'admin',
			// 				siteCode: '1000',
			// 				produceCode: '000100305998',
			// 				materialCode: '000000040000015127',
			// 				materialDesc: '榄菊蚊香小盘Ф134mm×H100mm 36圈内增高塑料筒（有字盖）(2201)',
			// 				planDate: '2023-12-25',
			// 				planNumber: 3000.0,
			// 				outNumber: 3000.0,
			// 				locCode: 'WH02',
			// 				productionLineCode: 'LJ8',
			// 				orderStatus: '3',
			// 				userDefined1: '20231225154549',
			// 				userDefined2: '00001',
			// 				userDefined3: '',
			// 				userDefined10: '1',
			// 				createDate: '2023-12-25',
			// 				id: '18d2af6969e0405ba202a5c09bc14f331',
			// 				active: '1',
			// 				unit: 'ST',
			// 			},
			// 			{
			// 				createBy: 'admin',
			// 				siteCode: '1000',
			// 				produceCode: '000100305998',
			// 				materialCode: '000000040000015127',
			// 				materialDesc: '榄菊蚊香小盘Ф134mm×H100mm 36圈内增高塑料筒（有字盖）(2201)',
			// 				planDate: '2023-12-25',
			// 				planNumber: 3000.0,
			// 				outNumber: 3000.0,
			// 				locCode: 'WH02',
			// 				productionLineCode: 'LJ8',
			// 				orderStatus: '3',
			// 				userDefined1: '20231225154549',
			// 				userDefined2: '00001',
			// 				userDefined3: '',
			// 				userDefined10: '1',
			// 				createDate: '2023-12-25',
			// 				id: '18d2af6969e0405ba202a5c09bc14f332',
			// 				active: '1',
			// 				unit: 'ST',
			// 			},
			// 		],
			// 	},
			// 	{
			// 		createBy: 'admin',
			// 		siteCode: '1000',
			// 		produceCode: '000100305998',
			// 		materialCode: '000000040000015127',
			// 		materialDesc: '榄菊蚊香小盘Ф134mm×H100mm 36圈内增高塑料筒（有字盖）(2201)',
			// 		planDate: '2023-12-25',
			// 		planNumber: 3000.0,
			// 		outNumber: 3000.0,
			// 		locCode: 'WH02',
			// 		productionLineCode: 'LJ8',
			// 		orderStatus: '3',
			// 		userDefined1: '20231225154549',
			// 		userDefined2: '00001',
			// 		userDefined3: '',
			// 		userDefined10: '1',
			// 		createDate: '2023-12-25',
			// 		id: '18d2af6969e0405ba202a5c09bc14f32',
			// 		active: '1',
			// 		unit: 'ST',
			// 	},
			// ],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: 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: '',
        planDateMin: '',
        materialCode:'',
			},

			queryParams2: {
				orderNo: '',
				ken: '',
				warehouseNo: '',
				list: [],
			},
			queryParams3: {
				ID: '',
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
			},
			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: [],
      produceCodeTEM:  '',
		};
	},
	created() {
		this.getList();
		this.getselect()
	},
	methods: {
		/** 查询包材出库单列表 */
		indexMethod(index) {
			return index + 1;
		},
		getList() {
			this.loading = true;
			// this.outorderList.forEach((item, index) => {
			// 	item.index = index + 1
			// });
      listOutorderZC(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.queryForm = {}
		},

		// 表单重置
		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.queryParams1.pageNum = 1;
			this.getList1();
		},
		/** 重置按钮操作 */
		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.qty = event;
			// 或者调用后端接口保存数据
			// this.saveQtyToServer(row.id, event);
		},


		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加包材出库单--反冲类型";
			this.queryParams1 = {}
			this.addoutorderList = []
		},
		/** 修改按钮操作 */
		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 => ({ produceCode: item.produceCode,userDefined1:item.userDefined1 }));
			//let postData = this.ids.map(id => ({ id: id }));
			console.log(postData)
      OutboundPostingzcSAP(JSON.stringify(postData)).then(response => {
				this.$modal.msgSuccess("操作完成");
			});
		},
		/** 提交按钮 */
		submitForm() {
			const _this = this
			this.$refs["queryParams1"].validate(valid => {
				if (valid) {
					console.log(_this.selectedRows)
					if (_this.selectedRows.length <= 0) {
						_this.$modal.msgError("请选择");
						return
					}
					let tem = ""
					_this.selectedRows.forEach(function (row) {
						// 在这里对每个 row 进行操作

						if (row.outNumber === row.planNumber) {
							_this.$modal.msgError("已经出完");
							tem = "0"
						}
					});
					if (tem == "0") {
						return
					}
					// var bull = _this.selectedRows.some((item) => {
					// 	// console.log(item.stationNo ==  undefined || item.stationNo == '',item.stationNo)
					// 	return item.productionLineCode == undefined || item.productionLineCode == ''
					// })
          //
					// if (bull) {
					// 	_this.$modal.msgError("请选择包装线");
					// 	return
					// }

          _this.selectedRows.forEach(function(row) {
            // 在这里处理每个元素
            row.stationNo = row.productionLineCode;
            console.log(row);
          });
					if (this.form.ID != null) {
						// updateOutorder(this.form).then(response => {
						// 	this.$modal.msgSuccess("修改成功");
						// 	this.open = false;
						// 	this.getList();
						// });
					} else {
						//this.queryParams2.orderNo = this.queryParams1.produceCode
            this.queryParams2.orderNo = this.produceCodeTEM
						this.queryParams2.warehouseNo = this.queryParams1.warehouseNo
						this.queryParams2.list = _this.selectedRows
						this.queryParams2.ken = 2
						addPurchaseOrderOutbound(JSON.stringify(_this.queryParams2)).then(response => {
							this.$modal.msgSuccess("新增成功");
							this.open = false;
							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>
