<template>
	<div class="main-container order-mc-bg">
		<div class="purchase-container">
			<toolBtn @actionhandel="actionhandel" :btnType="btnType"></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="purchase-page-body">
				<div class="purchase-page-table-header">
					<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
												v-model.trim="orderNumber"
												@keyup.enter="searchList"
												:oninput="
													(orderNumber = orderNumber
														.toString()
														.replace(
															/(^\s*)|(\s*$)/g,
															''
														))
												"
												@input="
													searchCom(
														orderNumber,
														'billNo',
														'ipt'
													)
												"
												placeholder="请输入组织间需求订单号"
												class="f_12"
											></el-input>
											<div
												:data-clipboard-text="
													orderNumber
												"
												@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
												v-model="billVal"
												placeholder="选择状态"
												@change="
													clearCom(
														billVal,
														'documentStatus'
													)
												"
												:clearable="true"
											>
												<el-option
													class="f_12"
													@click="
														searchCom(
															billVal,
															'documentStatus',
															'opt'
														)
													"
													v-for="item in statusForm.bills"
													:key="item.id"
													:label="item.name"
													:value="item.id"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item label="下单日期">
											<el-date-picker
												class="f_12"
												v-model="modelValue"
												@change="
													dateCom(
														modelValue,
														'beginDate',
														'endDate'
													)
												"
												value-format="YYYY-MM-DD"
												format="YYYY-MM-DD"
												type="daterange"
												start-placeholder="开始时间"
												end-placeholder="结束时间"
											></el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label="接单组织">
											<el-select
												v-model="salepersonVal"
												placeholder="选择组织"
												@change="
													clearCom(
														salepersonVal,
														'receptOrgId'
													)
												"
												:clearable="true"
											>
												<el-option
													class="f_12"
													@click="
														searchCom(
															salepersonVal,
															'receptOrgId',
															'opt'
														)
													"
													v-for="item in statusForm.receptOrgs"
													:key="item.id"
													:label="item.name"
													:value="item.id"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item
											class="Iisshow"
											label="产品"
										>
											<el-input
												v-model.trim="product"
												@input="
													searchCom(
														product,
														'productKey',
														'ipt'
													)
												"
												:oninput="
													(product = product
														.toString()
														.replace(
															/(^\s*)|(\s*$)/g,
															''
														))
												"
												@keyup.enter="searchList"
												placeholder="请输入物料名称/编码/SKU"
												class="f_12"
											></el-input>
											<div
												:data-clipboard-text="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
												class="alias-open"
												@click="openRow"
											>
												<span
													class="iconfont"
													:class="[
														isDown
															? 'icon-shuangjiantouzhankai-xia'
															: 'icon-shuangjiantoushouqi-shang',
													]"
												></span>
											</div>
											<el-button
												size="small"
												@click="resetSearch"
												>重置</el-button
											>
											<el-button
												type="primary"
												size="small"
												@click="searchList"
												>搜索</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="3">
										<el-form-item
											class="Iisshow"
											label="已收数量"
										>
											<el-input
												v-model="transferQtyBegin"
												placeholder="起始值"
												@input="
													numberRexgu(
														transferQtyBegin,
														'transferQtyBegin',
														'transferQtyEnd'
													)
												"
												@keyup.enter="searchList"
												@blur="
													clearZero(
														transferQtyBegin,
														'transferQtyBegin',
														'transferQtyEnd'
													)
												"
												:maxlength="15"
												class="f-12"
											></el-input>
											<!-- <div :data-clipboard-text="transferQtyBegin" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>-->
										</el-form-item>
									</el-col>
									<el-col :span="3">
										<el-form-item
											label="——"
											class="Iisshow"
										>
											<el-input
												v-model="transferQtyEnd"
												placeholder="结束值"
												@keyup.enter="searchList"
												@blur="
													clearZero(
														transferQtyEnd,
														'transferQtyEnd',
														'transferQtyBegin'
													)
												"
												@input="
													numberRexgu(
														transferQtyEnd,
														'transferQtyEnd',
														'transferQtyBegin'
													)
												"
												:maxlength="15"
												class="f-12"
											></el-input>
											<!-- <div :data-clipboard-text="transferQtyEnd" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>-->
										</el-form-item>
									</el-col>
									<el-col :span="3">
										<el-form-item
											class="Iisshow"
											label="未收数量"
										>
											<el-input
												v-model="untransferQtyBegin"
												placeholder="起始值"
												@input="
													numberRexgu(
														untransferQtyBegin,
														'untransferQtyBegin',
														'untransferQtyEnd'
													)
												"
												@keyup.enter="searchList"
												@blur="
													clearZero(
														untransferQtyBegin,
														'untransferQtyBegin',
														'untransferQtyEnd'
													)
												"
												:maxlength="15"
												class="f-12"
											></el-input>
											<!-- <div :data-clipboard-text="untransferQtyBegin" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>-->
										</el-form-item>
									</el-col>
									<el-col :span="3">
										<el-form-item
											label="——"
											class="Iisshow"
										>
											<el-input
												v-model="untransferQtyEnd"
												placeholder="结束值"
												@keyup.enter="searchList"
												@blur="
													clearZero(
														untransferQtyEnd,
														'untransferQtyEnd',
														'untransferQtyBegin'
													)
												"
												@input="
													numberRexgu(
														untransferQtyEnd,
														'untransferQtyEnd',
														'untransferQtyBegin'
													)
												"
												:maxlength="15"
												class="f-12"
											></el-input>
											<!-- <div :data-clipboard-text="untransferQtyEnd" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>-->
										</el-form-item>
									</el-col>
								</el-row>
								<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"
												@result="
													resultCom(
														$event,
														'customerSel1',
														'customerObj1',
														'tempObj1'
													)
												"
												:key="compKey1"
												:reset="reset"
											></CustomCondition>
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item label="自定义条件2">
											<CustomCondition
												:getCustomerItem="statusForm"
												@result="
													resultCom(
														$event,
														'customerSel2',
														'customerObj2',
														'tempObj2'
													)
												"
												:key="compKey2"
												:reset="reset"
											></CustomCondition>
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item label="自定义条件3">
											<CustomCondition
												:getCustomerItem="statusForm"
												@result="
													resultCom(
														$event,
														'customerSel3',
														'customerObj3',
														'tempObj3'
													)
												"
												:key="compKey3"
												:reset="reset"
											></CustomCondition>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<div
					class="purchase-page-table-body"
					:style="{ height: heightNum + 'px' }"
				>
					<el-table
						class="table-box"
						:data="tableData"
						border
						ref="tableInfoRef"
						v-loading="tableLoading"
						@row-click="openDetails"
						@row-dblclick="openDetailsDB"
						style="width: 100%; font-size: 12px"
						:max-height="heightNum"
						:header-cell-class-name="headerRigthMethod"
						:header-cell-style="headerBg"
						:cell-style="tableColumnClassName"
						@selection-change="handleSelectionChange"
					>
						<el-table-column
							type="selection"
							align="center"
							fixed
							width="40"
						/>
						<el-table-column
							prop="saleOrderNo"
							label="销售订单号"
							fixed
							align="left"
							width="187"
						>
							<template #default="scope">
								<span>{{ scope.row.saleOrderNo }}</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="billNo"
							label="组织间需求单号"
							fixed
							align="left"
							width="172"
						>
							<template #default="scope">
								<span>{{ scope.row.billNo }}</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="materialNumber"
							label="物料编码"
							align="left"
							fixed
							width="150"
						/>
						<el-table-column
							prop="specification"
							label="规格型号(SKU)"
							fixed
							align="left"
							width="280"
						/>
						<el-table-column
							prop="materialName"
							label="物料名称"
							fixed
							align="left"
							width="120"
						/>
						<el-table-column
							prop="documentStatus"
							label="单据状态"
							fixed
							align="center"
							width="72"
						/>
						<el-table-column
							prop="isClosed"
							label="关闭状态"
							align="center"
							width="72"
						/>
						<el-table-column
							prop="orderQty"
							label="下单数量"
							align="right"
							width="100"
						/>
						<el-table-column
							prop="orderDate"
							label="下单日期"
							align="left"
							width="83"
						/>
						<el-table-column
							prop="hopeFinishDate"
							label="期望交期"
							align="left"
							width="83"
						/>
						<el-table-column
							prop="is211"
							label="是否211"
							align="center"
							width="72"
						/>
						<el-table-column
							prop="supplyChain"
							label="供应链"
							align="center"
							width="72"
						/>
						<el-table-column
							prop="receptOrgName"
							align="left"
							label="接单组织"
							width="172"
						/>
						<el-table-column
							prop="deliveredQty"
							align="right"
							label="已交数量"
							width="100"
						>
							<template #default="scope">{{
								(scope.row.deliveredQty =
									scope.row.deliveredQty === null
										? 0
										: scope.row.deliveredQty)
							}}</template>
						</el-table-column>
						<el-table-column
							prop="undeliveredQty"
							align="right"
							label="未交数量"
							width="100"
						>
							<template #default="scope">{{
								(scope.row.undeliveredQty =
									scope.row.undeliveredQty === null
										? 0
										: scope.row.undeliveredQty)
							}}</template>
						</el-table-column>
						<el-table-column
							prop="transferQty"
							align="right"
							label="已收数量"
							width="100"
						>
							<template #default="scope">{{
								(scope.row.transferQty =
									scope.row.transferQty === null
										? 0
										: scope.row.transferQty)
							}}</template>
						</el-table-column>
						<el-table-column
							prop="untransferQty"
							align="right"
							label="未收数量"
							width="100"
						>
							<template #default="scope">{{
								(scope.row.untransferQty =
									scope.row.untransferQty === null
										? 0
										: scope.row.untransferQty)
							}}</template>
						</el-table-column>
						<el-table-column
							prop="stockName"
							align="left"
							label="仓库"
							width="120"
						/>
						<el-table-column
							prop="description"
							label="备注"
							align="left"
							width="280"
						/>
					</el-table>
				</div>
			</div>
			<!-- 操作结果 -->
			<el-dialog title="操作结果" v-model="dialogVisible" width="40%">
				<div class="sale-page-table-body">
					<el-table
						class="table-box"
						:data="tableInfo"
						height="300"
						border
						:header-cell-class-name="headerRigthMethod"
						id="tableInfo-table"
					>
						<el-table-column prop="date" label="序号" width="50">
							<template #default="scope">
								<span>{{ scope.$index + 1 }}</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="orderNo"
							label="组织间需求单"
							width="200"
						></el-table-column>
						<el-table-column prop="a" label="指令" 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 prop="msg" label="信息">
							<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
							size="small"
							@click="
								handelhtmlToExcel(
									'tableInfo-table',
									'操作结果'
								);
								dialogVisible = false;
							"
							>导 出</el-button
						>
						<el-button
							type="primary"
							size="small"
							@click="dialogVisible = false"
							>关 闭</el-button
						>
					</span>
				</template>
			</el-dialog>
			<!-- 底部 -->
			<div
				class="purchase-page-footer"
				:style="{ marginTop: footerMg + 'px' }"
			>
				<div class="footer-left">
					<div>
						<span>下单数量:</span>
						<span class="sale-number-color">{{
							orderQtyTotal
						}}</span>
					</div>
					<div>
						<span>已交数量:</span>
						<span class="sale-number-color">{{
							deliveredQtyTotal
						}}</span>
					</div>
					<div>
						<span>未交数量:</span>
						<span class="sale-number-color">{{
							undeliveredQtyTotal
						}}</span>
					</div>
					<div>
						<span>已收数量:</span>
						<span class="sale-number-color">{{
							transferQtyTotal
						}}</span>
					</div>
					<div>
						<span>未收数量:</span>
						<span class="sale-number-color">{{
							untransferQtyTotal
						}}</span>
					</div>
				</div>
				<div class="footer-right">
					<el-pagination
						:page-sizes="pagingList"
						:page-size="pageSize"
						layout="slot,sizes,total, prev,pager, next,jumper"
						:total="totalCount"
						popper-class="每页显示"
						:pager-count="5"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					>
						<span class="total-select-item">
							共选中
							<text
								style="
									text-align: center;
									color: #4178d5;
									padding: 0 1px;
								"
								>{{ selectItem }}</text
							>行
						</span>
					</el-pagination>
				</div>
				<div class="footer-pagination-total-page">
					<span>共{{ totalPageNumber }}页</span>
				</div>
			</div>
			<!-- 选择 下推单据 -->
			<el-dialog
				title="选择下推单据"
				v-model="dialogxt"
				width="20%"
				top="15%"
			>
				<el-radio-group v-model="pushdownVal">
					<el-radio
						v-for="item in pushDownList"
						:key="item.id"
						:value="item.id"
						:label="item.id"
						>{{ item.value }}</el-radio
					>
				</el-radio-group>
				<template #footer>
					<span class="dialog-footer">
						<el-button size="small" @click="dialogxt = false"
							>取 消</el-button
						>
						<el-button
							type="primary"
							size="small"
							@click="sumitPushdown(pushdownVal)"
							>确 定</el-button
						>
					</span>
				</template>
			</el-dialog>
			<!-- 选择 上下查单据 -->
			<el-dialog
				:title="CXttile"
				v-model="dialogCX"
				width="20%"
				top="15%"
			>
				<div class="sale-page-table-body">
					<el-radio-group
						v-model="CXcheckVal"
						v-if="CXttile === '上查结果'"
					>
						<el-radio
							:label="it.orderType"
							v-for="(it, index) in upOrDownList"
							:key="index"
							>{{ it.orderName }}({{ it.orderCount }})</el-radio
						>
					</el-radio-group>
					<el-radio-group
						v-model="CXcheckVal"
						v-if="CXttile === '下查结果'"
					>
						<el-radio
							:label="it.orderType"
							v-for="(it, index) in upOrDownList"
							:key="index"
							>{{ it.orderName }}({{ it.orderCount }})</el-radio
						>
					</el-radio-group>
				</div>
				<template #footer>
					<span class="dialog-footer">
						<el-button size="small" @click="dialogCX = false"
							>取 消</el-button
						>
						<el-button type="primary" size="small" @click="submitCX"
							>确 定</el-button
						>
					</span>
				</template>
			</el-dialog>
		</div>
	</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { toRaw } from '@vue/reactivity';
