<!-- 生产订单 -->
<template>
	<div class="main-container order-mc-bg">
		<div class="sale-container">
			<div v-if="printTablelist.length">
				<prtMoledop
					:printData="{
						tableData: printTablelist,
						orderName: '生产用料清单',
						ids: printIds,
					}"
					:theadDate="theadDate"
					v-show="false"
				>
				</prtMoledop>
			</div>

			<!-- 顶部按钮组 -->
			<toolBtn :btnType="btnType" @actionhandel="actionhandel"></toolBtn>
			<!-- 上下查 -->
			<div class="TopInfo" v-if="OrderNoNameslist.length > 0">
				关联查询：
				<strong>{{ OrderNoNameStr }}</strong>
				<strong>{{ OrderNoNameslist.length > 5 ? '等' : '' }}</strong>
				{{ $route.query.actionName ? $route.query.actionName : '' }}所选
				<strong>{{ OrderNoNameslist.length }}</strong
				>条明细行的 <strong>{{ CXaction }}</strong
				>结果
			</div>
			<!-- 列表 -->
			<div class="sale-page-body">
				<!-- 表头 -->
				<div class="sale-page-table-header" ref="getSaleTableHeader">
					<el-form :inline="true">
						<el-row class="form-row1">
							<el-col :span="20">
								<el-row :gutter="2">
									<el-col :span="4">
										<el-form-item
											class="Iisshow"
											label="销售订单号"
										>
											<el-input
												class="f-12"
												placeholder="请输入销售订单号"
												v-model.trim="search.salNo"
											></el-input>
											<div
												:data-clipboard-text="
													search.salNo
												"
												@click="saleOrderCopy"
												class="copyBtn"
											>
												<i
													class="el-icon-document-copy"
												/>
											</div>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item
											class="Iisshow"
											label="生产订单号"
										>
											<el-input
												class="f-12"
												placeholder="请输入生产订单号"
												v-model.trim="search.produceNo"
											></el-input>
											<div
												:data-clipboard-text="
													search.produceNo
												"
												@click="saleOrderCopy"
												class="copyBtn"
											>
												<i
													class="el-icon-document-copy"
												/>
											</div>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label="单据状态">
											<el-select
												clearable
												placeholder="请选择"
												v-model="search.documentStatus"
											>
												<el-option
													:key="key + index"
													:label="value"
													:value="key"
													class="f-12"
													v-for="(
														value, key, index
													) in documentStatuslist"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label="生产部门">
											<el-select
												clearable
												filterable
												placeholder="请选择部门"
												v-model="search.workShopId"
											>
												<el-option
													class="f_12"
													label="全部"
													value="0"
												></el-option>
												<el-option
													:key="item.name"
													:label="item.name"
													:value="item.id"
													class="f-12"
													v-for="item in productDeptList"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item
											class="Iisshow"
											label="产品"
										>
											<el-input
												class="f-12"
												placeholder="请输入物料名称/编码/SKU"
												v-model.trim="search.product"
											></el-input>
											<div
												:data-clipboard-text="
													search.product
												"
												@click="saleOrderCopy"
												class="copyBtn"
											>
												<i
													class="el-icon-document-copy"
												/>
											</div>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
							<el-col :span="4" class="form-row-lastcol">
								<el-row :gutter="2">
									<el-col :span="24">
										<el-form-item class="form-group1">
											<div
												@click="openRow"
												class="alias-open"
											>
												<span
													:class="[
														isDown
															? 'icon-shuangjiantouzhankai-xia'
															: 'icon-shuangjiantoushouqi-shang',
													]"
													class="iconfont"
												></span>
											</div>
											<el-button
												size="small"
												@click="resetSearch()"
												>重置</el-button
											>
											<el-button
												@click="searchData"
												size="small"
												type="primary"
												>搜索</el-button
											>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
						<el-row class="form-row2" v-show="rowShow">
							<el-col :span="21">
								<el-row :gutter="2">
									<el-col :span="4">
										<el-form-item label="领料状态">
											<el-select
												clearable
												placeholder="请选择"
												v-model="search.pickmtStatus"
											>
												<el-option
													:key="key + index"
													:label="value"
													:value="key"
													class="f-12"
													v-for="(
														value, key, index
													) in pickmtStatuslist"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="7">
										<el-form-item label="下单日期">
											<el-date-picker
												@change="time1Chang"
												class="f-12"
												end-placeholder="结束时间"
												start-placeholder="开始时间"
												type="daterange"
												v-model="Time1"
												value-format="YYYY-MM-DD"
											></el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="7">
										<el-form-item label="期望交期">
											<el-date-picker
												class="f-12"
												end-placeholder="结束时间"
												start-placeholder="开始时间"
												type="daterange"
												v-model="Time2"
												value-format="YYYY-MM-DD"
											></el-date-picker>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row class="form-row2" v-show="rowShow">
									<el-col :span="21">
										<el-row
											:gutter="2"
											class="form-row2-row2"
										>
											<el-col
												:span="8"
												class="form-r2-r2-col"
											>
												<el-form-item
													label="自定义条件1"
												>
													<CustomCondition
														:getCustomerItem="
															statusForm
																? statusForm
																: {}
														"
														:key="compKey1"
														:reset="reset"
														@result="
															resultCom(
																$event,
																'customerSel1',
																'customerObj1',
																'tempObj1'
															)
														"
													></CustomCondition>
												</el-form-item>
											</el-col>
											<el-col :span="8">
												<el-form-item
													label="自定义条件2"
												>
													<CustomCondition
														:getCustomerItem="
															statusForm
																? statusForm
																: {}
														"
														:key="compKey2"
														:reset="reset"
														@result="
															resultCom(
																$event,
																'customerSel2',
																'customerObj2',
																'tempObj2'
															)
														"
													></CustomCondition>
												</el-form-item>
											</el-col>
											<el-col :span="8">
												<el-form-item
													label="自定义条件3"
												>
													<CustomCondition
														:getCustomerItem="
															statusForm
																? statusForm
																: {}
														"
														:key="compKey3"
														:reset="reset"
														@result="
															resultCom(
																$event,
																'customerSel3',
																'customerObj3',
																'tempObj3'
															)
														"
													></CustomCondition>
												</el-form-item>
											</el-col>
										</el-row>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<!-- 列表 -->
				<div class="sale-page-table-body">
					<el-table
						:data="tableData"
						:header-cell-class-name="headerRigthMethod"
						:max-height="heightNum"
						@row-dblclick="openDetailsDB"
						@selection-change="handleSelectionChange"
						border
						class="table-box"
						element-loading-spinner="el-icon-loading"
						element-loading-text="加载中，请稍后..."
						ref="tableInfoRef"
						style="width: 100%; font-size: 12px"
						v-loading="isLoading"
					>
						<el-table-column
							align="center"
							fixed
							type="selection"
							width="40"
						/>
						<el-table-column
							align="left"
							fixed
							label="销售订单号"
							prop="salOrderNo"
							width="187"
						></el-table-column>
						<el-table-column
							align="left"
							fixed
							label="生产订单号"
							prop="produceNo"
							width="120"
						>
							<template #default="scope">
								<span
									@click="jump(scope.row)"
									style="color: #4178d5"
									>{{ scope.row.produceNo }}</span
								>
							</template>
						</el-table-column>
						<el-table-column
							align="center"
							label="下单日期"
							prop="date"
							width="83"
						>
							<template #default="scope">
								<span>{{
									scope.row.date
										? transformTime(scope.row.date)
										: ''
								}}</span>
							</template>
						</el-table-column>
						<el-table-column
							align="center"
							label="单据状态"
							prop="documentStatus"
							width="72"
						/>
						<el-table-column
							align="center"
							label="业务状态"
							prop="status"
							width="72"
						/>
						<el-table-column
							align="left"
							label="物料编码"
							prop="materialNumber"
							width="150"
						/>
						<el-table-column
							align="left"
							label="规格型号(SKU)"
							prop="specification"
							width="280"
						/>
						<el-table-column
							align="left"
							label="物料名称"
							prop="materialName"
							width="150"
						/>
						<el-table-column
							align="left"
							label="生产部门"
							prop="workShop"
							width="120"
						/>
						<el-table-column
							align="left"
							label="计划开工日期"
							prop="planStartDate"
							width="96"
						>
							<template #default="scope">
								<span>
									{{
										scope.row.planStartDate
											? transformTime(
													scope.row.planStartDate
											  )
											: scope.row.planStartDate
									}}
								</span>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="计划完工日期"
							prop="planFinishDate"
							width="96"
						>
							<template #default="scope">
								<span>{{
									scope.row.planFinishDate
										? transformTime(
												scope.row.planFinishDate
										  )
										: ''
								}}</span>
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="数量"
							prop="number"
							width="100"
						/>
						<el-table-column
							align="right"
							label="领料套数"
							prop="pickmtNumber"
							width="100"
						/>
						<el-table-column
							align="center"
							label="领料状态"
							prop="pickmtStatus"
							width="72"
						/>
						<el-table-column
							align="right"
							label="合格入库数量"
							prop="stockEligibleNumber"
							width="100"
						/>
						<el-table-column
							align="right"
							label="未入库数量"
							prop="noStockEligibleNumber"
							width="100"
						/>
						<el-table-column
							align="left"
							label="仓库"
							prop="stock"
							width="120"
						/>
						<el-table-column
							align="left"
							label="结案日期"
							prop="closeDate"
							width="83"
						>
							<template #default="scope">
								<span>{{
									scope.row.closeDate
										? transformTime(scope.row.closeDate)
										: ''
								}}</span>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="期望交期"
							prop="expectDate"
							width="83"
						>
							<template #default="scope">
								<span>{{
									scope.row.expectDate
										? transformTime(scope.row.expectDate)
										: ''
								}}</span>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="用料清单"
							prop="placeOrder"
							width="150"
						>
							<template #default="scope">
								<span
									@click="
										jumpUserMaterialSet(index, scope.row)
									"
									class="text-blue"
									v-if="scope.row.documentStatus === '已审核'"
									>用料清单({{ scope.row.printCount }})</span
								>
								<span class="text-black-light" v-else
									>用料清单({{ scope.row.printCount }})</span
								>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="备注"
							prop="remark"
							width="280"
						>
							<template #default="scope">
								<div
									:title="scope.row.remark"
									class="noteOrder"
									v-show="scope.row.showTooltip"
								>
									{{ scope.row.remark }}
								</div>
								<div
									class="noteOrder"
									v-show="!scope.row.showTooltip"
								>
									{{ scope.row.remark }}
								</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<!-- 底部 -->
			<div class="sale-page-footer">
				<div class="footer-left">
					<div>
						<span>生产数量:</span>
						<span class="sale-number-color">{{ number }}</span>
					</div>
					<div>
						<span>领料套数:</span>
						<span class="sale-number-color">{{
							pickmtNumber
						}}</span>
					</div>
					<div>
						<span>合格入库数量:</span>
						<span class="sale-number-color">{{
							stockEligibleNumber
						}}</span>
					</div>
					<div>
						<span>未入库数量:</span>
						<span class="sale-number-color">{{
							noStockEligibleNumber
						}}</span>
					</div>
				</div>
				<div class="footer-right">
					<el-pagination
						:currentPage="search.pageNo"
						:page-size="search.pageSize"
						:page-sizes="[50, 100, 150]"
						:total="orderTotal"
						@current-change="handleCurrentChange"
						@size-change="handleSizeChange"
						layout="slot,sizes, total,prev,pager, next,jumper"
						popper-class="每页显示"
					>
						<span class="total-select-item">
							共选中
							<text
								style="
									text-align: center;
									color: #4178d5;
									padding: 0 1px;
								"
							>
								{{
									multipleSelection
										? multipleSelection.length
										: 0
								}} </text
							>行
						</span>
					</el-pagination>
				</div>
				<div class="footer-pagination-total-page">
					<span
						>共{{ Math.ceil(orderTotal / search.pageSize) }}页</span
					>
				</div>
			</div>
		</div>
		<!-- 操作结果 -->
		<el-dialog title="操作结果" v-model="dialogVisible" width="40%">
			<div class="sale-page-table-body">
				<el-table
					:data="tableInfo"
					:header-cell-class-name="headerRigthMethod"
					border
					class="table-box"
					height="300"
					id="tableInfo-table"
				>
					<el-table-column label="序号" prop="date" width="50">
						<template #default="scope">
							<span>{{ scope.$index + 1 }}</span>
						</template>
					</el-table-column>
					<el-table-column
						label="生产订单号"
						prop="orderNo"
						width="200"
					></el-table-column>
					<el-table-column label="指令" prop="a" width="110">
						<template #default>
							<span>
								{{
									actionType === 'submit'
										? '提交'
										: actionType === 'revoke'
										? '撤销'
										: actionType === 'audit'
										? '审核'
										: actionType === 'de-approval'
										? '反审'
										: actionType === 'delet'
										? '删除'
										: actionType === 'finish'
										? '完工'
										: actionType === 'close-case'
										? '结案'
										: actionType === 'de-excute-start'
										? '反执行至开工'
										: actionType === 'de-approval'
										? '反审'
										: actionType === 'delet'
										? '删除'
										: actionType === 'finish'
										? '完工'
										: actionType === 'close-case'
										? '结案'
										: actionType === 'de-excute-finish'
										? '反执行至完工'
										: ''
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column label="结果" width="80">
						<template #default="scope">
							<span :style="{ 'txt-Red': scope.row.isSuccess }">{{
								scope.row.isSuccess ? '成功' : '失败'
							}}</span>
						</template>
					</el-table-column>
					<el-table-column label="信息" prop="msg">
						<template #default="scope">
							<span class="txt-Red">{{ scope.row.msg }}</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<span
						class="f-12 ext-black-light"
						style="margin-right: 25px"
					>
						共{{
							tableInfo && tableInfo.length > 0
								? tableInfo.length
								: 0
						}}条
					</span>
					<el-button
						@click="
							handelhtmlToExcel('tableInfo-table', '下单结果');
							dialogVisible = false;
						"
						size="small"
						>导 出</el-button
					>
					<el-button
						@click="dialogVisible = false"
						size="small"
						type="primary"
						>关 闭</el-button
					>
				</span>
			</template>
		</el-dialog>
		<!-- 选择下推单据 -->
		<el-dialog
			title="选择下推单据"
			top="15%"
			v-model="dialogxt"
			width="20%"
		>
			<div class="sale-page-table-body">
				<el-radio-group v-model="pushdownVal">
					<el-radio :label="1">生产入库单</el-radio>
					<el-radio :label="2">生产补料单</el-radio>
					<el-radio :label="3">生产领料单</el-radio>
					<el-radio :label="4">生产退料单</el-radio>
				</el-radio-group>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogxt = false" size="small"
						>取 消</el-button
					>
					<el-button
						@click="sumitPushdown"
						size="small"
						type="primary"
						>确 定</el-button
					>
				</span>
			</template>
		</el-dialog>
		<!-- 选择上下查单据 -->
		<el-dialog :title="CXttile" top="15%" v-model="dialogCX" width="20%">
			<div class="sale-page-table-body">
				<el-radio-group
					v-if="CXttile === '上查结果'"
					v-model="CXcheckVal"
				>
					<el-radio
						:key="index"
						:label="it.orderType"
						v-for="(it, index) in upOrDownList"
					>
						{{ it.orderName }}({{ it.orderCount }})
					</el-radio>
				</el-radio-group>
				<el-radio-group
					v-if="CXttile === '下查结果'"
					v-model="CXcheckVal"
				>
					<el-radio
						:key="index"
						:label="it.orderType"
						v-for="(it, index) in upOrDownList"
					>
						{{ it.orderName }}({{ it.orderCount }})
					</el-radio>
				</el-radio-group>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogCX = false" size="small"
						>取 消</el-button
					>
					<el-button @click="submitCX" size="small" type="primary"
						>确 定</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script>
import examineTop from '@/components/examineTop/index.vue';

import { mapState } from 'vuex';
import {
	resultComMethods,
	customChangeMethods,
	transformTimestamp,
	exporthandel,
	htmlToExcel,
	newprintPreview1,
} from '@/utils/pubulic.js';
import { toRaw } from 'vue';
import { orderCopy } from '@/utils/takeMethods';
import { productOrderPrint } from '@/utils/printPagekey.js';
import CustomCondition from '@/components/public/CustomCondition.vue';
import prtMoledop from '@/components/public/printviews/prtMoledop.vue';
export default {
	name: 'ProductOrder',
	components: {
		prtMoledop,
		examineTop,
		CustomCondition,
	},
	data() {
		return {
			theadDate: JSON.parse(JSON.stringify(productOrderPrint)), // 打印要的字段表
			printTablelist: [], //用来清单打印的数据
			printIds: [],
			statusForm: {
				customCondition: [],
				warehouse: [],
			}, // 自定义条件 订单类型 单据状态 供应组织 是否211 是否赠品 关闭状态
			//条件
			reset: false,
			customerSel1: '',
			customerSel2: '',
			customerSel3: '',
			tempObj1: null,
			tempObj2: null,
			tempObj3: null,
			compKey1: 0,
			compKey2: 0,
			compKey3: 0,
			CXcheckVal: '', // 上下查选中
			dialogCX: false, // 上下查弹框控制
			upOrDownList: [], // 上查下查弹窗可选数据
			OrderNoNameslist: [], // 上查下查的订单号
			OrderNoNameStr: '', // 上查下查的订单号str
			CXaction: '', // 判断是上查还是下查
			OrdedetailIds: [], // 勾选的明细id集合
			OrderNoNames: [], // 选择的单据订单号集合
			CXttile: '', // 查询弹框的名称
			multipleSelection: [], // 列表选中
			pushdownVal: null, // 下推选择
			actionType: '', //判断点击的顶部那个按钮
			tableInfo: [], //操作结果
			isLoading: false, //表格加载数据
			documentStatuslist: [], // 单据状态
			pickmtStatuslist: [], // 领料状态
			produceBusinessStatuslist: [], // 业务状态
			btnType: ['save', 'close', 'de-close', 'print-brower', 'exDetails'], // 不需要显示的顶部按钮类型
			productDeptList: [], // 生产部门
			Time1: [],
			Time2: [],
			dialogVisible: false, // 操作弹框显示
			dialogxt: false, // 选择下推单据弹框显示
			// 搜索条件
			search: {
				salNo: '', // 销售订单号
				orgId: '', // 组织ID
				produceNo: '', // 生产订单号
				documentStatus: '', //单据状态
				workShopId: '', //生产部门
				product: '', //产品 物料名称/编码/SKU
				pickmtStatus: '', //领料状态
				status: '', // 业务状态
				orderBeginDate: '', // 下单开始日期
				orderEndDate: '', //下单结束日期
				expectBeginDate: '', // 期望开始交期
				expectEndDate: '', //期望结束交期
				detailsIds: [], // 明细列表ID 上下查 使用
				pageNo: 1, // 页码
				pageSize: 50, // 页数
			},
			number: 0, //生产数量统计
			pickmtNumber: 0, //领取套数统计
			stockEligibleNumber: 0, //合格入库数量统计
			noStockEligibleNumber: 0, //未入库数量统计
			orderTotal: 0, // 未入库数量统计
			tableData: [],
			rowShow: false,
			heightNum: 0,
			windowHeight: 0,
			isDown: true,
		};
	},
	// components: {
	// 	CustomCondition,
	// },
	computed: {
		...mapState({
			orgId: (state) =>
				state && state.org && state.org.orgId ? state.org.orgId : null,
		}),
		transformTime: function () {
			return function (value) {
				return transformTimestamp(value);
			};
		},
	},
	created() {
		this.windowHeight = document.documentElement.clientHeight;
		this.heightNum =
			this.windowHeight - (40 + 30 + 54 + 34 + 34 + 34 + 16 + 16);
		this.search.orgId = this.orgId;
		this.getProductdept();
		this.Init();
	},
	activated() {
		// 键盘监听事件
		document.addEventListener('keyup', this.keyupFn, false);
	},
	deactivated() {
		document.removeEventListener('keyup', this.keyupFn, false);
	},
	watch: {
		orgId(val) {
			if (val) {
				this.search.orgId = val;
				this.search.pageNo = 1;
				this.getproductOrder();
			}
		},
		customerSel1: function () {
			let returnR = customChangeMethods(
				this.customerSel1,
				this.customerSel2,
				this.customerSel3,
				'x',
				this.compKey1
			);
			this.customerSel1 = returnR.selfVal;
			this.customerSel2 = returnR.otherO;
			this.customerSel3 = returnR.otherT;
			this.compKey1 = returnR.keyRsf;
		},
		customerSel2: function () {
			let returnR = customChangeMethods(
				this.customerSel2,
				this.customerSel1,
				this.customerSel3,
				'y',
				this.compKey2
			);
			this.customerSel2 = returnR.selfVal;
			this.customerSel1 = returnR.otherO;
			this.customerSel3 = returnR.otherT;
			this.compKey2 = returnR.keyRsf;
		},
		customerSel3: function () {
			let returnR = customChangeMethods(
				this.customerSel3,
				this.customerSel1,
				this.customerSel2,
				'z',
				this.compKey3
			);
			this.customerSel3 = returnR.selfVal;
			this.customerSel1 = returnR.otherO;
			this.customerSel2 = returnR.otherT;
			this.compKey3 = returnR.keyRsf;
		},
	},
	methods: {
		keyupFn(e) {
			if (e.keyCode === 13) {
				// enter见搜索
				this.searchData();
			}
		},
		// 初始化
		Init() {
			this.getcheckInfo();
			this.getproductOrder();
			this.getStatus();
			this.getselfData();
		},
		resetSearch() {
			// 搜索条件
			this.reset = true;
			this.search = {
				salNo: '', // 销售订单号
				orgId: this.orgId, // 组织ID
				produceNo: '', // 生产订单号
				documentStatus: '', //单据状态
				workShopId: '', //生产部门
				product: '', //产品 物料名称/编码/SKU
				pickmtStatus: '', //领料状态
				status: '', // 业务状态
				orderBeginDate: '', // 下单开始日期
				orderEndDate: '', //下单结束日期
				expectBeginDate: '', // 期望开始交期
				expectEndDate: '', //期望结束交期
				detailsIds: [], // 明细列表ID 上下查 使用
				pageNo: 1, // 页码
				pageSize: 50, // 页数
			};
			this.Time1 = [];
			this.Time2 = [];
			this.customerSel1 = '';
			this.customerSel2 = '';
			this.customerSel3 = '';
			setTimeout(() => {
				this.reset = false;
			}, 200);
			this.getproductOrder();
		},
		resultCom(result, fieldSale, fieldObj, tempObj) {
			// 自定义条件赋值
			let returnResult = resultComMethods(
				result,
				this[fieldSale],
				result.outResult,
				this[tempObj],
				this.search
			);
			this[fieldSale] = returnResult.fieldSale;
			this[fieldObj] = returnResult.fieldObj;
			this[tempObj] = returnResult.tempObj;
			this.search = returnResult.search;
		},
		// 操作弹框导出
		handelhtmlToExcel(domid, title) {
			htmlToExcel(domid, title);
		},
		// 上下查数据
		getcheckInfo() {
			if (this.$route.query) {
				this.search.detailsIds = this.$route.query.detailsIds
					? JSON.parse(
							decodeURIComponent(this.$route.query.detailsIds)
					  )
					: [];
				this.CXaction =
					this.$route.query.actionType === 'up' ? '上查' : '下查';
				let ordNostr = '';
				this.OrderNoNameslist = this.$route.query.OrderNoNames
					? JSON.parse(
							decodeURIComponent(this.$route.query.OrderNoNames)
					  )
					: [];
				if (this.OrderNoNameslist) {
					this.OrderNoNameslist.forEach((it, index) => {
						if (index < 5) {
							ordNostr = ordNostr + it + ',';
						}
					});
				}
				this.OrderNoNameStr = ordNostr;
			}
		},
		// 用料清单-跳转到生产用料清单设置页面
		jumpUserMaterialSet(index, item) {
			if (item.documentStatus === '已审核') {
				this.$router.push({
					path: '/production/productMange/useMaterialSet',
					query: { detailId: item.detailId },
				});
			}
		},
		// 双击计入
		openDetailsDB(row, column) {
			let typeStr1 =
				row.documentStatus === '重新审核' ||
				row.documentStatus === '创建'
					? 'edit'
					: 'see';
			this.$router.push({
				path: '/production/productMange/productOrderSet',
				query: { type: typeStr1, productId: row.id },
			});
		},
		// 自定义的数据源
		getselfData() {
			// 获取自定义条件数据
			this.$http.get('Dictionary/produce').then((req) => {
				// 下拉字段集合
				var newList = [];
				toRaw(req.data).forEach((element) => {
					newList.push(element);
				});
				this.statusForm.customCondition = toRaw(newList);
				// 获取仓库
				this.$http.get('SysConfig/GetWarehouse').then((req) => {
					this.statusForm.warehouse = req.data;
				});
			});
		},
		// 自定义监听数据处理
		setselfChangeValue(
			customerSel1,
			customerSel2,
			customerSel3,
			key,
			compKey
		) {
			if (this[customerSel1] == undefined) {
				this[customerSel1] = key;
			}
			if (this[customerSel1] == key) {
				return;
			}
			if (
				this[customerSel1] == this[customerSel2] ||
				this[customerSel1] == this[customerSel3]
			) {
				this[customerSel1] = key;
				this[compKey] += 1;
				this.$message.error({
					message: '不能重复选择!',
					showClose: true,
				});
			}
		},
		// 自定义选择赋值结果
		selfResult(result, fieldSale, fieldObj, tempObj) {
			this[fieldSale] = result.currVal;
			this[fieldObj] = result.outResult;

			if (JSON.stringify(this[fieldObj]) != '{}') {
				this[tempObj] = JSON.parse(JSON.stringify(this[fieldObj]));
				for (const key in this[fieldObj]) {
					this.search[key] = this[fieldObj][key];
				}
			} else {
				for (const key in this[tempObj]) {
					delete this.search[`${key}`];
				}
				this[tempObj] = null;
			}
			if (this[fieldSale] == undefined || this[fieldSale] == '') {
				for (const key in this[tempObj]) {
					delete this.search[`${key}`];
				}
				this[tempObj] = null;
			}
		},
		// 搜索切换高度
		openRow() {
			this.isDown = !this.isDown;
			this.rowShow = !this.rowShow;
			if (this.rowShow) {
				this.heightNum = this.heightNum - 80;
			} else {
				this.heightNum = this.heightNum + 80;
			}
		},
		// 点击生产订单查看或者是编辑
		jump(item) {
			// 只有创建和重新审核的单据才能做修改，其余都是查看
			let typeStr =
				item.documentStatus === '重新审核' ||
				item.documentStatus === '创建'
					? 'edit'
					: 'see';
			if (typeStr === 'edit') {
				this.$router.push({
					path: '/production/productMange/productOrderSet',
					meta: { title: '编辑生产订单' },
					query: { type: typeStr, productId: item.id },
				});
			} else {
				this.$router.push({
					path: '/production/productMange/productOrderSet',
					query: { type: typeStr, productId: item.id },
				});
			}
		},
		//确定上下查
		submitCX() {
			if (this.CXcheckVal) {
				let pathName = '';
				if (this.CXcheckVal === 7) {
					// 销售订单
					pathName = 'SaleOrder';
				}
				if (this.CXcheckVal === 10) {
					// 组织间需求单
					pathName = 'orgNeeds';
				}
				if (this.CXcheckVal === 19) {
					// 生产入库单
					pathName = 'ProductWarehousingOrder';
				}
				if (this.CXcheckVal === 17) {
					// 生产补料单
					pathName = 'ProductReplenishment';
				}
				if (this.CXcheckVal === 16) {
					// 生产领料单
					pathName = 'ProductPicking';
				}
				if (this.CXcheckVal === 18) {
					// 生产退料单
					pathName = 'ProductReturnMaterial';
				}
				if (this.CXcheckVal === 10) {
					// 组织间
					pathName = 'OrgNeeds';
				}
				let ary = [];
				ary = this.upOrDownList.filter((it) => {
					return it.orderType === this.CXcheckVal;
				});
				if (pathName) {
					this.$router.push({
						name: pathName,
						query: {
							detailsIds: JSON.stringify(
								ary.length > 0 ? ary[0].detailsIds : []
							),
							actionType:
								this.CXttile === '上查结果' ? 'up' : 'down',
							actionName: '生产订单',
							OrderNoNames: JSON.stringify(
								ary.length > 0 ? ary[0].billNos : []
							),
						},
					});
					this.dialogCX = false;
				}
			} else {
				this.$message.error({
					message: '请先选择在确认',
					showClose: true,
				});
			}
		},
		// 下推确定
		sumitPushdown() {
			if (this.pushdownVal) {
				let pathName = '';
				let routerName = '';
				if (this.pushdownVal === 1) {
					// 生产入库
					pathName = 'ProduceOrder/PushDownInStock';
					routerName = 'AddProductWarehouOrder';
				}
				if (this.pushdownVal === 2) {
					// 生产补料单
					pathName = 'ProduceOrder/PushDownFeed';
					routerName = 'AddProudtreplenishmentOrder';
				}
				if (this.pushdownVal === 3) {
					// 生产领料单
					pathName = 'ProduceOrder/PushDownPick';
					routerName = 'AddProductPickOrder';
				}
				if (this.pushdownVal === 4) {
					// 生产退料单
					pathName = 'ProduceOrder/PushDownReturn';
					routerName = 'AddProudtReturnOrder';
				}
				this.$http
					.post(pathName, { ids: this.OrdedetailIds })
					.then((res) => {
						if (res.status === 200) {
							this.$router.push({
								name: routerName,
								query: {
									type: 'pushDown',
									ids: encodeURIComponent(
										JSON.stringify(this.OrdedetailIds)
									),
								},
							});
							this.dialogxt = false;
						}
					});
			} else {
				this.$message.error({
					message: '请先选中在确认',
					showClose: true,
				});
			}
		},
		// 获取需要状态列表---[单据状态，领料状态，业务状态]
		getStatus() {
			this.$http.get('ProduceOrder/GetStatus').then((r) => {
				if (r.status === 200) {
					this.documentStatuslist = r.data.documentStatus;
					this.pickmtStatuslist = r.data.pickmtStatus;
					this.produceBusinessStatuslist =
						r.data.produceBusinessStatus;
				}
			});
		},
		// 获取部门数据
		getProductdept() {
			this.$http.post('SysConfig/GetDept/' + this.orgId).then((res) => {
				if (res.status === 200) {
					this.productDeptList = res.data;
				}
			});
		},
		// 获取生产订单数据
		getproductOrder() {
			this.isLoading = true;
			this.$http
				.post('ProduceOrder/ProduceOrderQuery', this.search)
				.then((res) => {
					if (res.status === 200) {
						this.isLoading = false;
						res.data.list.forEach((it) => {
							it.number = it.number ? it.number : 0;
							it.pickmtNumber = it.pickmtNumber
								? it.pickmtNumber
								: 0;
							it.stockEligibleNumber = it.stockEligibleNumber
								? it.stockEligibleNumber
								: 0;
							it.noStockEligibleNumber = it.noStockEligibleNumber
								? it.noStockEligibleNumber
								: 0;
						});
						this.tableData = res.data.list;
						this.orderTotal = res.data.total ? res.data.total : 0;
						this.noStockEligibleNumber =
							res.data.noStockEligibleNumber;
						this.number = res.data.number;
						this.pickmtNumber = res.data.pickmtNumber;
						this.stockEligibleNumber = res.data.stockEligibleNumber;
					}
				});
		},
		// 顶部公共按钮操作
		actionhandel(type) {
			this.actionType = type;
			// 点击新增
			if (type === 'add') {
				this.$router.push({
					path: '/production/productMange/productOrderSet',
					query: { type: 'add', id: '', sjtag: Math.random() * 36 },
				});
			}
			if (this.multipleSelection && this.multipleSelection.length > 0) {
				let nweArysize = 0;
				// 单据id集合 （有去重）
				let newArry = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.id;
						})
					),
				];
				// 取单据订单号
				let orderNoArry = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.produceNo;
						})
					),
				];
				this.OrderNoNames = [];
				this.OrderNoNames = orderNoArry;
				// 明细id集合 （有去重）
				let detailsIds = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.detailId;
						})
					),
				];
				this.OrdedetailIds = [];
				this.OrdedetailIds = detailsIds;
				// 单据id 集合的size
				nweArysize = new Set(
					this.multipleSelection.map((item) => {
						return item.id;
					})
				).size;
				// 点击复制
				if (type === 'copy') {
					if (nweArysize !== 1 && nweArysize > 0) {
						this.$message.error({
							message: '只能克隆单号相同的生产订单',
							showClose: true,
						});
					} else {
						this.$router.push({
							path: '/production/productMange/productOrderSet',
							query: {
								type: 'copy',
								productId: this.multipleSelection[0].id,
								detailsIds: JSON.stringify(detailsIds),
							},
						});
					}
				}
				// 点击提交
				if (type === 'submit') {
					this.toolarFn('ProduceOrder/CommitList', newArry);
				}
				// 点击撤销
				if (type === 'revoke') {
					this.toolarFn('ProduceOrder/Revoke', newArry);
				}
				// 点击审核
				if (type === 'audit') {
					this.toolarFn('ProduceOrder/Check', newArry);
				}
				// 点击反审核
				if (type === 'de-approval') {
					this.toolarFn('ProduceOrder/NoCheck', newArry);
				}
				// 点击删除
				if (type === 'delet') {
					this.toolarFn('ProduceOrder/Delete', newArry);
				}
				// 点击下推
				if (type === 'push-down') {
					if (detailsIds.length <= 20) {
						if (
							this.multipleSelection.filter((it) => {
								return it.documentStatusKey !== 'c';
							}).length > 0
						) {
							this.$message.error({
								message:
									'单据状态错误，只能选择单据状态为已审核单据，请重新选择！',
								showClose: true,
							});
						} else {
							this.dialogxt = true;
						}
					} else {
						this.$message.warning({
							message: '最多一次性下推二十条明细',
							showClose: true,
						});
					}
				}
				// 点击完工
				if (type === 'finish') {
					this.toolarFn('ProduceOrder/Finished', newArry, detailsIds);
				}
				// 点击结案
				if (type === 'close-case') {
					this.toolarFn(
						'ProduceOrder/CaseClosed',
						newArry,
						detailsIds
					);
				}
				// 点击反执行至开工
				if (type === 'de-excute-start') {
					this.toolarFn('ProduceOrder/ToStart', newArry, detailsIds);
				}
				// 点击反执行至完工
				if (type === 'de-excute-finish') {
					this.toolarFn(
						'ProduceOrder/ToFinished',
						newArry,
						detailsIds
					);
				}
				// 点击查询--上查
				if (type === 'up-check') {
					this.$http
						.post('ProduceOrder/Upper', { ids: detailsIds })
						.then((res) => {
							if (res.status === 200) {
								this.upOrDownList = res.data;
								this.dialogCX =
									res.data && res.data.length > 0
										? true
										: false;
								this.CXttile = '上查结果';
								this.CXcheckVal =
									res.data && res.data.length === 1
										? res.data[0].orderType
										: null; //只有一个，就个默认值
							}
						});
				}
				// 点击查询--下查
				if (type === 'down-check') {
					this.$http
						.post('ProduceOrder/Lower', { ids: detailsIds })
						.then((res) => {
							if (res.status === 200) {
								this.upOrDownList = res.data;
								this.dialogCX =
									res.data && res.data.length > 0
										? true
										: false;
								this.CXttile = '下查结果';
								this.CXcheckVal =
									res.data && res.data.length === 1
										? res.data[0].orderType
										: null; //只有一个，就个默认值
							}
						});
				}
				//打印
				if (type === 'print-aterial-list') {
					if (!detailsIds.length) {
						this.$message.error({
							message: '请选择需要打印/预览的用料清单信息',
							showClose: true,
						});
						return false;
					}

					this.$http
						.post('ProduceMaterial/ProduceMaterialQuery', {
							detailsIds: detailsIds,
						})
						.then((res) => {
							if (res.status === 200) {
								if (res.data.documentStatusKey === 'c') {
									this.$http
										.post('ProduceOrder/PrintCountList', {
											ids: detailsIds,
										})
										.then((result) => {
											if (result.status === 200) {
												let list = []; //用于存储分子不是0的数据
												let ids = []; //list的outSourcOrderNo集合
												list = res.data.list.filter(
													(item) => {
														return item.numerator;
													}
												);

												let lLength = list.length;
												for (
													let i = 0;
													i < lLength;
													i++
												) {
													ids.push(
														list[i]
															.produceMaterialNo
													);
												}
												this.printIds = [
													...new Set(ids),
												];

												let length =
													this.printIds.length;
												// 这里为什么要用双循环对比？因为要拿i塞数据
												for (
													let i = 0;
													i < length;
													i++
												) {
													this.printTablelist[i] = [];
													for (
														let j = 0;
														j < lLength;
														j++
													) {
														if (
															this.printIds[i] ==
															list[j]
																.produceMaterialNo
														) {
															this.printTablelist[
																i
															].push(list[j]);
														}
													}
												}
												if (
													this.printTablelist.length >
													0
												) {
													this.$nextTick(() => {
														newprintPreview1(
															'生产用料清单',
															this.printIds
																.length,
															this.printTablelist
														);
													});
												} else {
													this.$message.error({
														message:
															'所选用料清单明细为空，无法打印!',
														showClose: true,
													});
												}
											}
										});
								} else {
									this.$message.error({
										message:
											'只能打印预览已经审核的用料清单信息',
										showClose: true,
									});
								}
							}
						});
				}
			} else {
				//按列表字段导出,点击全部导出
				if (
					type !== 'add' &&
					type !== 'refresh' &&
					type !== 'list-export' &&
					type !== 'all-export'
				) {
					this.$message.error({
						message: '请先勾选',
						showClose: true,
					});
				}
			}
			if (type === 'list-export' || type === 'all-export') {
				exporthandel(
					type === 'list-export'
						? 'ProduceOrder/Export'
						: 'ProduceOrder/ExportAll',
					this.search
				);
			}
			// 点击刷新
			if (type === 'refresh') {
				this.getproductOrder();
			}
		},
		// 顶部操作方法-公共部分封装下
		toolarFn(path, newArry, detailsIds) {
			let formdata = detailsIds
				? {
						ids: newArry,
						detailsIds: detailsIds,
				  }
				: { ids: newArry };
			this.$http.post(path, formdata).then((res) => {
				if (res.status === 200) {
					this.dialogVisible = true;
					this.tableInfo = res.data;
					this.search.pageNo = 1;
					this.getproductOrder();
				}
			});
		},
		// 下单日期改变
		time1Chang(value) {
			if (value && value.length > 0) {
				this.search.orderBeginDate = value[0];
				this.search.orderEndDate = value[1];
			} else {
				this.search.orderBeginDate = '';
				this.search.orderEndDate = '';
			}
		},
		// 期望日期改变
		c(value) {
			if (value && value.length > 0) {
				this.search.expectBeginDate = value[0];
				this.search.expectEndDate = value[1];
			} else {
				this.search.expectBeginDate = '';
				this.search.expectEndDate = '';
			}
		},
		// 订单号 复制按钮
		saleOrderCopy() {
			orderCopy();
		},
		// 搜索事件
		searchData() {
			this.search.pageNo = 1;
			this.getproductOrder();
		},
		headerRigthMethod({ row, column, rowIndex, columnIndex }) {
			return 'headerRight';
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		handleSizeChange(val) {
			this.search.pageNo = 1;
			this.search.pageSize = val;
			this.Init();
		},
		handleCurrentChange(val) {
			this.search.pageNo = val;
			this.Init();
		},
	},
};
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderList.scss';
@import '@/assets/style/saleOrder/common.scss';
</style>
