<!-- 委外用料设置-->
<template>
	<div
		:style="{ height: heightNum + 'px!important' }"
		class="sale-details-container order-mc-bg main-container"
	>
		<div class="sale-details-btn-group">
			<!-- 顶部按钮 -->
			<toolBtn
				:btnType="btnType"
				:isDisable="isDisable"
				@actionhandel="actionhandel"
			></toolBtn>
		</div>
		<div class="sale-details-base-info">
			<img
				class="reviewIconImg"
				src="../../../assets/reviewed_ico.png"
				v-if="pagefromData.documentStatus === 'c'"
			/>
			<el-tabs style="margin-bottom: 8px" type="border-card">
				<!-- 基本信息 -->
				<el-tab-pane label="基本信息">
					<div class="base-info-form-box">
						<el-form
							:model="pagefromData"
							label-width="80px"
							ref="form"
						>
							<el-row :gutter="10">
								<el-col :span="4">
									<div class="div-col">
										<div class="order-number-bx item-bt-s">
											<el-form-item
												label="委外用料单编号"
											>
												<el-input
													disabled
													placeholder="(保存时自动生成)"
													v-model.trim="
														pagefromData.outSourcMaterialNo
													"
												></el-input>
											</el-form-item>
										</div>
										<el-form-item
											:required="true"
											class="item-bt-s"
											label="委外订单类型"
										>
											<el-select
												disabled
												filterable
												v-model="
													pagefromData.documentType
												"
											>
												<el-option
													:key="key + index"
													:label="value"
													:value="key"
													style="font-size: 12px"
													v-for="(
														value, key, index
													) in documentTypelist"
												></el-option>
											</el-select>
										</el-form-item>
										<div class="order-number-bx item-bt-s">
											<el-form-item
												:required="true"
												label="委外订单号"
											>
												<el-input
													disabled
													placeholder="(保存时自动生成)"
													v-model.trim="
														pagefromData.outSourcOrderNo
													"
												></el-input>
											</el-form-item>
										</div>
										<el-form-item
											:required="true"
											class="item-bt-s"
											label="委外组织"
										>
											<el-select
												disabled
												placeholder="请选择"
												v-model="pagefromData.suborgId"
											>
												<el-option
													:key="item.name"
													:label="item.name"
													:value="item.id"
													class="f-12"
													:style="{
														height: item.disable
															? '0px'
															: 'auto',
													}"
													v-for="item in orgIdArr"
												></el-option>
											</el-select>
										</el-form-item>
									</div>
								</el-col>
								<el-col :span="4">
									<div class="div-col col-2">
										<el-form-item
											class="item-bt-s"
											label="单据状态"
										>
											<el-select
												:disabled="true"
												placeholder="请选择单据状态"
												v-model="
													pagefromData.documentStatus
												"
											>
												<el-option
													:key="key + index"
													:label="value"
													:value="key"
													style="font-size: 12px"
													v-for="(
														value, key, index
													) in documentStatuslist"
												></el-option>
											</el-select>
										</el-form-item>
										<el-form-item
											class="item-bt-s"
											label="供应商"
										>
											<el-select
												disabled
												placeholder="请选择"
												v-model="
													pagefromData.supplierId
												"
											>
												<el-option
													:key="item.name"
													:label="item.name"
													:value="item.id"
													class="f-12"
													:style="{
														height: item.disable
															? '0px'
															: 'auto',
													}"
													v-for="item in supplierlist"
												></el-option>
											</el-select>
										</el-form-item>
										<div class="order-number-bx item-bt-s">
											<el-form-item label="采购订单号">
												<el-input
													disabled
													placeholder="(保存时自动生成)"
													v-model.trim="
														pagefromData.purorderNo
													"
												></el-input>
											</el-form-item>
										</div>
										<el-form-item
											class="item-bt-s item-date"
											label="期望交期"
										>
											<el-date-picker
												disabled
												v-model="
													pagefromData.expectDate
												"
											></el-date-picker>
										</el-form-item>
									</div>
								</el-col>
								<el-col :span="4">
									<div class="div-col">
										<el-row :gutter="0">
											<el-col :span="24">
												<el-form-item
													:maxlength="50"
													:required="true"
													class="item-bt-s"
													label="物料编码"
												>
													<el-input
														disabled
														maxlength="50"
														v-model.trim="
															pagefromData.materialNumber
														"
													></el-input>
												</el-form-item>
												<el-form-item
													class="item-bt-s"
													label="物料名称"
												>
													<el-input
														disabled
														v-model.trim="
															pagefromData.materialName
														"
													></el-input>
												</el-form-item>
												<el-form-item
													class="item-bt-s"
													label="规格型号（sku）"
												>
													<el-input
														disabled
														v-model.trim="
															pagefromData.specification
														"
													></el-input>
												</el-form-item>
												<el-form-item
													class="item-bt-s"
													label="BOM版本"
												>
													<el-input
														disabled
														placeholder
														v-model.trim="
															pagefromData.bomVersion
														"
													></el-input>
												</el-form-item>
											</el-col>
										</el-row>
									</div>
								</el-col>
								<el-col :span="4">
									<div class="div-col">
										<el-form-item
											class="item-bt-s"
											disabled
											label="单位"
										>
											<el-select
												:disabled="true"
												v-model="pagefromData.unitId"
											>
												<el-option
													:key="item.id + item.name"
													:label="item.name"
													:value="item.id"
													style="font-size: 12px"
													v-for="item in unitlist"
												></el-option>
											</el-select>
										</el-form-item>
										<el-form-item
											class="item-bt-s"
											label="数量"
										>
											<el-input
												disabled
												placeholder
												v-model.trim="
													pagefromData.number
												"
											></el-input>
										</el-form-item>
									</div>
								</el-col>
								<el-col :span="8"></el-col>
							</el-row>
						</el-form>
					</div>
				</el-tab-pane>
				<!-- 操作记录 -->
				<el-tab-pane label="操作记录">
					<div class="base-info-form-box">
						<el-form
							:model="pagefromData"
							label-width="80px"
							ref="form"
						>
							<el-row :gutter="10">
								<el-col :span="4">
									<div class="div-col">
										<el-form-item
											class="item-bt-s"
											label="创建人"
										>
											<span>{{
												pagefromData.createName
											}}</span>
										</el-form-item>
										<el-form-item
											class="item-bt-s item-date"
											label="创建时间"
										>
											<span>{{
												pagefromData.createDate
											}}</span>
										</el-form-item>
									</div>
								</el-col>
								<el-col :span="4">
									<div class="div-col col-2">
										<el-form-item
											:required="true"
											class="item-bt-s"
											label="最后修改人"
										>
											<span>{{
												pagefromData.modifyName
											}}</span>
										</el-form-item>
										<el-form-item
											:required="true"
											class="item-bt-s"
											label="最后修改时间"
										>
											<span>{{
												pagefromData.modifyDate
											}}</span>
										</el-form-item>
										<el-form-item
											:required="true"
											class="item-bt-s"
											label="提交时间"
										>
											<span>{{
												pagefromData.modifyDate
											}}</span>
										</el-form-item>
									</div>
								</el-col>
								<el-col :span="4">
									<div class="div-col">
										<el-row :gutter="0">
											<el-col :span="24">
												<el-form-item
													:maxlength="50"
													class="item-bt-s"
													label="审核人"
												>
													<span>{{
														pagefromData.checkName
													}}</span>
												</el-form-item>
												<el-form-item
													class="item-bt-s"
													label="审核时间"
												>
													<span>{{
														pagefromData.checkDate
													}}</span>
												</el-form-item>
											</el-col>
										</el-row>
									</div>
								</el-col>
							</el-row>
						</el-form>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
		<!-- 明细信息 -->
		<div class="sale-details-tell-info">
			<div class="tell-info-row-title">
				<h3>明细信息</h3>
				<div class="long-line-bx">
					<div class="long-line"></div>
				</div>
			</div>
			<!-- 明细工具栏 -->
			<div class="tell-info-button-group">
				<DetailsOperation
					:detailBtn="detailBtn"
					:deviationSelectArr="selectRowIndexArr"
					:isEdit="
						pagefromData.documentStatus !== 'a' &&
						pagefromData.documentStatus !== 'd'
					"
					@copyCellcolumn="copyCellcolumn"
					@copyRow="bottomCopyRow"
					@deleteRow="selectDeleteRow"
					@insertObj="getInsertInfo"
				></DetailsOperation>
			</div>
			<!-- 表格信息-->
			<div class="tell-info-table">
				<el-table
					:cell-class-name="tableCellClassName"
					:data="pagefromData.details"
					:header-cell-class-name="mustAfter"
					@cell-click="getRowCol"
					@select="selectRow"
					@select-all="selectRowAll"
					border
					max-height="400"
					ref="multipleTable"
					style="width: 100%; font-size: 12px"
				>
					<el-table-column
						align="center"
						fixed
						type="selection"
						width="40"
					/>
					<el-table-column
						align="center"
						label="序号"
						type="index"
						width="46"
					>
						<template #default="scope">
							<span>{{ scope.$index + 1 }}</span>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="materialId" width="200">
						<template #header>
							<span
								class="iconfont icon-bianji1 iconfont-mg"
							></span
							>子项物料编码
						</template>
						<template #default="scope">
							<el-select
								:disabled="
									!!scope.row.id ||
									(scope.row.id === 0 &&
										pagefromData.documentStatus !== 'a' &&
										pagefromData.documentStatus !== 'd')
								"
								:id="'materialId' + scope.$index"
								:loading="loading"
								:remote-method="
									(query) => {
										matterCodeChange(
											query,
											'materialId',
											scope.$index
										);
									}
								"
								@change="metterChange($event, scope.$index)"
								@click="
									getRowCol(
										scope.row,
										scope.column,
										'materialId'
									)
								"
								filterable
								placeholder="请输入关键词"
								remote
								reserve-keyword
								v-if="scope.row.ismaterialshow"
								v-model="scope.row.materialId"
							>
								<el-option
									:key="item.id + item.number"
									:label="item.number"
									:value="item.id"
									:style="{
										height: item.disable ? '0px' : 'auto',
									}"
									v-for="item in matterallCodelist[
										scope.$index
									]"
								></el-option>
							</el-select>
							<span v-else>{{ scope.row.materialNumber }}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="子项规格型号(SKU)"
						prop="specification"
						width="280"
					/>
					<el-table-column
						align="left"
						label="子项物料名称"
						prop="materialName"
						width="180"
					/>
					<el-table-column align="left" prop="numerator" width="100">
						<template #header>
							<span
								class="iconfont icon-bianji1 iconfont-mg"
							></span
							>用量:分子
						</template>
						<template #default="scope">
							<div v-if="scope.row.isnumeratorshow">
								<el-input
									:disabled="
										pagefromData.documentStatus !== 'a' &&
										pagefromData.documentStatus !== 'd'
									"
									:id="'numerator' + scope.$index"
									:maxlength="11"
									@change="
										numberChage(
											scope.row.numerator,
											scope.$index,
											scope.row,
											'分子',
											'numerator'
										)
									"
									auto-complete="off"
									placeholder="0"
									v-model="scope.row.numerator"
								></el-input>
							</div>
							<span v-else>{{ scope.row.numerator }}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						prop="denominator"
						width="100"
					>
						<template #header>
							<span
								class="iconfont icon-bianji1 iconfont-mg"
							></span
							>用量:分母
						</template>
						<template #default="scope">
							<div v-if="scope.row.isdenominatorshow">
								<el-input
									:disabled="
										pagefromData.documentStatus !== 'a' &&
										pagefromData.documentStatus !== 'd'
									"
									:id="'denominator' + scope.$index"
									:maxlength="11"
									@change="
										numberChage(
											scope.row.denominator,
											scope.$index,
											scope.row,
											'分母',
											'denominator'
										)
									"
									auto-complete="off"
									placeholder="1"
									v-model="scope.row.denominator"
								></el-input>
							</div>
							<span v-else>{{ scope.row.denominator }}</span>
						</template>
					</el-table-column>

					<el-table-column
						align="left"
						label="应发数量(子单位)"
						prop="sendNumber"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.sendNumberchild
									? scope.row.sendNumberchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="已领数量(子单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.receiveNumberchild
									? scope.row.receiveNumberchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="退料数量(子单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realReturnNumberchild
									? scope.row.realReturnNumberchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="补料数量(子单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realFeedNumberchild
									? scope.row.realFeedNumberchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="未领数量(子单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.noReceiveNumberchild
									? scope.row.noReceiveNumberchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="即时库存(子单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realStockchild
									? scope.row.realStockchild
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="子单位"
						prop="subUnitId"
						width="120"
					>
						<template #default="scope">
							<span>{{
								publicidbyname(unitlist, scope.row.subUnitId)
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="损耗率%"
						prop="ffixscrapqty"
						width="120"
					>
						<template #default="scope">
							<span>{{
								(scope.row.ffixscrapqty
									? scope.row.ffixscrapqty
									: 0) * 100
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="应发数量(单位)"
						prop="sendNumber"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.sendNumber ? scope.row.sendNumber : 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="已领数量(单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.receiveNumber
									? scope.row.receiveNumber
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="退料数量(单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realReturnNumber
									? scope.row.realReturnNumber
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="补料数量(单位)"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realFeedNumber
									? scope.row.realFeedNumber
									: 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="即时库存(单位)"
						prop="realStock"
						width="120"
					>
						<template #default="scope">
							<span>{{
								scope.row.realStock ? scope.row.realStock : 0
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="未领数量(单位)"
						prop="noReceiveNumber"
						width="120"
					></el-table-column>
					<el-table-column
						align="left"
						label="发料方式"
						prop="fissueType"
						width="130"
					>
						<template #default="scope">
							<span>
								{{
									scope.row.fissueType
										? publicidbyname(
												sendMaterialTypelist,
												scope.row.fissueType
										  )
										: null
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="单位"
						prop="unitId"
						width="120"
					>
						<template #default="scope">
							<span>{{
								publicidbyname(unitlist, scope.row.unitId)
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="left"
						label="是否关键/件"
						prop="isKeyComponent"
						width="120"
					>
						<template #default="scope">
							<el-checkbox
								:disabled="
									pagefromData.documentStatus !== 'a' &&
									pagefromData.documentStatus !== 'd'
								"
								v-model="scope.row.isKeyComponent"
							/>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="remark" width="225">
						<template #header>
							<span
								class="iconfont icon-bianji1 iconfont-mg"
							></span
							>位置号/模号/备注
						</template>
						<template #default="scope">
							<el-input
								:disabled="
									pagefromData.documentStatus !== 'a' &&
									pagefromData.documentStatus !== 'd'
								"
								:id="'remark' + scope.$index"
								:maxlength="2000"
								@input="
									getRowCol(scope.row, scope.column, 'remark')
								"
								v-if="scope.row.isremarkshow"
								v-model="scope.row.remark"
							></el-input>
							<sapn v-else>{{ scope.row.remark }}</sapn>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
	</div>
</template>
<script>
import { mapState } from 'vuex';
import { Decimal } from 'decimal.js';
import { countMethodsUnitNumber } from '@/utils/count.js';
import { theUnitSet, batchhandle } from '@/utils/pubulic.js';
import { bottomAddRow } from '@/utils/takeMethods';
export default {
	name: 'OutsourcMaterials',
	data() {
		return {
			salePrecisionNumberP: [], // 单位
			salePrecisionNumber: [], // 子单位
			isPrecisionP: [], // 单位
			isPrecision: [], // 子单位
			isCountP: [], // 单位 精度
			isCount: [], // 子单位 精度
			isDisable: false,
			detailBtn: ['copy'],
			actionType: '', // 操作动作 新增还是修改还是编辑
			documentStatuslist: [], // 单据状态
			documentTypelist: [], // 单据类型
			sendMaterialTypelist: [], // 发料方式下拉数据
			matterallCodelist: [[]], // 物料下拉数据
			unitlist:
				this.$store.state && this.$store.state.storeData.allUnit
					? this.$store.state.storeData.allUnit
					: [], // 获取计量单位数据, //获取单位的精度和类型集合
			supplierlist: [], //供应商
			loading: false,
			documentStatus: '', // 单据状态
			pagefromData: {},
			btnType: [
				'add',
				'copy',
				'delete',
				'delet',
				'operation',
				's-p-t-g4',
				's-p-t-g5',
				'exDetails',
			], // 不需要显示的顶部按钮类型
			addRow: {
				id: 0,
				seq: '', //序号
				materialId: '', //物料编码
				materialNumber: '', //物料编码
				materialName: '', //物料名称
				specification: '', // 规格型号
				numerator: 0, //分子
				denominator: 1, //分母
				unitId: '', //单位
				subUnitId: '', // 子单位
				sendNumber: 0, //应发数量
				ffixscrapqty: null, //损耗率
				receiveNumber: 0, //已领数量
				noReceiveNumber: 0, //未领数量
				fissueType: '1', //发料方式
				realStock: '', //即时库存
				isKeyComponent: false, //是否关键件
				isAuto: false, //是否自动生成 true 自动生成 false 或者null 手动新增
				remark: '', //备注
			},
			insertTopVal: '',
			insertBottomVal: '',
			selectRowIndex: 0,
			// 批量填充
			batchfill: {
				romIndex: null,
				columnIndex: null,
				columnkey: null,
			},
			heightNum: 0,
			selectRowIndexArr: [],
		};
	},
	computed: {
		...mapState({
			orgId: (state) =>
				state && state.org && state.org.orgId ? state.org.orgId : null,
			orgIdArr: (state) => (state ? state.user.orgIdArr : null),
		}),
		publicidbyname: function () {
			// 根据key值显示对应的键名
			return function (arr, key) {
				return theUnitSet(arr, key);
			};
		},
	},
	created() {
		this.heightNum =
			document.documentElement.clientHeight - (40 + 30 + 16 + 16);
		this.Init();
	},
	methods: {
		Init() {
			this.getUnit();
			this.getStatus();
			this.getsupplierList();
			this.InItEditorCopy();
		},
		// 保存或者提交的时候，对数据个别字段例如 isGive is211 seq 做数据整理，避免提交保存失败
		arrangeData() {
			let newDetails = this.pagefromData.details.map((v, index) => {
				return { ...v, seq: index };
			});
			this.pagefromData.details = newDetails;
			if (this.pagefromData.details) {
				// 清空明细选中
				this.$refs.multipleTable.clearSelection();
				this.selectRowIndexArr = [];
			}
		},
		// 初始化--编辑或者详情
		InItEditorCopy() {
			// 如果是复制，编辑，查看--过来的新增订单
			if (this.$route.query.detailId) {
				this.getUseMaterialSetInfo(this.$route.query.detailId);
			}
		},
		// 生产组织下拉改变是 （会影响生产部门的数据）
		orgChange(value) {
			if (
				this.pagefromData.details &&
				this.pagefromData.details.length > 0
			) {
				this.pagefromData.details.forEach((res, index) => {
					this.pagefromData.details[index].workShopId = null;
				});
			}
		},
		// 获取每一条的精度和类型
		numberPrecisionMethods(index, unit, S, P, C) {
			if (this.pagefromData.details[index][unit]) {
				let tempList = this.unitlist.filter(
					(it) => it.id === this.pagefromData.details[index][unit]
				);
				if (tempList && tempList.length > 0) {
					tempList[0].precision == 0
						? (this[P][index] = true)
						: (this[P][index] = false);
					tempList[0].precision == 0
						? (this[S][index] = 0)
						: (this[S][index] = tempList[0].precision);
				}
			}
			this[P][index] = this[P][index] ? this[P][index] : false;
			this[S][index] =
				this[S][index] || this[S][index] == 0 ? this[S][index] : 10;
			if (
				!this.pagefromData.details[index].materialNumber &&
				!this.$route.query.id
			) {
				this[P][index] = true;
			}
			if (!this[C][index]) {
				this[C][index] = 1;
			}
		},
		// 数量改变时
		numberChage(val, index, item, type, key) {
			// 判断条件 子单位
			this.numberPrecisionMethods(
				index,
				'subUnitId',
				'salePrecisionNumber',
				'isPrecision',
				'isCount'
			);
			// 判断条件 单位
			this.numberPrecisionMethods(
				index,
				'unitId',
				'salePrecisionNumberP',
				'isPrecisionP',
				'isCountP'
			);
			// 输入限制
			if (val) {
				this.pagefromData.details[index][key] = val
					.toString()
					.replace(/[^\d^\\.]+/g, '')
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
					.replace(
						/^(\\-)*(\d+)\.(\d\d\d\d\d\d\d\d\d\d).*$/,
						'$1$2.$3'
					);

				// 计算子单位
				// 计算应发子单位计算处理  应发数量(子单位)=(分子numerator/分母denominator)*订单数量number*(1+损耗率ffixscrapqtyName)
				this.pagefromData.details[index].sendNumberchild =
					Decimal(
						Decimal(this.pagefromData.details[index].numerator).div(
							Decimal(
								this.pagefromData.details[index].denominator
							)
						)
					).mul(Decimal(this.pagefromData.number)) *
					Decimal(1).add(
						Decimal(
							this.pagefromData.details[index].ffixscrapqty
								? this.pagefromData.details[index].ffixscrapqty
								: 0
						)
					);
				// 精度处理
				const jdarry1 = [
					{ key: 'sendNumber', keychild: 'sendNumberchild' },
					{ key: 'realStock', keychild: 'realStockchild' },
				];
				jdarry1.forEach((it) => {
					this.dataNumjd(index, it.key, it.keychild, 'numchange');
				});
				// 精度处理end
				this.pagefromData.details[index][key] =
					this.pagefromData.details[index][key] * 1;
			} else {
				this.pagefromData.details[index].sendNumber = null;
				this.pagefromData.details[index].sendNumberchild = null;
			}
		},
		//数据精度处理
		dataNumjd(index, key, keychild, type) {
			// 判断条件 单位
			this.numberPrecisionMethods(
				index,
				'unitId',
				'salePrecisionNumberP',
				'isPrecisionP',
				'isCountP'
			);
			const tempListUnitId = this.unitlist.filter(
				(it) => it.id === this.pagefromData.details[index].unitId
			);
			// 判断条件 子单位
			this.numberPrecisionMethods(
				index,
				'subUnitId',
				'salePrecisionNumber',
				'isPrecision',
				'isCount'
			);
			const tempList = this.unitlist.filter(
				(it) => it.id === this.pagefromData.details[index].subUnitId
			);
			if (key) {
				this.pagefromData.details[index][key] =
					this.pagefromData.details[index][keychild] /
					(this.pagefromData.details[index].subUnitMultiple
						? this.pagefromData.details[index].subUnitMultiple
						: 1);
				this.pagefromData.details[index][keychild] =
					this.pagefromData.details[index][key] *
					(this.pagefromData.details[index].subUnitMultiple
						? this.pagefromData.details[index].subUnitMultiple
						: 1);
				//(单位)
				let resultRealSo = countMethodsUnitNumber(
					tempListUnitId,
					this.pagefromData.details[index][key],
					this.pagefromData.details[index][key],
					this.isCountP[index],
					this.salePrecisionNumberP[index],
					true
				);
				this.pagefromData.details[index][key] = resultRealSo.value;
				// 计算应发单位计算处理  未领数量 = 应发 -已领+退料
				this.pagefromData.details[index].noReceiveNumber = Decimal(
					this.pagefromData.details[index].sendNumber
						? this.pagefromData.details[index].sendNumber
						: 0
				)
					.sub(
						Decimal(
							this.pagefromData.details[index].receiveNumber
								? this.pagefromData.details[index].receiveNumber
								: 0
						)
					)
					.add(
						Decimal(
							this.pagefromData.details[index].realReturnNumber
								? this.pagefromData.details[index]
										.realReturnNumber
								: 0
						)
					);
				this.pagefromData.details[index].noReceiveNumber =
					this.pagefromData.details[index].noReceiveNumber > 0
						? this.pagefromData.details[index].noReceiveNumber
						: 0;
				this.isCountP[index] = resultRealSo.isDefault;

				// (子单位)
				let resultRealSoc = countMethodsUnitNumber(
					tempList,
					this.pagefromData.details[index][keychild],
					this.pagefromData.details[index][keychild],
					this.isCount[index],
					this.salePrecisionNumber[index],
					true
				);
				this.pagefromData.details[index][keychild] =
					resultRealSoc.value;
				// 计算应发子单位计算处理  未领数量 = 应发 -已领+退料
				this.pagefromData.details[index].noReceiveNumberchild = Decimal(
					this.pagefromData.details[index].sendNumberchild
						? this.pagefromData.details[index].sendNumberchild
						: 0
				)
					.sub(
						Decimal(
							this.pagefromData.details[index].receiveNumberchild
								? this.pagefromData.details[index]
										.receiveNumberchild
								: 0
						)
					)
					.add(
						Decimal(
							this.pagefromData.details[index]
								.realReturnNumberchild
								? this.pagefromData.details[index]
										.realReturnNumberchild
								: 0
						)
					);
				this.pagefromData.details[index].noReceiveNumberchild =
					this.pagefromData.details[index].noReceiveNumberchild > 0
						? this.pagefromData.details[index].noReceiveNumberchild
						: 0;
				this.isCount[index] = resultRealSoc.isDefault;
			}
		},
		// 获取委外用料清单详情
		getUseMaterialSetInfo(detailId) {
			this.matterallCodelist = [];
			const names = [];
			this.$http
				.get('OutSourcMaterial/GetByOutSourcOrderDetailId/' + detailId)
				.then((res) => {
					if (res.status === 200) {
						this.pagefromData = JSON.parse(
							JSON.stringify(res.data)
						);
						this.pagefromData.prdorgId = res.data.prdorgId
							? parseInt(res.data.prdorgId)
							: '';
						if (res.data.details && res.data.details.length > 0) {
							res.data.details.forEach((it, index) => {
								Object.assign(it, {
									ismaterialshow: false,
									isnumeratorshow: false,
									isdenominatorshow: false,
									isremarkshow: false,
								});
								this.pagefromData.details[index].seq = index;
								this.pagefromData.details[
									index
								].noReceiveNumber = it.noReceiveNumber
									? it.noReceiveNumber
									: 0;
								this.pagefromData.details[
									index
								].noReceiveNumberchild = it.noReceiveNumberchild
									? it.noReceiveNumberchild
									: 0;
								this.pagefromData.details[index].fissueType =
									it.fissueType + '';
								names.push(it.materialNumber);
								// 损耗率的小数精度处理
								this.pagefromData.details[
									index
								].ffixscrapqtyName = Decimal(
									Decimal(
										it.ffixscrapqty ? it.ffixscrapqty : 0
									).mul(100)
								).toNumber();
								// 精度处理
								let jdarry = [
									{
										key: 'realStock',
										keychild: 'realStockchild',
									},
									{
										key: 'noReceiveNumber',
										keychild: 'noReceiveNumberchild',
									},
								];
								jdarry.forEach((it) => {
									this.dataNumjd(index, it.key, it.keychild);
								});
								// 精度处理end
							});
							this.initMatterCode(names, res.data.details.length);
						} else {
							this.matterallCodelist.push([]);
							this.pagefromData.details = [
								JSON.parse(JSON.stringify(this.addRow)),
							];
						}
					}
				});
		},
		// 获取单位
		getUnit() {
			var unitlist =
				this.$store.state && this.$store.state.storeData
					? this.$store.state.storeData.allUnit
					: [];
			if (
				JSON.stringify(
					this.$store.state && this.$store.state.storeData
						? this.$store.state.storeData.allUnit
						: []
				) === '[]'
			) {
				this.$http.get('SysConfig/GetUnitAllProperty').then((r) => {
					if (r.status === 200) {
						this.unitlist = this.$store.state.storeData.allUnit =
							r.data;
					}
				});
			} else {
				this.unitlist = unitlist;
			}
		},
		// 获取需要状态列表---[单据状态，领料状态，业务状态]
		getStatus() {
			var infoStatus =
				this.$store.state && this.$store.state.storeData
					? this.$store.state.storeData.infoStatusww
					: {};
			if (
				JSON.stringify(
					this.$store.state && this.$store.state.storeData
						? this.$store.state.storeData.infoStatusww
						: {}
				) === '{}'
			) {
				this.$http.get('OutSourcOrder/GetStatus').then((r) => {
					if (r.status === 200) {
						this.documentStatuslist = r.data.documentStatus;
						this.documentTypelist = r.data.pickDocumentType;
						this.sendMaterialTypelist = r.data.sendMaterialType;
						this.pagefromData.moType = Object.keys(
							r.data.pickDocumentType
						)[0];
						this.$store.state.storeData.infoStatusww = r.data;
					}
				});
			} else {
				this.documentStatuslist = infoStatus.documentStatus;
				this.documentTypelist = infoStatus.pickDocumentType;
				this.sendMaterialTypelist = infoStatus.sendMaterialType;
				this.pagefromData.moType = Object.keys(
					infoStatus.pickDocumentType
				)[0];
			}
		},
		// 计算应发数量
		calculationSendNumber(index) {
			this.pagefromData.details[index].sendNumber = 0;
			this.pagefromData.details[index].numerator = 0;
			this.pagefromData.details[index].denominator = 1;
			this.pagefromData.details[index].sendNumberchild = 0;
			this.pagefromData.details[index].receiveNumberchild = 0;
			this.pagefromData.details[index].realReturnNumberchild = 0;
			this.pagefromData.details[index].realFeedNumberchild = 0;
			this.pagefromData.details[index].noReceiveNumberchild = 0;
			this.pagefromData.details[index].ffixscrapqty = 0;
			this.pagefromData.details[index].ffixscrapqtyName = 0;
			this.pagefromData.details[index].receiveNumber = 0;
			this.pagefromData.details[index].realReturnNumber = 0;
			this.pagefromData.details[index].realFeedNumber = 0;
			this.pagefromData.details[index].noReceiveNumber = 0;
			this.pagefromData.details[index].realStock = 0;
			this.pagefromData.details[index].realStockchild = 0;

			// let needNum =
			// 	this.pagefromData.number *
			// 	(this.pagefromData.details[index].numerator /
			// 		this.pagefromData.details[index].denominator);
			// this.pagefromData.details[index].sendNumber = parseInt(
			// 	needNum +
			// 		needNum *
			// 			(this.pagefromData.details[index].ffixscrapqty
			// 				? this.pagefromData.details[index].ffixscrapqty
			// 				: 0)
			// );
		},
		// 物料下拉更新
		metterChange(val, index) {
			let metterInfo = {};
			metterInfo = this.matterallCodelist[index].filter((res) => {
				return res.id === val;
			})[0];
			this.pagefromData.details[index].materialName = metterInfo.name;
			this.pagefromData.details[index].materialNumber = metterInfo.number;
			this.pagefromData.details[index].specification =
				metterInfo.specifications;
			this.pagefromData.details[index].unitId = metterInfo.baseUnitId;
			this.pagefromData.details[index].subUnitId = metterInfo.subUnitId;
			this.pagefromData.details[index].realStock = metterInfo.realStock;
			this.pagefromData.details[index].subUnitMultiple =
				metterInfo.subUnitMultiple;
			// this.dataNumjd(index, 'realStock', 'realStockchild');
			// console.log('走到了这里了吗');
			//计算应发数量
			this.calculationSendNumber(index);
		},
		// 初始化一次性获取物料信息的接口
		initMatterCode(names, total) {
			this.$http
				.post('SysConfig/GetMaterialLikeList', {
					names: names,
					file: 'Number',
					orgId: this.pagefromData.suborgId,
				})
				.then((res) => {
					if (res.status == 200) {
						if (total && total > 0) {
							for (let tag = 0; tag < total; tag++) {
								this.matterallCodelist[tag] = [];
								this.matterallCodelist[tag] = res.data;
							}
						}
					}
				});
		},
		// 获取物料编码信息
		matterCodeChange(val, type, index) {
			const _this = this;
			if (val !== '') {
				this.loading = true;
				this.loading = false;
				this.$http
					.showLoading(false)
					.post('SysConfig/GetMaterial', {
						name: val,
						orgId: this.pagefromData.suborgId,
						file: 'Number',
					})
					.then((res) => {
						if (res.status === 200) {
							if (index || index === 0) {
								_this.matterallCodelist[index] = [];
								_this.matterallCodelist[index] =
									res.data && res.data.length > 0
										? res.data
										: [];
							}
						}
					});
			} else {
				this.matterallCodelist[index] = [];
			}
		},
		//顶部按钮操作栏
		actionhandel(type) {
			//点击保存

			this.isDisable = true;
			setTimeout(() => {
				this.isDisable = false;
			}, 2000);

			if (type === 'save') {
				this.savePageData();
			}
			//点击提交
			if (type === 'submit') {
				this.submitPageData();
			}
			//点击撤销
			if (type === 'revoke') {
				this.toolarFn('OutSourcMaterial/Revoke', '撤销');
			}
			//点击审核
			if (type === 'audit') {
				this.toolarFn('OutSourcMaterial/Check', '审核');
			}
			//点击反审核
			if (type === 'de-approval') {
				this.toolarFn('OutSourcMaterial/NoCheck', '反审核');
			}
		},
		// 顶部操作方法-有公共的部分封装下
		toolarFn(path, typeName) {
			let formdata = { ids: [this.pagefromData.id] };
			this.$http.post(path, formdata).then((res) => {
				if (res.status === 200) {
					if (
						res.data &&
						res.data.length === 1 &&
						!res.data[0].isSuccess
					) {
						this.$message.error({
							message: res.data[0].msg,
							showClose: true,
						});
					} else {
						this.pagefromData.details.forEach((it) => {
							it.fissueType = it.fissueType + '';
						});
						this.pagefromData.documentStatus =
							typeName === '审核'
								? 'c'
								: typeName === '反审核'
								? 'd'
								: typeName === '撤销'
								? 'a'
								: this.pagefromData.documentStatus;
						this.$message.success({
							message: typeName + '成功',
							showClose: true,
						});
					}
				}
				this.$forceUpdate();
			});
		},
		setComputeLog() {
			let units = {};
			this.$store.state.storeData.allUnit.forEach((item) => {
				units[item.id] = item;
			});

			this.pagefromData.details.forEach((item) => {
				if (item.materialNumber) {
					item.computeLog = `数量：【${
						this.pagefromData.number
					}】-物料编码:${item.materialNumber}-分子:【${
						item.numerator
					}】-分母:【${item.denominator}】-应发数量(子单位):【${
						item.sendNumberchild
					}】-子单位ID:【${item.subUnitId}】-子单位名称:【${
						units[item.subUnitId].name
					}】-子单位roundoffType:【${
						units[item.subUnitId].roundoffType
					}】-子单位precision:【${
						units[item.subUnitId].precision
					}】-应发数量(单位):【${item.sendNumber}】-单位:【${
						item.unitId
					}】-单位名称:【${
						units[item.unitId].name
					}】-单位precision:【${
						units[item.unitId].precision
					}】-单位roundoffType:【${
						units[item.unitId].roundoffType
					}】-损耗率:【${item.ffixscrapqtyName}】`;
				}
			});
		},
		// 保存
		savePageData() {
			this.setComputeLog();
			this.arrangeData();
			this.$http
				.post('OutSourcMaterial/Save', this.pagefromData)
				.then((res) => {
					if (res.status === 200) {
						this.getUseMaterialSetInfo(this.$route.query.detailId);
						if (
							res.data &&
							res.data.length === 1 &&
							!res.data[0].isSuccess
						) {
							this.$message.error({
								message: res.data[0].msg,
								showClose: true,
							});
						} else {
							this.$message.success({
								message: '保存成功',
								showClose: true,
							});
						}
					}
				});
		},
		// 提交
		submitPageData() {
			this.setComputeLog();
			this.arrangeData();
			this.$http
				.post('OutSourcMaterial/Commit', this.pagefromData)
				.then((res) => {
					if (res.status === 200) {
						this.getUseMaterialSetInfo(this.$route.query.detailId);
						if (
							res.data &&
							res.data.length === 1 &&
							!res.data[0].isSuccess
						) {
							this.$message.error({
								message: res.data[0].msg,
								showClose: true,
							});
						} else {
							this.pagefromData.documentStatus = 'b';
							this.$message.success({
								message: '提交成功',
								showClose: true,
							});
						}
					}
				});
		},
		// 星星--头部必填ico显示
		mustAfter(obj) {
			let arry = [2, 5, 6];
			if (arry.indexOf(obj.columnIndex) !== -1) {
				return 'must';
			}
		},
		// 获取供应商-下拉列表
		getsupplierList() {
			if (
				this.$store.state &&
				this.$store.state.storeData &&
				this.$store.state.storeData.supplierSelect.length > 0
			) {
				this.supplierlist = this.$store.state.storeData.supplierSelect;
			} else {
				this.$http.get('SysConfig/supplier/select').then((r) => {
					if (r.status === 200) {
						this.supplierlist =
							this.$store.state.storeData.supplierSelect = r.data;
					}
				});
			}
		},
		// 失焦处理
		selectBlur() {
			let _this = this;
			_this.pagefromData.details.forEach((el) => {
				el.ismaterialshow = false;
				el.isnumeratorshow = false;
				el.isdenominatorshow = false;
				el.isremarkshow = false;
			});
		},
		// 插入的行
		getInsertInfo(data) {
			this.pagefromData.details = bottomAddRow(
				this.pagefromData.details,
				JSON.parse(JSON.stringify(this.addRow))
			);
			this.matterallCodelist.splice(this.pagefromData.details, 0, []);
			// if (data.insertTopVal != 0) {
			//   for (let i = 0; i < data.insertTopVal; i++) {
			//     this.pagefromData.details.splice(this.selectRowIndex, 0, JSON.parse(JSON.stringify(this.addRow)))
			//     this.matterallCodelist.splice(this.selectRowIndex, 0, [])
			//     this.selectRowIndex = parseInt(this.selectRowIndex) + 1
			//   }
			// }
			// if (data.insertBottomVal != 0) {
			//   for (let i = 0; i < data.insertBottomVal; i++) {
			//     var num = this.selectRowIndex + 1
			//     this.pagefromData.details.splice(num, 0, JSON.parse(JSON.stringify(this.addRow)))
			//     this.matterallCodelist.splice(num, 0, [])
			//   }
			// }
			this.$nextTick(() => {
				this.$refs.multipleTable.$refs.bodyWrapper.scrollTop =
					this.$refs.multipleTable.$refs.bodyWrapper.scrollHeight;
			});
			this.selectBlur();
			this.arrangeData();
		},
		// 向下复制行
		bottomCopyRow(data) {
			// 判断行数
			if (this.selectRowIndexArr.length == 1) {
				const tableArr = JSON.parse(
					JSON.stringify(
						this.pagefromData.details[this.selectRowIndex]
					)
				);
				tableArr.id = 0;
				var insertNum = this.selectRowIndex + 1;
				this.pagefromData.details.splice(insertNum, 0, tableArr);
				this.matterallCodelist.splice(
					insertNum,
					0,
					JSON.parse(
						JSON.stringify(
							this.matterallCodelist[this.selectRowIndex]
						)
					)
				);
				this.arrangeData();
			} else {
				this.$message.error({
					message: '请勾选一条行,在操作',
					showClose: true,
				});
			}
		},
		// 删除行
		selectDeleteRow(data) {
			if (this.selectRowIndexArr.length <= 0) {
				this.$message.warning({
					message: '请选择要删除的行!',
					showClose: true,
				});
				return;
			}
			// 不能为空
			if (
				this.pagefromData.details.length > 1 &&
				this.selectRowIndexArr.length < this.pagefromData.details.length
			) {
				let masgtag = 0;
				// this.selectRowIndexArr.forEach((k) => {
				// 	this.pagefromData.details.forEach((l, index) => {
				// 		if (k === l.seq) {
				// 			if (!l.id || !l.isAuto) {
				// 				this.pagefromData.details.splice(index, 1);
				// 				this.matterallCodelist.splice(index, 1);
				// 			} else if (l.isAuto) {
				// 				// masgtag++;
				// 				this.$message.error({
				// 					message: '存在BOM携带而来的数据不可删除',
				// 					showClose: true,
				// 				});
				// 				return false;
				// 			}
				// 		}
				// 	});
				// });
				let length = this.pagefromData.details.length || 0;
				for (let i = 0; i < length; i++) {
					if (
						this.selectRowIndexArr.includes(
							this.pagefromData.details[i].seq
						)
					) {
						if (this.pagefromData.details[i].isAuto) {
							this.$message.error({
								message: '存在BOM携带而来的数据不可删除',
								showClose: true,
							});
							return false;
						}
						if (length === 1) {
							this.$message.error({
								message: '至少保留一行明细!',
								showClose: true,
							});
							return false;
						}
						if (
							!this.pagefromData.details[i].id ||
							!this.pagefromData.isAuto
						) {
							this.pagefromData.details.splice(i, 1);
							this.matterallCodelist.splice(i, 1);
						}
					}
				}
				// if (masgtag > 0) {
				// 	this.$message.error({
				// 		message: '存在BOM携带而来的数据不可删除',
				// 		showClose: true,
				// 	});
				// }
				this.arrangeData();
			} else {
				this.$message.warning({
					message: '至少保留一行明细!',
					showClose: true,
				});
			}
		},
		// 批量填充
		copyCellcolumn(data) {
			let batcharry = [
				'materialId',
				'numerator',
				'denominator',
				'remark',
			];
			this.pagefromData = batchhandle(
				this.pagefromData,
				this.matterallCodelist,
				this.batchfill.romIndex,
				this.batchfill.columnkey,
				batcharry
			);
			// 重新判断数量精度
			for (
				let i = this.batchfill.romIndex + 1;
				i < this.pagefromData.details.length;
				i++
			) {
				if (this.batchfill.columnkey == 'denominator') {
					this.numberChage(
						this.pagefromData.details[i].denominator,
						i,
						this.pagefromData.details[i],
						'分母',
						'denominator'
					);
				}
				if (this.batchfill.columnkey == 'numerator') {
					this.numberChage(
						this.pagefromData.details[i].numerator,
						i,
						this.pagefromData.details[i],
						'分子',
						'numerator'
					);
				}
				if (
					this.batchfill.columnkey === 'specification' ||
					this.batchfill.columnkey === 'materialId'
				) {
					this.pagefromData.details[i].denominator = 1;
					this.pagefromData.details[i].numerator = 0;
					this.numberChage(
						this.pagefromData.details[i].numerator,
						i,
						this.pagefromData.details[i],
						'分子',
						'numerator'
					);
				}
			}
		},
		//注意这里是解构
		tableCellClassName({ row, column, rowIndex, columnIndex }) {
			row.index = rowIndex;
			column.index = columnIndex;
		},
		getRowCol(row, column, cell, event) {
			this.batchfill.romIndex = row.index;
			this.batchfill.columnIndex = column.index;
			if (typeof cell === 'string') {
				this.batchfill.columnkey = cell;
			} else {
				this.batchfill.columnkey = column.property;
			}
			// 处理表格下拉框输入框显示隐藏
			this.pagefromData.details.forEach((it, index) => {
				Object.assign(it, {
					ismaterialshow: false,
					isnumeratorshow: false,
					isdenominatorshow: false,
					isremarkshow: false,
				});
			});
			var showtagarry = [
				'ismaterialshow',
				'isnumeratorshow',
				'isdenominatorshow',
				'isremarkshow',
			];
			var parentshowtagarry = [
				'materialId',
				'numerator',
				'denominator',
				'remark',
			];
			showtagarry.forEach((k, idx) => {
				if (column.property == parentshowtagarry[idx]) {
					this.pagefromData.details[row.index][k] = true;
					this.$nextTick((_) => {
						if (
							document.getElementById(column.property + row.index)
						) {
							document
								.getElementById(column.property + row.index)
								.focus();
						}
					});
				}
			});
		},
		// 明细选择行的数据处理
		selectdataSet(selection, row) {
			this.multipleSelection = [];
			this.multipleSelection = selection;
			if (row) {
				this.selectRowIndex = row.seq;
			}
			if (selection && selection.length > 0) {
				this.selectRowIndex = selection[0].seq;
			}
			if (selection.length != 0) {
				this.selectRowIndexArr = selection.map((it) => {
					return it.seq;
				});
			} else {
				this.selectRowIndexArr = [];
			}
		},
		// 选择全部明细(全选)
		selectRowAll(selection) {
			this.selectdataSet(selection);
		},
		// 选择的行（单选）
		selectRow(selection, row) {
			this.selectdataSet(selection);
		},
	},
};
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderDetails.scss';

.el-form-item__label {
	width: 97px !important;
}

::v-deep(.div-col .el-input__inner) {
	padding: 0 30px 0 8px;
	width: 165px !important;
}
</style>