import { orderCopy } from '@/utils/takeMethods';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
	getStatusType,
	moreEnpty,
	exporthandel,
	htmlToExcel,
	resultComMethods,
	customChangeMethods,
} from '@/utils/pubulic.js';
import CustomCondition from '@/components/public/CustomCondition.vue';
export default {
	name: 'OrgNeeds',
	components: {
		CustomCondition,
	},
	data() {
		return {
			windowHeight: 0, // 获取屏幕高度
			tableLoading: false,
			heightNum: 0, // 容器高度
			rowShow: false, // 显示自定义搜索
			isDown: true, // 搜索展开按钮
			pagingList: [50, 100, 150], // 底部 N/页
			pageSize: 50, // N/页
			pageNo: 1, // 当前的页签
			totalCount: 0, // 总计条数
			totalPageNumber: 0, // 通过条目数计算页数
			selectItem: 0, // 选中的条目总计
			multipleSelection: [], // 选中的条目arr
			orderNumber: '', // 订单号
			billVal: '', // 单据状态
			modelValue: null, // 下单日期
			salepersonVal: '', // 接单组织
			product: '', // 产品
			orderVal: '', // 订单类型
			orderQtyTotal: '', // 下单数量
			deliveredQtyTotal: '', // 已交数量
			undeliveredQtyTotal: '', // 未交数量
			transferQtyTotal: '', // 已收数量
			untransferQtyTotal: '', // 未收数量
			transferQtyBegin: '',
			transferQtyEnd: '',
			untransferQtyBegin: '',
			untransferQtyEnd: '',
			reset: false,
			customerSel1: '', // 条件 待抽取
			customerSel2: '',
			customerSel3: '',
			customerObj1: null,
			customerObj2: null,
			customerObj3: null,
			tempObj1: null,
			tempObj2: null,
			tempObj3: null,
			compKey1: 0,
			compKey2: 0,
			compKey3: 0,
			statusForm: {
				// 自定义条件 订单类型 单据状态 供应组织 是否211 是否赠品 关闭状态
				customCondition: [], // 自定义条件
				bills: [], // 单据状态
				is211: [], // 是否211
				cloStatus: [], // 关闭状态
				warehouse: [], // 仓库
				childWarehouse: [], // 仓位
				qcPerson: [], // 跟单员
				supplyChainType: [], // 供应链
				supplys: [], // 供应组织
				closeStatus: [], // 关闭状态
				receptOrgs: [], // 接单组织
				dataSourceTypes: [], //数据来源
			},
			tableData: [], // 表格对数据
			btnType: [
				'exDetails',
				'save',
				'print-brower',
				'split-order',
				'print-aterial-list',
				'finish',
				'close-case',
				'de-excute-start',
				'de-excute-finish',
				's-p-t-g7',
				's-p-t-g8',
				's-p-t-g9',
				's-p-t-g10',
			], // 不需要显示的顶部按钮类型
			search: {
				// 搜索对象
				pageNo: 1,
				pageSize: 50,
				transferQtyBegin: null,
				transferQtyEnd: null,
				untransferQtyBegin: null,
				untransferQtyEnd: null,
				orgId:
					this.$store.state &&
					this.$store.state.org &&
					this.$store.state.org.orgId === ''
						? this.orgIdArr[0].id
						: this.$store.state.org.orgId,
				extention: {},
			},
			dialogVisible: false, // 操作弹框显示
			tableInfo: [], // 操作结果
			actionType: '', // 操作类型
			pushdownVal: null, // 下推选择
			dialogxt: false, // 选择下推单据弹框显示
			OrdedetailIds: [], // 勾选的明细id集合
			dialogCX: false, // 上下查弹框控制
			upOrDownList: [], // 上查下查弹窗可选数据
			OrderNoNameslist: [], // 上查下查的订单号
			OrderNoNameStr: '', // 上查下查的订单号
			CXaction: '', // 判断是上查还是下查
			CXttile: '', // 查询弹框的名称
			CXcheckVal: '', // 选择的查询radio
			OrderNoNames: [], // 选择的单据订单号集合
			pushDownList: [
				// 下推集合
				{ id: 1, value: '生产订单' },
				{ id: 2, value: '委外订单' },
				{ id: 3, value: '采购订单' },
				{ id: 4, value: '组织间需求单' },
				{ id: 5, value: '分步式调出单' },
			],
			isTrue: false,
		};
	},
	methods: {
		// 操作弹框导出
		handelhtmlToExcel(domid, title) {
			htmlToExcel(domid, title);
		},
		// 自定义条件赋值
		resultCom(result, fieldSale, fieldObj, tempObj) {
			let returnResult = resultComMethods(
				result,
				this[fieldSale],
				toRaw(result.outResult),
				this[tempObj],
				this.search.extention
			);
			this[fieldSale] = returnResult.fieldSale;
			this[fieldObj] = returnResult.fieldObj;
			this[tempObj] = returnResult.tempObj;
			this.search.extention = returnResult.search;
		},
		Init() {
			let vuexKey = ['warehouseAll', 'dicOrgani'];
			let setVuexData = ['setWarehouseAll', 'setDicOrgani'];
			let requestQueryUrl = [
				'SysConfig/GetWarehouse',
				'Dictionary/organization',
			];
			let resDataQuery = ['warehouse', 'customCondition'];

			vuexKey.forEach((ele, ind) => {
				if (this[vuexKey[ind]] && this[vuexKey[ind]].length > 0) {
					if (typeof resDataQuery[ind] == 'string') {
						this.statusForm[resDataQuery[ind]] = JSON.parse(
							JSON.stringify(this[vuexKey[ind]])
						);
					} else {
						resDataQuery[ind].forEach((ele, index) => {
							this.statusForm[resDataQuery[ind][index]] =
								JSON.parse(JSON.stringify(this[vuexKey[ind]]));
						});
					}
					if (vuexKey[ind] == 'unitAll') {
						this.unitData = this.statusForm[resDataQuery[ind]];
					}
				} else {
					this.$http.get(requestQueryUrl[ind]).then((r) => {
						if (r.status === 200) {
							if (typeof resDataQuery[ind] == 'string') {
								this.statusForm[resDataQuery[ind]] = r.data;
								this[setVuexData[ind]](
									this.statusForm[resDataQuery[ind]]
								);
							} else {
								resDataQuery[ind].forEach((ele, index) => {
									this.statusForm[resDataQuery[ind][index]] =
										r.data;
									this[setVuexData[ind]](
										this.statusForm[
											resDataQuery[ind][index]
										]
									);
								});
							}
						}
					});
				}
			});

			if (
				this.listGetStatus &&
				JSON.stringify(this.listGetStatus) !== '{}'
			) {
				for (const key in this.listGetStatus.documentStatus) {
					// 单据状态
					this.statusForm.bills.push({
						id: key,
						name: this.listGetStatus.documentStatus[key],
					});
				}
				for (const key in this.listGetStatus.closeStatus) {
					// 关闭的状态
					this.statusForm.cloStatus.push({
						id: key,
						name: this.listGetStatus.closeStatus[key],
					});
				}
				for (const key in this.listGetStatus.is211) {
					// 是否211
					this.statusForm.is211.push({
						id: key,
						name: this.listGetStatus.is211[key],
					});
				}
				for (const key in this.listGetStatus.supplyChainType) {
					// 供应链
					this.statusForm.supplyChainType.push({
						id: key,
						name: this.listGetStatus.supplyChainType[key],
					});
				}
				for (const key in this.listGetStatus.dataSourceType) {
					// 数据来源
					this.statusForm.dataSourceTypes.push({
						id: key,
						name: this.listGetStatus.dataSourceType[key],
					});
				}
			} else {
				this.$http.get('SysConfig/GetStatus').then((req) => {
					// 获取各种状态
					if (req.status == 200) {
						this.setListGetStatus(req.data);
						for (const key in req.data.documentStatus) {
							// 单据状态
							this.statusForm.bills.push({
								id: key,
								name: req.data.documentStatus[key],
							});
						}
						for (const key in req.data.closeStatus) {
							// 关闭的状态
							this.statusForm.cloStatus.push({
								id: key,
								name: req.data.closeStatus[key],
							});
						}
						for (const key in req.data.is211) {
							// 是否211
							this.statusForm.is211.push({
								id: key,
								name: req.data.is211[key],
							});
						}
						for (const key in req.data.supplyChainType) {
							// 供应链
							this.statusForm.supplyChainType.push({
								id: key,
								name: req.data.supplyChainType[key],
							});
						}
						for (const key in req.data.dataSourceType) {
							// 数据来源
							this.statusForm.dataSourceTypes.push({
								id: key,
								name: req.data.dataSourceType[key],
							});
						}
					}
				});
			}

			this.windowHeight = document.documentElement.clientHeight;
			if (this.$route.query.detailsIds) {
				this.heightNum = this.windowHeight - 301; // 计算表格高度
			} else {
				this.heightNum = this.windowHeight - 258; // 计算表格高度
			}
			this.containerHeight = this.windowHeight - 102;
			this.footerMg = 0;
			this.statusForm.receptOrgs = this.orgIdArr; // 获取接单组织
			this.statusForm.supplys = this.orgIdArr; // 获取供应组织
			if (this.$store.state.org.orgId) {
				this.search.orgId = this.$store.state.org.orgId;
			}
			this.getList(this.search);
		},
		dateCom(val, keyS, keyE) {
			// 下单日期
			if (!val) {
				delete this.search[keyS];
				delete this.search[keyE];
			} else {
				this.search[keyS] = val[0];
				this.search[keyE] = val[1];
			}
		},
		// 验证输入百分比是数字，0，或者小数，首位不允许多个0
		numberRexgu(value, key, eKey) {
			if (value) {
				if (value.toString().indexOf('.') != -1) {
					let value_after = parseInt(
						value.toString().substring(0, value.indexOf('.'))
					);
					let value_before = value.replace(/\d+\.(\d*)/, '$1');
					if (value_after.toString().length > 8) {
						let newValue =
							value_after.toString().substring(0, 8) +
							'.' +
							value_before;
						this[key] = (newValue
							.toString()
							.match(/\d{1,8}(\.\d{0,6})?/) || [''])[0];
					} else {
						this[key] = (value
							.toString()
							.match(/\d{1,8}(\.\d{0,6})?/) || [''])[0];
					}
				}
				this[key] = (value.toString().match(/\d{1,8}(\.\d{0,6})?/) || [
					'',
				])[0];
				// 当结束值 小于 开始值 的时候 == 开始值
				// if(key == 'transferQtyEnd' || key == 'untransferQtyEnd'){
				//   if(this[key] < this[eKey]){
				//     this[key] = this[eKey]
				//   }
				// }
				// if(key == 'transferQtyBegin' || key == 'untransferQtyBegin'){
				//   if(this[eKey]){
				//     if(this[key] > this[eKey]){
				//       this[key] = this[eKey]
				//     }
				//   }
				// }
				if (this[key]) {
					this.search[key] = moreEnpty(this[key]) * 1;
					this.search[key] = this[key] * 1;
				}
			} else {
				this.search[key] = null;
				this[key] = null;
			}
		},
		// 去0
		clearZero(value, key, eKey) {
			if (value) {
				this[key] = value * 1;
				// if(key == 'transferQtyEnd' || key == 'untransferQtyEnd'){
				//   if(this[key] < this[eKey]){
				//     this[key] = this[eKey]
				//   }
				// }
				if (this[key]) {
					this.search[key] = moreEnpty(this[key]);
					this.search[key] = this[key];
				}
			}
		},
		clearCom(val, key) {
			// 清空方法
			if (!val) {
				delete this.search[key];
			}
		},
		searchCom(val, key, type) {
			// 搜索共用方法
			if (!val) {
				delete this.search[key];
			} else {
				if (type === 'ipt') {
					this.search[key] = moreEnpty(val);
				}
				this.search[key] = val;
			}
			if (type === 'opt') {
				this.searchList();
			}
		},
		actionhandel(type) {
			// 顶部公共按钮操作
			this.actionType = type;
			if (type === 'add') {
				// 点击新增
				this.$router.push({
					path: '/purchase/demand/createOrgNeeds',
					query: { type: 'add', id: '', sjtag: Math.random() * 36 },
				});
			}
			if (this.multipleSelection && this.multipleSelection.length > 0) {
				let nweArysize = 0;
				let newArry = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.id;
						})
					),
				];
				let closArr = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.documentStatus;
						})
					),
				];
				let detailsIds = [
					...new Set(
						this.multipleSelection.map((item) => {
							return item.id;
						})
					),
				];
				this.OrdedetailIds = [];
				this.OrdedetailIds = detailsIds;
				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: '/purchase/demand/createOrgNeeds',
							query: {
								type: 'copy',
								id: this.multipleSelection[0].id,
								sjtag: Math.random() * 36,
							},
						});
					}
				}

				if (type === 'submit') {
					// 点击提交
					this.toolarFn('Organization/submit/status', newArry);
				}
				if (type === 'revoke') {
					// 点击撤销
					this.toolarFn('Organization/revoke', newArry);
				}
				if (type === 'audit') {
					// 点击审核
					this.toolarFn('Organization/check', newArry);
				}

				if (type === 'de-approval') {
					// 点击反审核
					this.toolarFn('Organization/recheck', newArry);
				}

				if (type === 'delet') {
					// 点击删除
					this.toolarFn('Organization/delete', newArry);
				}

				if (type === 'close') {
					// 点击关闭
					this.closeOrder(
						'Organization/close',
						newArry,
						detailsIds,
						type,
						closArr,
						'关闭'
					);
				}

				if (type === 'de-close') {
					// 点击反关闭
					this.closeOrder(
						'Organization/reclose',
						newArry,
						detailsIds,
						type,
						closArr,
						'反关闭'
					);
				}
				if (type === 'list-export') {
					// 列表字段导出
					this.toolarFn();
				}
				if (type === 'all-export') {
					// 全部字段导出
					this.toolarFn();
				}
				if (type === 'push-down') {
					// 点击下推
					if (detailsIds.length <= 20) {
						if (
							this.multipleSelection.filter((it) => {
								return it.documentStatus !== '已审核';
							}).length > 0
						) {
							this.$message.error({
								message:
									'单据状态错误，只能选择单据状态为已审核单据，请重新选择！',
								showClose: true,
							});
						} else {
							this.dialogxt = true;
						}
					} else {
						this.$message.warning({
							message: '最多一次性下推二十条明细',
							showClose: true,
						});
					}
				}
				if (type === 'up-check') {
					// 点击查询--上查
					if (detailsIds.length > 0) {
						this.$http
							.post('Organization/upper', { ids: detailsIds })
							.then((res) => {
								if (res.status === 200) {
									if (
										res.data.length === 0 ||
										res.data === []
									) {
										this.$message.warning({
											message: '没有可上查的单据！',
											showClose: true,
										});
									} else {
										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; //只有一个，就个默认值
									}
								}
							});
					} else {
						this.$message.warning({
							message:
								'请先勾选明细,并确认勾选的信息是否有保存提交,只有有效明细信息才能上查',
							showClose: true,
						});
					}
				}
				if (type === 'down-check') {
					// 点击查询--下查
					this.$http
						.post('Organization/lower', { ids: detailsIds })
						.then((res) => {
							if (res.status === 200) {
								if (res.data.length === 0 || res.data === []) {
									this.$message.warning({
										message: '没有可下查的单据!',
										showClose: true,
									});
								} else {
									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; //只有一个，就个默认值
								}
							}
						});
				}
			} 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'
						? 'Organization/Export'
						: 'Organization/ExportAll',
					this.search
				);
			}
			if (type === 'refresh') {
				// 点击刷新
				this.getList(this.search);
			}
		},
		async closeOrder(path, newArry, detailsIds, type, closArr, val) {
			if (type === 'close' || type === 'de-close') {
				this.isTrue = true;
				await closArr.forEach((element) => {
					if (element != '已审核') {
						this.$message.warning({
							message: '请选择已审核的单据行进行关闭!',
							showClose: true,
						});
						this.isTrue = false;
					}
				});
				if (this.isTrue) {
					let formdata = detailsIds
						? { ids: detailsIds }
						: { ids: newArry };
					ElMessageBox.confirm(
						'你确认要' + val + '所选单据行',
						'操作确认',
						{
							confirmButtonText: '确认',
							cancelButtonText: '取消',
							type: 'Success',
						}
					)
						.then(() => {
							this.$http.post(path, formdata).then((res) => {
								if (res.status === 200) {
									ElMessage({
										type: 'success',
										message: val + '成功',
										showClose: true,
									});
									this.getList(this.search);
								} else {
									ElMessage({
										type: 'info',
										message: res.data[0].msg,
										showClose: true,
									});
								}
							});
						})
						.catch(() => {
							ElMessage({
								type: 'info',
								message: '取消' + val,
								showClose: true,
							});
						});
				}
			}
		},
		toolarFn(path, newArry, detailsIds, type) {
			// 顶部操作方法
			let formdata = detailsIds ? { ids: detailsIds } : { ids: newArry };
			this.$http.post(path, formdata).then((res) => {
				if (res.status === 200) {
					this.dialogVisible = true;
					this.tableInfo = res.data;
					this.getList(this.search);
				}
			});
		},
		sumitPushdown(id) {
			// 下推确定
			this.CXcheckVal = id;
			if (id) {
				let pathName = '';
				let routerName = '';
				let type = '';
				if (this.CXcheckVal === 1) {
					// "生产订单"
					pathName = 'Organization/push/produce';
					routerName = 'ProductOrderCreate';
				}
				if (this.CXcheckVal === 3) {
					// "采购订单"
					pathName = 'Organization/push/purchase';
					routerName = 'CreatePurchase';
					type = 'y';
				}
				if (this.CXcheckVal === 2) {
					// "委外订单"
					pathName = 'Organization/push/outsource';
					routerName = 'AddOutSourcOrder';
				}
				if (this.CXcheckVal === 4) {
					// "组织间需求单"
					pathName = 'Organization/push/self/';
					routerName = 'CreateOrgNeeds';
				}
				if (this.CXcheckVal === 5) {
					// "分步式调出单"
					pathName = 'Organization/push/transferout';
					routerName = 'ActiveIssue';
				}
				if (this.CXcheckVal === 4) {
					if (this.OrdedetailIds.length === 1) {
						this.$http
							.post(pathName + this.OrdedetailIds)
							.then((res) => {
								if (res.status === 200) {
									this.dialogxt = false;
									this.$router.push({
										name: routerName,
										query: {
											type: 'pushDown',
											pushDownData: JSON.stringify(
												res.data
											),
											sjtag: Math.random() * 36,
										},
									});
								} else {
									this.dialogxt = false;
								}
							});
					} else {
						this.$message.error({
							message: '组织间需求单不允许多条合并下推!',
							showClose: true,
						});
					}
				} else {
					if (type == 'y') {
						this.$http
							.post(pathName, { ids: this.OrdedetailIds })
							.then((res) => {
								if (res.status === 200) {
									this.dialogxt = false;
									this.$router.push({
										name: routerName,
										query: {
											type: 'pushDown',
											pushDownData: JSON.stringify(
												res.data
											),
											typeId: 1,
											pushType: type,
											sjtag: Math.random() * 36,
										},
									});
								} else {
									this.dialogxt = false;
								}
							});
					} else {
						this.$http
							.post(pathName, { ids: this.OrdedetailIds })
							.then((res) => {
								if (res.status === 200) {
									this.dialogxt = false;
									this.$router.push({
										name: routerName,
										query: {
											type: 'pushDown',
											pushDownData: JSON.stringify(
												res.data
											),
											typeId: 1,
											sjtag: Math.random() * 36,
										},
									});
								} else {
									this.dialogxt = false;
								}
							});
					}
				}
			} else {
				this.$message.error({
					message: '请先选中在确认',
					showClose: true,
				});
			}
		},
		submitCX() {
			// 确定上下查
			if (this.CXcheckVal) {
				let pathName = '';
				if (this.CXcheckVal === 1) {
					// "生产"
					pathName = 'ProductOrder';
				}
				if (this.CXcheckVal === 3) {
					// "委外"
					pathName = 'OutsourcOrder';
				}
				if (this.CXcheckVal === 2) {
					// "采购"
					pathName = 'DemandOrder';
				}
				if (this.CXcheckVal === 20) {
					// "分步式"
					pathName = 'WarehouseAllocationkissue';
				}
				if (this.CXcheckVal === 10) {
					// "组织间需求"
					pathName = 'OrgNeeds';
				}
				// "销售订单"
				if (this.CXcheckVal === 7) {
					pathName = 'SaleOrder';
				}

				let ary = [];
				ary = this.upOrDownList.filter((it) => {
					return it.orderType === this.CXcheckVal;
				});
				if (pathName) {
					this.dialogCX = false;
					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[0].billNos),
						},
					});
					this.dialogCX = false;
				}
			} else {
				this.$message.error({
					message: '请先选择在确认',
					showClose: true,
				});
			}
		},
		getcheckInfo() {
			// 上下查数据
			if (this.$route.query) {
				let ordNostr = '';
				this.search.detailsIds = this.$route.query.detailsIds
					? JSON.parse(
							decodeURIComponent(this.$route.query.detailsIds)
					  )
					: [];
				this.CXaction =
					this.$route.query.actionType === 'up' ? '上查' : '下查';
				this.OrderNoNameslist = this.$route.query.OrderNoNames
					? JSON.parse(
							decodeURIComponent(this.$route.query.OrderNoNames)
					  )
					: [];
				if (this.OrderNoNameslist.length > 0) {
					this.heightNum = this.heightNum - 36;
				}
				if (this.OrderNoNameslist) {
					this.OrderNoNameslist.forEach((it, index) => {
						if (index < 5) {
							ordNostr = ordNostr + it + ',';
						}
					});
				}
				this.OrderNoNameStr = ordNostr;
			}
		},
		handleSelectionChange(val) {
			// 表格选中条目发生改变
			this.selectItem = val.length;
			this.multipleSelection = val;
		},
		handleSizeChange(val) {
			// 每页条数
			this.pageSize = val;
			this.search.pageSize = val;
			this.totalPageNumber = Math.ceil(this.totalCount / this.pageSize);
			this.getList(this.search);
		},
		handleCurrentChange(val) {
			// 分页当前页切换
			this.pageNo = val;
			this.search.pageNo = val;
			this.getList(this.search);
		},
		headerBg({ row, column, rowIndex, columnIndex }) {
			// 顶部字段居右
			if (
				columnIndex === 13 ||
				columnIndex === 14 ||
				columnIndex === 15
			) {
				return `text-align:right!important;`;
			} else if (columnIndex === 9 || columnIndex === 10) {
				return `text-align:center!important;`;
			}
		},
		headerRigthMethod({ row, column, rowIndex, columnIndex }) {
			return 'headerRight';
		},
		openRow() {
			// 展开行
			this.isDown = !this.isDown;
			this.rowShow = !this.rowShow;
			if (this.rowShow) {
				this.heightNum = this.heightNum - 80;
			} else {
				this.heightNum = this.heightNum + 80;
			}
		},
		// 订单号 复制按钮
		saleOrderCopy() {
			orderCopy();
		},
		openDetails(row, column) {
			// 详情跳转
			if (column.property == 'billNo') {
				this.$router.push({
					path: '/purchase/demand/createOrgNeeds',
					query: {
						type: 'details',
						id: row.id,
						status: row.documentStatus,
					},
				});
			}
		},
		openDetailsDB(row, column) {
			// 详情跳转
			this.$router.push({
				path: '/purchase/demand/createOrgNeeds',
				query: {
					type: 'details',
					id: row.id,
					status: row.documentStatus,
				},
			});
		},
		tableColumnClassName({ row, column }) {
			if (column.property == 'billNo') {
				return 'color:#4178D5';
			}
		},
		getList(search) {
			// 获取列表信息
			this.tableLoading = true;
			this.$http.post('Organization/list', search).then((req) => {
				if (req.status == 200) {
					this.tableLoading = false;
					this.tableData = req.data.list;
					this.totalCount = req.data.totalCount; // 列表总条数
					this.orderQtyTotal = req.data.orderQtyTotal; // 下单数量
					this.deliveredQtyTotal = req.data.deliveredQtyTotal; // 已交数量
					this.undeliveredQtyTotal = req.data.undeliveredQtyTotal; // 未交数量
					this.transferQtyTotal = req.data.transferQtyTotal; // 已收数量
					this.untransferQtyTotal = req.data.untransferQtyTotal; // 未收数量
					this.totalPageNumber = Math.ceil(
						this.totalCount / this.pageSize
					);
					if (
						this.multipleSelection.length &&
						this.multipleSelection.length > 0
					) {
						let detailsIds = [
							...new Set(
								this.multipleSelection.map((item) => {
									return item.id;
								})
							),
						];
						this.tableData.forEach((el, ind) => {
							if (detailsIds.indexOf(el.id) !== -1) {
								this.$refs.tableInfoRef.toggleRowSelection(
									this.tableData[ind],
									true
								);
							}
						});
					}
				}
			});
		},
		searchList() {
			// 搜索
			this.getList(this.search);
		},
		resetSearch() {
			// 重置
			let arr = [
				'orderNumber',
				'billVal',
				'modelValue',
				'salepersonVal',
				'product',
			];
			for (let index = 0; index < arr.length; index++) {
				this[arr[index]] = '';
			}
			this.reset = true;
			this.search = {
				pageNo: this.pageNo,
				pageSize: this.pageSize,
				orgId: this.$store.state.org
					? this.$store.state.org.orgId
					: null,
			};
			this.search.detailsIds = [];
			this.search.extention = {};
			this.customerSel1 = '';
			this.customerSel2 = '';
			this.customerSel3 = '';
			if (this.$route.query.detailsIds) {
				this.search.detailsIds = JSON.parse(
					decodeURIComponent(this.$route.query.detailsIds)
				);
			}
			setTimeout(() => {
				this.reset = false;
			}, 200);
			this.searchList();
		},
		...mapActions({
			setWarehouseAll: 'storeData/setWarehouseAll',
			setListGetStatus: 'storeData/setListGetStatus',
			setDicOrgani: 'storeData/setDicOrgani',
		}),
		addListNeeds(event) {
			if (event.keyCode === 13) {
				this.searchList();
			}
		},
	},
	computed: {
		...mapState({
			orgId: (state) => (state && state.user ? state.user.orgId : null),
			orgIdArr: (state) => (state ? state.user.orgIdArr : null),
			getDeptId: (state) => (state ? state.org.orgId : null),
			orgIdChange() {
				// 监听ID
				return this.$store.state.org
					? this.$store.state.org.orgId
					: null;
			},
			warehouseAll: (state) => state.storeData.warehouseAll,
			listGetStatus: (state) => state.storeData.listGetStatus,
			dicOrgani: (state) => state.storeData.dicOrgani,
		}),
	},
	mounted: function () {},
	created: function () {
		this.getcheckInfo();
		this.Init();
	},
	activated() {
		document.addEventListener('keyup', this.addListNeeds, false);
	},
	deactivated() {
		document.removeEventListener('keyup', this.addListNeeds, false);
	},
	watch: {
		// 监听组织发生变化重新获取列表
		orgIdChange: function () {
			this.search.orgId =
				this.$store.state && this.$store.state.org
					? this.$store.state.org.orgId
					: null;
			// if (!this.search.orgId) {
			// 	return;
			// }
			this.getList(this.search);
			this.resetSearch();
		},
		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;
		},
	},
};
</script>
<style lang="scss" scoped>
@import '@/assets/style/purchase/purchaseCommon.scss';
@import '@/assets/style/purchase/orgNeedsList.scss';
@import '@/assets/style/saleOrder/common.scss';
</style>
