<template>
	<div class="main-container order-mc-bg">
		<div
			:style="{ height: containerHeight + 'px!important' }"
			class="sale-container"
		>
			<toolBtn
				:btnType="btnType"
				:isDisable="isDisable"
				@actionhandel="actionhandel"
			></toolBtn>
			<div class="sale-page-body">
				<div class="sale-page-table-header" ref="getSaleTableHeader">
					<el-form :inline="true">
						<el-row class="form-row1">
							<el-col :span="20">
								<el-row :gutter="2">
									<el-col :span="5">
										<el-form-item label="供应组织/供应商">
											<el-select
												:clearable="true"
												:remote-method="
													getSuppOrgSerach
												"
												@change="
													clearCom(
														supplierOrgId,
														'supplierOrgId'
													)
												"
												filterable
												placeholder="请选择供应组织或供应商"
												remote
												reserve-keyword
												v-model="supplierOrgId"
											>
												<el-option
													:key="item.id"
													:label="item.name"
													:value="item.id"
													@click="
														searchCom(
															supplierOrgId,
															'supplierOrgId'
														)
													"
													class="f_12"
													v-for="item in statusForm.supplierOrgs"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label=" 物料">
											<el-input
												:input="
													clearCom(
														material,
														'material'
													)
												"
												@keyup.enter="
													searchCom(
														material,
														'material'
													)
												"
												class="f_12"
												placeholder="请输入物料编码/名称/规格型号"
												v-model.trim="material"
											></el-input>
											<!-- <div :data-clipboard-text="material" @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-input
												:input="
													clearCom(
														ProduceMaterial,
														'ProduceMaterial'
													)
												"
												@keyup.enter="
													searchCom(
														ProduceMaterial,
														'ProduceMaterial'
													)
												"
												class="f_12"
												placeholder="请输入父项物料编码"
												v-model.trim="ProduceMaterial"
											></el-input>
										
										</el-form-item>
									</el-col> -->
									<el-col :span="9"></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">
											<el-button
												@click="resetSearch"
												size="small"
												>重置</el-button
											>
											<el-button
												@click="searchList"
												size="small"
												type="primary"
												>搜索</el-button
											>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<div
					:style="{ height: heightNum + 'px' }"
					class="sale-page-table-body"
				>
					<el-table
						:cell-style="cellColor"
						:data="tableData"
						:header-cell-style="headerBg"
						:header-cell-class-name="mustAfter"
						:max-height="heightNum"
						@cell-click="getRowCol"
						@selection-change="handleSelectionChange"
						@sort-change="onSortTime"
						border
						class="table-box"
						ref="fileTable"
						style="width: 100%; font-size: 12px"
						v-loading="tableLoading"
					>
						<el-table-column
							align="center"
							fixed
							type="selection"
							width="40"
						/>
						<el-table-column
							align="left"
							fixed
							label="物料编码"
							prop="materialNumber"
							width="172"
						/>
						<el-table-column
							align="left"
							fixed
							label="物料名称"
							prop="materialName"
							width="150"
						/>
						<el-table-column
							align="left"
							label="规格型号(SKU)"
							prop="specification"
							width="280"
						/>
						<el-table-column
							align="left"
							label="物料承担方"
							prop="materialBear"
							width="84"
						/>
						<el-table-column
							align="left"
							label="物料属性"
							prop="materialPropertyKey"
							width="96"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>物料属性
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isMaterialPropertyKey">
									{{
										getNameObj(
											statusForm.materialPropertys,
											scope.row.materialPropertyKey
										)
									}}
								</span>
								<el-select
									:id="'materialPropertyKey' + scope.$index"
									@click="
										getRowCol(
											scope.row,
											scope.column,
											'materialPropertyKey'
										)
									"
									placeholder=" "
									v-if="scope.row.isMaterialPropertyKey"
									v-model="scope.row.materialPropertyKey"
								>
									<el-option
										:key="key + index"
										:label="value"
										:value="key"
										@click="
											upDataRow(
												scope.$index,
												scope.row.materialPropertyKey,
												'materialPropertyKey'
											)
										"
										class="f_12"
										v-for="(
											value, key, index
										) in statusForm.materialPropertys"
									></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="供应组织/供应商"
							prop="supplyOrgOrSupplier"
							width="172"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>供应组织/供应商
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isSupplyOrgOrSupplier">{{
									scope.row.supplyOrgOrSupplier
								}}</span>
								<el-select
									:id="'supplyOrgOrSupplier' + scope.$index"
									:remote-method="
										(query) => {
											getSuppOrg(query, scope.$index);
										}
									"
									filterable
									placeholder=" "
									remote
									reserve-keyword
									v-if="scope.row.isSupplyOrgOrSupplier"
									v-model="scope.row.supplyOrgOrSupplier"
								>
									<el-option
										:key="item.id"
										:label="item.name"
										:value="item.id"
										@click="
											detailsCom(
												scope.row.supplyOrgOrSupplier,
												'supplyOrgId',
												'supplierId',
												scope.row,
												item.name
											)
										"
										class="f_12"
										v-for="item in supplierList[
											scope.$index
										]"
									></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column
							align="center"
							label="交期天数"
							prop="deliveryDay"
							width="100"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>交期天数
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isDeliveryDay">{{
									scope.row.deliveryDay
								}}</span>
								<input
									:id="'deliveryDay' + scope.$index"
									:maxlength="4"
									@blur="
										saleNum(
											scope.row.index,
											scope.row.deliveryDay,
											'deliveryDay'
										)
									"
									autocomplete="off"
									class="el-input__inner"
									placeholder=" "
									v-if="scope.row.isDeliveryDay"
									v-model.lazy="scope.row.deliveryDay"
								/>
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="当前需求"
							prop="currNeed"
							sortable="custom"
							width="96"
						>
							<template #default="scope">
								{{
									(scope.row.currNeed =
										scope.row.currNeed === null
											? 0
											: scope.row.currNeed)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="应备库存"
							prop="readyStock"
							sortable="custom"
							width="96"
						>
							<template #default="scope">
								{{
									(scope.row.readyStock =
										scope.row.readyStock === null
											? 0
											: scope.row.readyStock)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="实际库存"
							prop="realStock"
							sortable="custom"
							width="96"
						>
							<template #default="scope">
								{{
									(scope.row.realStock =
										scope.row.realStock === null
											? 0
											: scope.row.realStock)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="供应商库存"
							prop="supplierStock"
							sortable="custom"
							width="112"
						>
							<template #default="scope">
								{{
									(scope.row.supplierStock =
										scope.row.supplierStock === null
											? 0
											: scope.row.supplierStock)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="备料中"
							prop="planNumber"
							sortable="custom"
							width="96"
						>
							<template #default="scope">
								{{
									(scope.row.planNumber =
										scope.row.planNumber === null
											? 0
											: scope.row.planNumber)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="状态(实际)"
							prop="realStockStatus"
							width="120"
						>
							<template #default="scope">{{
								scope.row.realStockStatus + '%'
							}}</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="状态(实际+备料中)"
							prop="allStockStatus"
							width="150"
						>
							<template #default="scope">{{
								scope.row.allStockStatus + '%'
							}}</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="税率%"
							prop="tariff"
							width="72"
						>
							<template #default="scope">
								{{
									(scope.row.tariff =
										scope.row.tariff === null
											? 0
											: scope.row.tariff)
								}}
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							label="含税单价"
							prop="purchasePrice"
							width="110"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>含税单价
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isPurchasePrice">{{
									scope.row.purchasePrice
								}}</span>
								<input
									:id="'purchasePrice' + scope.$index"
									:maxlength="11"
									@blur="
										taxPriceNumberRex(
											scope.row.purchasePrice,
											scope.row,
											'purchasePrice'
										)
									"
									autocomplete="off"
									class="el-input__inner"
									placeholder=" "
									v-if="scope.row.isPurchasePrice"
									v-model.lazy="scope.row.purchasePrice"
								/>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="下单仓库"
							prop="stockId"
							width="150"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>下单仓库
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isStockId">{{
									getNameArr(
										statusForm.stocks,
										scope.row.stockId
									)
								}}</span>
								<el-select
									:id="'stockId' + scope.$index"
									placeholder=" "
									v-if="scope.row.isStockId"
									v-model="scope.row.stockId"
								>
									<el-option
										:key="item.id"
										:label="item.name"
										:value="item.id"
										class="f_12"
										v-for="item in statusForm.stocks"
									></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column
							align="left"
							label="下单备注"
							prop="remark"
							width="280"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>下单备注
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isRemark">{{
									scope.row.remark
								}}</span>
								<input
									:id="'remark' + scope.$index"
									:key="scope.row.id"
									autocomplete="off"
									class="el-input__inner"
									maxlength="2000"
									placeholder=" "
									v-if="scope.row.isRemark"
									v-model.lazy="scope.row.remark"
								/>
							</template>
						</el-table-column>
						<el-table-column
							align="right"
							fixed="right"
							label="应下单数量"
							prop="number"
							sortable="custom"
							width="140"
						>
							<template #header>
								<span
									class="iconfont icon-bianji1 iconfont-mg"
								></span
								>应下单数量
							</template>
							<template #default="scope">
								<span v-if="!scope.row.isNumber">{{
									scope.row.number
								}}</span>
								<input
									:id="'number' + scope.$index"
									:ref="'number' + scope.$index"
									@blur="
										saleNumber(
											scope.row.index,
											scope.row.number,
											'number',
											scope.row.precision
										)
									"
									autocomplete="off"
									autofocus
									class="el-input__inner"
									maxlength="19"
									placeholder
									v-if="scope.row.isNumber"
									v-model.lazy="scope.row.number"
								/>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<!-- 底部 -->
				<div class="sale-page-footer">
					<div class="footer-left"></div>
					<div class="footer-right">
						<el-pagination
							:page-size="pageSize"
							:page-sizes="pagingList"
							:pager-count="5"
							:total="totalItemNumber"
							@current-change="handleCurrentChange"
							@size-change="handleSizeChange"
							layout="slot,sizes,total, prev,pager, next,jumper"
							popper-class="每页显示"
						>
							<span class="total-select-item">
								共选中
								<text
									style="
										text-align: center;
										color: #4178d5;
										padding: 0 1px;
									"
									>{{ selectItem }}</text
								>行
							</span>
						</el-pagination>
					</div>
					<div class="footer-pagination-total-page">
						<span>共{{ totalPageNumber }}页</span>
					</div>
				</div>
				<!-- 批量修改 -->
				<el-dialog v-model="dialogDownVisible" width="20%">
					<div class="dialog-header">
						<span>{{ '批量修改' }}</span>
					</div>
					<div class="dialog-table">
						<div class="editDialog">
							<span> <i style="color: red">*</i>交期天数 </span>
							<span>
								<el-input
									placeholder=" "
									v-model="details.deliveryDay"
								></el-input>
							</span>
						</div>
						<div class="editDialog">
							<span> <i style="color: red">*</i>物料属性 </span>
							<span>
								<el-select
									placeholder="请选择"
									v-model="details.materialPropertyKey"
								>
									<el-option
										:key="key + index"
										:label="value"
										:value="key"
										v-for="(
											value, key, index
										) in statusForm.materialPropertys"
									></el-option>
								</el-select>
							</span>
						</div>
						<div class="editDialog">
							<span>
								<i style="color: red">*</i>供应组织/供应商
							</span>
							<span>
								<el-select
									:remote-method="getSuppOrgSerachEdit"
									filterable
									placeholder="请选择"
									remote
									reserve-keyword
									v-model="details.supplyOrgOrSupplier"
								>
									<el-option
										:key="item.id"
										:label="item.name"
										:value="item.id"
										@click="
											pushDownCom(
												details.supplyOrgOrSupplier,
												'supplyOrgOrSupplier'
											)
										"
										v-for="item in statusForm.supplierOrgsEdit"
									></el-option>
								</el-select>
							</span>
						</div>
						<div class="editDialog">
							<span> <i style="color: red">*</i>下单仓库 </span>
							<span>
								<el-select
									placeholder="请选择"
									v-model="details.stockId"
								>
									<el-option
										:key="item.id"
										:label="item.name"
										:value="item.id"
										v-for="item in statusForm.stocks"
									></el-option>
								</el-select>
							</span>
						</div>
					</div>
					<template #footer>
						<span class="dialog-footer">
							<el-button
								@click="dialogDownVisible = false"
								size="small"
								type="primary"
								>取消</el-button
							>
							<el-button
								@click="sureDownOrder"
								size="small"
								type="primary"
								>确定</el-button
							>
						</span>
					</template>
				</el-dialog>
				<!-- 下单结果 -->
				<el-dialog
					title="下单结果"
					v-model="dialogVisibleDwon"
					width="47.1%"
				>
					<div class="sale-page-table-body">
						<el-table
							:data="tableInfo"
							:header-cell-class-name="headerRigthMethod"
							border
							class="table-box"
							height="300"
							id="tableInfo-table"
						>
							<el-table-column
								label="物料编码"
								prop="materialNumber"
								width="150"
							></el-table-column>
							<el-table-column
								label="物料名称"
								prop="materialName"
								width="150"
							></el-table-column>
							<el-table-column
								label="单据类型"
								prop="orderType"
								width="150"
							></el-table-column>
							<el-table-column
								label="单编编号"
								prop="orderNo"
								width="150"
							></el-table-column>
							<el-table-column
								label="状态"
								prop="isSuccess"
								width="100"
							>
								<template #default="scope">
									<span>{{
										scope.row.isSuccess === true
											? '成功'
											: '失败'
									}}</span>
								</template>
							</el-table-column>
							<el-table-column
								label="失败原因"
								prop="msg"
								width="130"
							>
								<template #default="scope">
									<el-tooltip placement="top">
										<template #content>{{
											scope.row.msg
										}}</template>
										<span>{{ scope.row.msg }}</span>
									</el-tooltip>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<template #footer>
						<span class="dialog-footer">
							<el-button
								@click="
									handelhtmlToExcel(
										'tableInfo-table',
										'下单结果'
									)
								"
								size="small"
								type="primary"
							>
								导 出
							</el-button>
							<el-button
								@click="dialogVisibleDwon = false"
								size="small"
								type="primary"
								>关 闭</el-button
							>
						</span>
					</template>
				</el-dialog>
			</div>
		</div>
	</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { exporthandel, htmlToExcel } from '@/utils/pubulic.js';
import { getArrayName, getObjectName, orderCopy } from '@/utils/takeMethods.js';
import { Decimal } from 'decimal.js';
export default {
	name: 'SupplySemiProdut',
	inject: ['reload'],
	data() {
		return {
			recordIndex: '',
			isDisable: false,
			supplierOrgId: '', // 供应商组织or供应商
			material: '', // 物料编码
			ProduceMaterial: '', // 成品sku
			supplierList: [],
			statusForm: {
				supplierOrgs: [], // 供应商组织or供应商
				supplierOrgsEdit: [],
				materials: [], // 物料编码
				materialSkus: [], // 产品sku
				materialPropertys: [], // 物料属性
				stocks: [], // 下单仓库
				supplys: [], // 供应商
				matterCodelist: [], // 产品
			},
			search: {
				// 列表请求参数
				pageNo: 1,
				pageSize: 50,
				orgId:
					this.$store.state &&
					this.$store.state.org &&
					this.$store.state.org.orgId === ''
						? this.orgIdArr[0].id
						: this.$store.state.org.orgId,
			},
			details: {
				deliveryDay: '',
				materialPropertyKey: '',
				supplyOrgOrSupplier: '',
				stockId: '',
				supplierId: '',
				supplyOrgId: '',
			}, // 修改的详情
			isLoading: false,
			dialogDownVisible: false, // 批量修改
			titleSku: 'ORICO-PHM-25-BK-EP',
			pageSize: 50, // 页数
			containerHeight: '', // body容器高度
			tableLoading: false, // 加载
			pagingSaleNumber: '', // 调出数量
			pagingList: [50, 100, 150], // 底部分页
			totalItemNumber: 0,
			totalPageNumber: 0,
			selectItem: 0, // 共选择的条目数
			tableData: [], // 表格数据
			heightNum: 0, // 搜索高度
			windowHeight: 0, // 屏幕高度
			multipleSelection: [], // 选择的条目
			actionType: '', // 操作类型
			btnType: [
				'add',
				'push-order',
				'batch-edit',
				'out-export',
				'copy',
				'submit',
				'revoke',
				'audit',
				'de-approval',
				'delete',
				'push-down',
				'operation',
				'query',
				'save',
				'split-order',
				'print-aterial-list',
				'finish',
				'close-case',
				'de-excute-start',
				'de-excute-finish',
				'de-close',
				'close',
			], // 禁用按钮
			recordCurrIndex: [],
			dialogVisibleDwon: false,
			tableInfo: [],
			tempDetails: {
				ProduceMaterial: '',
				orgId: '',
				materialPropertyType: '',
				supplyOrgId: '',
				supplierId: '',
				deliveryDay: '',
				purchasePrice: '',
			},
		};
	},
	methods: {
		getNameArr(arr, val) {
			return getArrayName(arr, val);
		},
		getNameObj(arr, val) {
			return getObjectName(arr, val);
		},
		getRowCol(row, column, cell) {
			let _that = this;
			_that.tableData.forEach((item) => {
				item.isMaterialPropertyKey = false;
				item.isSupplyOrgOrSupplier = false;
				item.isDeliveryDay = false;
				item.isPurchasePrice = false;
				item.isStockId = false;
				item.isRemark = false;
				item.isNumber = false;
			});
			// if (_that.recordIndex != '' || _that.recordIndex == '0') {
			// 	_that.tableData[row.index].isMaterialPropertyKey = false;
			// 	_that.tableData[row.index].isSupplyOrgOrSupplier = false;
			// 	_that.tableData[row.index].isDeliveryDay = false;
			// 	_that.tableData[row.index].isPurchasePrice = false;
			// 	_that.tableData[row.index].isStockId = false;
			// 	_that.tableData[row.index].isRemark = false;
			// 	_that.tableData[row.index].isNumber = false;
			// }
			switch (column.label) {
				case '物料属性':
					row.isMaterialPropertyKey = true;
					_that.recordIndex = row.index;
					break;
				case '供应组织/供应商':
					row.isSupplyOrgOrSupplier = true;
					_that.recordIndex = row.index;
					break;
				case '交期天数':
					row.isDeliveryDay = true;
					_that.recordIndex = row.index;
					break;
				case '含税单价':
					row.isPurchasePrice = true;
					_that.recordIndex = row.index;
					break;
				case '下单仓库':
					row.isStockId = true;
					_that.recordIndex = row.index;
					break;
				case '下单备注':
					row.isRemark = true;
					_that.recordIndex = row.index;
					break;
				case '应下单数量':
					row.isNumber = true;
					_that.recordIndex = row.index;
					break;
			}
			//   获取焦点
			this.$nextTick(() => {
				let strArr = [
					'物料属性',
					'供应组织/供应商',
					'交期天数',
					'含税单价',
					'下单仓库',
					'下单备注',
				];
				if (strArr.indexOf(column.label) !== -1) {
					document
						.getElementById(column.property + row.index)
						.focus();
				}
				if (column.label == '应下单数量') {
					this.$refs[column.property + row.index].focus();
				}
			});
		},
		onSortTime(column) {
			if (column.order == 'ascending') {
				// 升
				this.tableData.sort(this.compare(column.prop, 'asc'));
			} else if (column.order == 'descending') {
				// 降
				this.tableData.sort(this.compare(column.prop, 'des'));
			} else {
				this.tableData.sort(this.compare('materialNumber'));
			}
		},
		compare(key, type) {
			if (type === 'asc') {
				return function (a, b) {
					let valO = a[key];
					let valT = b[key];
					return valO - valT;
				};
			} else if (type === 'des') {
				return function (a, b) {
					let valO = a[key];
					let valT = b[key];
					return valT - valO;
				};
			} else {
				return function (a, b) {
					let valO = a[key];
					let valT = b[key];
					return valT > valO ? 1 : valO > valT ? -1 : 0;
				};
			}
		},
		// 操作弹框导出
		handelhtmlToExcel(domid, title) {
			htmlToExcel(domid, title);
			this.dialogVisibleDwon = false;
		},
		taxPriceNumberRex(val, row, key) {
			let numD = '';
			let count = '\\d';
			for (let index = 0; index < 4; index++) {
				numD = numD + count;
			}
			let reg = '/^(-)*(\\d+)\\.(' + numD + ').*$/';
			if (val) {
				this.tableData[row.index][key] = val
					.toString()
					.replace(/[^\d.]/g, '')
					.replace(/\.{2,}/g, '.')
					.replace(/^\./g, '')
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
					.replace(eval(reg), '$1$2.$3');
			} else {
				this.tableData[row.index][key] = 0;
			}
			this.upDataRow(row.index, this.tableData[row.index][key], key);
		},
		saleNumber(index, val, key, precision) {
			if (val) {
				if (precision == 0 || precision == null) {
					this.tableData[index][key] = val
						.toString()
						.replace(/\D\./g, '');
					this.tableData[index][key] =
						Decimal(this.tableData[index][key]).toFixed(
							0,
							Decimal.ROUND_DOWN
						) * 1;
				} else {
					let numD = '';
					let count = '\\d';
					for (let ind = 0; ind < precision; ind++) {
						numD = numD + count;
					}
					let reg = '/^(-)*(\\d+)\\.(' + numD + ').*$/';
					this.tableData[index][key] = val
						.toString()
						.replace(/[^\d^\\.]+/g, '')
						.replace('.', '$#$')
						.replace(/\./g, '')
						.replace('$#$', '.')
						.replace(eval(reg), '$1$2.$3');
				}
			}
		},
		saleNum(index, val, key) {
			//  输入整数
			if (val) {
				this.tableData[index][key] = val
					.toString()
					.replace(/[^\d]/g, '')
					.replace(/(^\s*)|(\s*$)/g, '');
			} else {
				this.tableData[index][key] = 0;
			}
			this.upDataRow(index, this.tableData[index][key], key);
		},
		upDataRow(ind, val, key) {
			if (key === 'purchasePrice') {
				if (!isNaN(val)) {
					this.requestDataRow(ind, val, key);
				}
			} else if (key === 'deliveryDay') {
				if (!isNaN(val)) {
					if (val.toString().charAt(val.length - 1) != '.') {
						this.requestDataRow(ind, val, key);
					}
				}
			} else {
				this.requestDataRow(ind, val, key);
			}
		},
		requestDataRow(ind, val, key) {
			let tempMaterialPropertyKey = [];
			let tempMaterialId = [];
			let tempMaterialIdS = [];
			let tempSupplyOrgId = [];
			let tempSupplierId = [];
			let tempDeliveryDay = [];
			let tempPurchasePrice = [];
			let requestData = {
				details: [
					{
						materialId: '',
						materialPropertyType: '',
						ProduceMaterial: '',
						supplyOrgId: '',
						supplierId: '',
						deliveryDay: '',
						purchasePrice: '',
						orgId: '',
					},
				],
			};
			tempMaterialPropertyKey = this.tableData.map(
				(it) => it.materialPropertyKey
			);
			tempMaterialId = this.tableData.map((it) => it.ProduceMaterial);
			tempMaterialIdS = this.tableData.map((it) => it.materialId);
			tempSupplyOrgId = this.tableData.map((it) => it.supplyOrgId);
			tempSupplierId = this.tableData.map((it) => it.supplierId);
			tempDeliveryDay = this.tableData.map((it) => it.deliveryDay);
			tempPurchasePrice = this.tableData.map((it) => it.purchasePrice);
			requestData.details[0].materialPropertyType =
				tempMaterialPropertyKey[ind];
			requestData.details[0].ProduceMaterial = tempMaterialId[ind];
			requestData.details[0].materialId = tempMaterialIdS[ind];
			requestData.details[0].deliveryDay = tempDeliveryDay[ind];
			requestData.details[0].purchasePrice = tempPurchasePrice[ind];
			requestData.details[0].orgId = this.$store.state.org
				? this.$store.state.org.orgId
				: null;

			if (tempSupplyOrgId[ind]) {
				requestData.details[0].supplyOrgId =
					tempSupplyOrgId[ind].toString().substr(0, 1) == 'z'
						? Number(tempSupplyOrgId[ind].toString().substr(1))
						: tempSupplyOrgId[ind];
			} else {
				requestData.details[0].supplyOrgId = null;
			}

			if (tempSupplierId[ind]) {
				requestData.details[0].supplierId =
					tempSupplierId[ind].toString().substr(0, 1) == 'g'
						? Number(tempSupplierId[ind].toString().substr(1))
						: tempSupplierId[ind];
			} else {
				requestData.details[0].supplierId = null;
			}

			this.$http
				.showLoading(false)
				.post('Materials/EditMaterial', requestData)
				.then((r) => {
					if (r.status === 200) {
						// console.log(r.message)
					}
				});
		},
		async matterCodeChange(val, ind) {
			// 获取物料编码信息
			if (val && this.$store.state.org.orgId) {
				this.statusForm.matterCodelist = await this.backMaterSkuMethods(
					val,
					'Specifications',
					this.$store.state.org.orgId
				);
			} else {
				this.statusForm.matterCodelist = [];
			}
		},
		getSuppOrgSerachEdit(val) {
			if (val === '') {
				this.statusForm.supplierOrgsEdit = [];
			} else {
				this.statusForm.supplierOrgsEdit = [];
				let query = {
					name: val,
				};
				this.$http
					.showLoading(false)
					.get('HalfProduct/GetSupplierAndOrganizationsList', query)
					.then((r) => {
						if (r.status === 200) {
							this.statusForm.supplierOrgsEdit = r.data;
						}
					});
			}
		},
		getSuppOrgSerach(val) {
			if (val === '') {
				this.statusForm.supplierOrgs = [];
			} else {
				this.statusForm.supplierOrgs = [];
				let query = {
					name: val,
				};
				this.$http
					.showLoading(false)
					.get('HalfProduct/GetSupplierAndOrganizationsList', query)
					.then((r) => {
						if (r.status === 200) {
							this.statusForm.supplierOrgs = r.data;
						}
					});
			}
		},
		getSuppOrg(val, index) {
			if (val === '') {
				this.supplierList[index] = [];
			} else {
				this.supplierList[index] = [];
				let query = {
					name: val,
				};
				this.$http
					.showLoading(false)
					.get('HalfProduct/GetSupplierAndOrganizationsList', query)
					.then((r) => {
						if (r.status === 200) {
							this.supplierList[index] = r.data;
						}
					});
			}
		},
		detailsCom(val, keyZ, keyG, row, name) {
			if (val != '' || val != null || val != 'undefined') {
				if (val.substr(0, 1) == 'g') {
					// supplierId  供应商
					this.tableData[row.index].supplierId = Number(
						val.substr(1)
					);
					this.tableData[row.index].supplyOrgId = null;
				} else {
					// supplyOrgId 供应组织
					this.tableData[row.index].supplierId = null;
					this.tableData[row.index].supplyOrgId = Number(
						val.substr(1)
					);
				}
				this.tableData[row.index].supplyOrgOrSupplier = name;
			} else {
				this.tableData[row.index].supplierId = null;
				this.tableData[row.index].supplyOrgId = null;
				this.tableData[row.index].supplyOrgOrSupplier = null;
			}
			let tempMatId = [];
			let tempMaterialPropertyKey = [];
			let tempMaterialId = [];
			let tempSupplyOrgId = [];
			let tempSupplierId = [];
			let tempDeliveryDay = [];
			let tempPurchasePrice = [];
			let requestData = {
				details: [
					{
						materialId: '',
						materialPropertyType: '',
						ProduceMaterial: '',
						supplyOrgId: '',
						supplierId: '',
						deliveryDay: '',
						purchasePrice: '',
						orgId: '',
					},
				],
			};
			tempMatId = this.tableData.map((it) => it.materialId);
			tempMaterialPropertyKey = this.tableData.map(
				(it) => it.materialPropertyKey
			);
			tempMaterialId = this.tableData.map((it) => it.ProduceMaterial);
			tempSupplyOrgId = this.tableData.map((it) => it.supplyOrgId);
			tempSupplierId = this.tableData.map((it) => it.supplierId);
			tempDeliveryDay = this.tableData.map((it) => it.deliveryDay);
			tempPurchasePrice = this.tableData.map((it) => it.purchasePrice);
			requestData.details[0].materialPropertyType =
				tempMaterialPropertyKey[row.index];
			requestData.details[0].ProduceMaterial = tempMaterialId[row.index];
			requestData.details[0].supplyOrgId = tempSupplyOrgId[row.index];
			requestData.details[0].supplierId = tempSupplierId[row.index];
			requestData.details[0].deliveryDay = tempDeliveryDay[row.index];
			requestData.details[0].purchasePrice = tempPurchasePrice[row.index];
			requestData.details[0].materialId = tempMatId[row.index];
			requestData.details[0].orgId = this.$store.state.org
				? this.$store.state.org.orgId
				: null;
			this.$http.post('Materials/EditMaterial', requestData).then((r) => {
				if (r.status === 200) {
					// console.log(r.message)
				}
			});
		},
		async sureDownOrder() {
			if (
				this.details.deliveryDay &&
				this.details.materialPropertyKey &&
				this.details.stockId
			) {
				this.dialogDownVisible = false;
				let pushData = {
					details: [
						{
							ProduceMaterial: '',
							materialId: '',
							orgId: '',
							materialPropertyType: '',
							supplyOrgId: '',
							supplierId: '',
							deliveryDay: '',
							purchasePrice: '',
						},
					],
				};
				for (
					let index = 0;
					index < this.multipleSelection.length - 1;
					index++
				) {
					pushData.details.push({
						ProduceMaterial: '',
						materialId: '',
						orgId: '',
						materialPropertyType: '',
						supplyOrgId: '',
						supplierId: '',
						deliveryDay: '',
						purchasePrice: '',
					});
				}
				pushData.details.forEach((el, ind) => {
					pushData.details[ind].materialPropertyType =
						this.details.materialPropertyKey;
					pushData.details[ind].deliveryDay =
						this.details.deliveryDay;
					pushData.details[ind].stockId = this.details.stockId;
					pushData.details[ind].supplierId = this.details.supplierId;
					pushData.details[ind].supplyOrgId =
						this.details.supplyOrgId;
					pushData.details[ind].orgId = this.$store.state.org
						? this.$store.state.org.orgId
						: null;
				});
				this.multipleSelection.forEach((ele, indx) => {
					pushData.details[indx].ProduceMaterial =
						ele.ProduceMaterial;
					pushData.details[indx].purchasePrice = ele.purchasePrice;
					pushData.details[indx].materialId = ele.materialId;
				});
				pushData.details.forEach((element) => {
					if (element.supplyOrgId) {
						element.supplyOrgId =
							element.supplyOrgId.toString().substr(0, 1) == 'z'
								? Number(
										element.supplyOrgId.toString().substr(1)
								  )
								: element.supplyOrgId;
					} else {
						element.supplyOrgId = null;
					}

					if (element.supplierId) {
						element.supplierId =
							element.supplierId.toString().substr(0, 1) == 'g'
								? Number(
										element.supplierId.toString().substr(1)
								  )
								: element.supplierId;
					} else {
						element.supplierId = null;
					}
				});
				await this.$http
					.post('Materials/EditMaterial', pushData)
					.then((r) => {
						if (r.status === 200) {
							this.getList(
								this.search,
								'yes',
								this.multipleSelection,
								this.details.stockId
							);
						}
					});
				this.multipleSelection = [];
			} else {
				this.$message.error({
					message: '修改内容不能为空!',
					showClose: true,
				});
			}
		},
		actionhandel(type) {
			// 顶部公共按钮操作
			this.actionType = type;
			if (this.multipleSelection && this.multipleSelection.length > 0) {
				let ids = [
					...new Set(
						this.multipleSelection.map((it) => {
							return it.id;
						})
					),
				];
				if (ids) {
					this.search.ids = ids;
				}
			} else {
				this.search.ids = [];
			}
			if (type === 'push-order') {
				// 下单
				if (this.multipleSelection.length > 0) {
					let tempList = this.multipleSelection.filter(
						(it) => it.number == 0
					);
					let str = '';
					if (tempList.length > 0) {
						tempList.forEach((element, index) => {
							index < tempList.length - 1
								? (str += element.materialNumber + '、')
								: (str += element.materialNumber);
						});
						this.$message.error({
							message: '物料：' + str + ',下单数量必须大于0!',
							showClose: true,
						});
					} else {
						this.isDisable = true;
						setTimeout(() => {
							this.isDisable = false;
						}, 2000);
						this.multipleSelection.forEach((element) => {
							if (typeof element.supplierId === 'string') {
								if (element.supplierId.substr(0, 1) === 'g') {
									element.supplierId = Number(
										element.supplierId.substr(1)
									);
								}
							}
							if (typeof element.supplyOrgId === 'string') {
								if (element.supplyOrgId.substr(0, 1) === 'z') {
									element.supplyOrgId = Number(
										element.supplyOrgId.substr(1)
									);
								}
							}
							element.number = Number(element.number);
						});
						let query = {
							orgId: this.$store.state.org
								? this.$store.state.org.orgId
								: null,
							details: this.multipleSelection,
						};
						this.$http
							.post('HalfProduct/Order', query)
							.then((r) => {
								if (r.status === 200) {
									this.dialogVisibleDwon = true;
									this.tableInfo = r.data;
									this.getList(this.search);
								}
							});
					}
				} else {
					this.$message.error({
						message: '请先选择要下单的物料',
						showClose: true,
					});
				}
			}
			if (type === 'out-export') {
				this.isDisable = true;
				setTimeout(() => {
					this.isDisable = false;
				}, 2000);
				// 导出
				exporthandel('HalfProduct/Export', this.search);
			}
			if (type === 'batch-edit') {
				// 批量修改
				// console.log('this.multipleSelection', this.multipleSelection)
				let deliveryDayList = [];
				let materialPropertyKeyList = [];
				let supplyOrgOrSupplierList = [];
				let stockIdList = [];
				let supplierIdList = [];
				let supplyOrgIdList = [];
				this.multipleSelection.forEach((el) => {
					deliveryDayList.push(el.deliveryDay);
					materialPropertyKeyList.push(el.materialPropertyKey);
					supplyOrgOrSupplierList.push(el.supplyOrgOrSupplier);
					stockIdList.push(el.stockId);
					supplierIdList.push(el.supplierId);
					supplyOrgIdList.push(el.supplyOrgId);
				});
				deliveryDayList = [...new Set(deliveryDayList)];
				materialPropertyKeyList = [...new Set(materialPropertyKeyList)];
				supplyOrgOrSupplierList = [...new Set(supplyOrgOrSupplierList)];
				stockIdList = [...new Set(stockIdList)];
				supplierIdList = [...new Set(supplierIdList)];
				supplyOrgIdList = [...new Set(supplyOrgIdList)];

				deliveryDayList.length == 1
					? (this.details.deliveryDay = deliveryDayList[0])
					: (this.details.deliveryDay = '');
				materialPropertyKeyList.length == 1
					? (this.details.materialPropertyKey =
							materialPropertyKeyList[0])
					: (this.details.materialPropertyKey = '');
				stockIdList.length == 1
					? (this.details.stockId = stockIdList[0])
					: (this.details.materialPropertyKey = '');
				if (supplyOrgOrSupplierList.length == 1) {
					this.getSuppOrgSerachEdit(supplyOrgOrSupplierList[0]);
					this.details.supplyOrgOrSupplier =
						supplyOrgOrSupplierList[0];
					this.details.supplierId = supplierIdList[0];
					this.details.supplyOrgId = supplyOrgIdList[0];
				} else {
					this.details.supplyOrgOrSupplier = '';
					this.statusForm.supplierOrgsEdit = [];
				}
				if (this.multipleSelection.length > 0) {
					this.isDisable = true;
					setTimeout(() => {
						this.isDisable = false;
					}, 2000);
					this.dialogDownVisible = true;
				} else {
					this.$message.error({
						message: '请先选择要修改的物料',
						showClose: true,
					});
				}
			}
			if (type === 'refresh') {
				this.isDisable = true;
				setTimeout(() => {
					this.isDisable = false;
				}, 2000);
				// 全局刷新
				this.$http.get('HalfProduct/Refresh').then((r) => {
					if (r.status === 200) {
						if (r.success == true) {
							this.$message.success({
								message: r.message,
								showClose: true,
							});
							this.getList(this.search);
						} else {
							this.$message.error({
								message: r.message,
								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.getList(this.search);
				}
			});
		},
		headerBg({ columnIndex }) {
			// 表头居右
			if (columnIndex === 30) {
				return `text-align:right!important;`;
			}
		},

		headerRigthMethod({ row, column, rowIndex, columnIndex }) {
			return 'headerRight';
		},
		handleSelectionChange(val) {
			// 表格选中条目发生改变
			this.selectItem = val.length;
			this.multipleSelection = val;
			this.recordCurrIndex = this.multipleSelection.map((it) => it.index);
		},
		handleSizeChange(val) {
			// 每页条数
			this.pageSize = val;
			this.totalPageNumber = Math.ceil(
				this.totalItemNumber / this.pageSize
			);
			this.getList(this.search);
		},
		handleCurrentChange(val) {
			// 分页当前页切换
			this.search.pageNo = val;
			this.getList(this.search);
		},
		getList(search, isTrue, obj, id) {
			// 列表请求
			this.tableLoading = true;
			this.$http
				.post('HalfProduct/HalfProductQuery', search)
				.then((req) => {
					if (req.status == 200) {
						this.tableLoading = false;
						this.tableData = req.data;
						if (this.tableData.length > 0) {
							this.tableData.forEach((element, index) => {
								element.isDeliveryDay = false;
								element.isMaterialPropertyKey = false;
								element.isSupplyOrgOrSupplier = false;
								element.isDeliveryDay = false;
								element.isPurchasePrice = false;
								element.isStockId = false;
								element.isRemark = false;
								element.isNumber = false;
								element.materialPropertyKey =
									element.materialPropertyKey + '';
								this.supplierList[index] =
									element.supplyOrgList || [];
								if (isTrue) {
									let val = '';
									if (element.supplierId) {
										val = element.supplierId;
									}
									if (element.supplyOrgId) {
										val = element.supplyOrgId;
									}
									if (
										val != '' ||
										val != null ||
										val != 'undefined'
									) {
										if (val.substr(0, 1) == 'g') {
											// supplierId  供应商
											this.tableData[index].supplierId =
												Number(val.substr(1));
											this.tableData[index].supplyOrgId =
												null;
										} else {
											// supplyOrgId 供应组织
											this.tableData[index].supplierId =
												null;
											this.tableData[index].supplyOrgId =
												Number(val.substr(1));
										}
									} else {
										this.tableData[index].supplierId = null;
										this.tableData[index].supplyOrgId =
											null;
									}
								}
								if (obj) {
									obj.forEach((ele) => {
										if (
											element.ProduceMaterial ===
											ele.ProduceMaterial
										) {
											element.stockId = id;
										}
									});
								}
								element.isMaterialPropertyKey = false;
								element.isSupplyOrgOrSupplier = false;
								element.isDeliveryDay = false;
								element.isPurchasePrice = false;
								element.isStockId = false;
								element.isRemark = false;
								element.isNumber = false;
							});
						}
						this.totalItemNumber = req.totalCount;
						this.totalPageNumber = Math.ceil(
							this.totalItemNumber / this.pageSize
						);
					}
				});
		},
		searchList() {
			// 搜索
			this.getList(this.search);
		},
		cellStyle({ row, column, rowIndex, columnIndex }) {
			row.index = rowIndex;
			column.index = columnIndex;
		},
		cellColor({ row, column, rowIndex, columnIndex }) {
			row.index = rowIndex;
			column.index = columnIndex;
			if (columnIndex == 13) {
				if (row.realStockStatus >= 120) {
					return 'color: #fff;background-color:#A0A0A0;';
				}
				if (row.realStockStatus < 120 && row.realStockStatus >= 100) {
					return 'color: #fff;background-color: #77CB44;';
				}
				if (row.realStockStatus < 100 && row.realStockStatus > 0) {
					return 'color: #fff;background-color: #F33B3B;';
				}
				if (row.realStockStatus == 0) {
					return 'color: #fff;background-color: #000;';
				}
			}
			if (columnIndex == 14) {
				if (row.allStockStatus >= 120) {
					return 'color: #fff;background-color:#A0A0A0;';
				}
				if (row.allStockStatus < 120 && row.allStockStatus >= 100) {
					return 'color: #fff;background-color: #77CB44;';
				}
				if (row.allStockStatus < 100 && row.allStockStatus > 0) {
					return 'color: #fff;background-color: #F33B3B;';
				}
				if (row.allStockStatus == 0) {
					return 'color: #fff;background-color: #000;';
				}
			}
		},
		// 星星
		mustAfter({ row, column, rowIndex, columnIndex }) {
			let arry = [17, 19];
			if (arry.indexOf(columnIndex) !== -1) {
				return 'must';
			}
		},
		pushDownCom(val, key, type) {
			if (key === 'supplyOrgOrSupplier') {
				if (val != '') {
					if (val.substr(0, 1) == 'g') {
						// supplierId
						this.details.supplierId = Number(val.substr(1));
						this.details.supplyOrgId = null;
					} else {
						// supplyOrgId
						this.details.supplierId = null;
						this.details.supplyOrgId = Number(val.substr(1));
					}
				} else {
					this.details.supplierId = null;
					this.details.supplyOrgId = null;
				}
			} else {
				this.search[key] = val;
			}
		},
		searchCom(val, key, type) {
			// 搜索公共方法
			if (key === 'supplierOrgId') {
				if (val != '') {
					if (val.substr(0, 1) == 'g') {
						// supplierId
						this.search.supplierId = Number(val.substr(1));
						this.search.supplyOrgId = null;
						delete this.search.supplyOrgId;
					} else {
						// supplyOrgId
						this.search.supplierId = null;
						this.search.supplyOrgId = Number(val.substr(1));
						delete this.search.supplierId;
					}
				} else {
					this.search.supplierId = null;
					this.search.supplyOrgId = null;
					delete this.search.supplierId;
					delete this.search.supplyOrgId;
				}
				this.getList(this.search);
			} else {
				this.search[key] = val;
				this.getList(this.search);
			}
		},
		clearCom(val, key) {
			// 删除的公共方法
			if (!val) {
				if (key === 'supplierOrgId') {
					delete this.search.supplyOrgId;
					delete this.search.supplierId;
					// this.getList(this.search)
				} else {
					if (key === 'material') {
						delete this.search[key];
					} else {
						delete this.search[key];
						// this.getList(this.search)
					}
				}
			} else {
				this.search[key] = val;
			}
		},
		Init() {
			this.windowHeight = document.documentElement.clientHeight; // 计算表格高度和底部位置
			this.heightNum = this.windowHeight - 258; // 计算表格高度
			this.containerHeight = this.windowHeight - 102; // 计算容器的高度
			this.getList(this.search, 'yes'); // 获取列表
			this.getDownOrg(); // 获取下单组织
			if (
				this.bomMaterilasObj &&
				JSON.stringify(this.bomMaterilasObj) !== '{}'
			) {
				this.statusForm.materialPropertys =
					this.bomMaterilasObj.materialPropertyType;
			} else {
				this.$http.get('Materials/GetStatus').then((r) => {
					if (r.status == 200) {
						this.setBomMaterilasObj(r.data);
						this.statusForm.materialPropertys =
							r.data.materialPropertyType;
					}
				});
			}
		},
		resetSearch() {
			let arr = [
				'supplierOrgId',
				'supplierId',
				'supplyOrgId',
				'material',
				'ProduceMaterial',
			];
			for (let index = 0; index < arr.length; index++) {
				this[arr[index]] = '';
			}
			this.search = {
				pageNo: this.pageNo,
				pageSize: this.pageSize,
				orgId: this.$store.state.org
					? this.$store.state.org.orgId
					: null,
			};
			this.getList(this.search);
		},
		async backMaterSkuMethods(val, key, id) {
			// 匹配物料sku的方法
			return this.$http
				.showLoading(false)
				.post('SysConfig/GetMaterial', {
					name: val,
					file: key,
					orgId: id,
					isProduct: true,
				})
				.then((res) => {
					if (res.status === 200) {
						return res.data;
					} else {
						return [];
					}
				});
		},
		async skuCodeChange(val) {
			// 获取型号SKU信息
			if (val) {
				this.statusForm.specificationsList =
					await this.backMaterSkuMethods(
						val,
						'Specifications',
						this.$store.state.org
							? this.$store.state.org.orgId
							: null
					);
			} else {
				this.statusForm.specificationsList = [];
			}
		},
		// 订单号 复制按钮
		saleOrderCopy() {
			orderCopy();
		},
		getDownOrg() {
			this.$http
				.get(
					'SysConfig/GetWarehouseByOrg/' + this.$store.state.org.orgId
				)
				.then((r) => {
					if (r.status == 200) {
						this.statusForm.stocks = r.data;
					}
				});
		},
		...mapActions({
			setBomMaterilasObj: 'storeData/setBomMaterilasObj',
		}),
	},
	computed: {
		...mapState({
			orgIdArr: (state) => state.user.orgIdArr,
			getDeptId: (state) => state.org.orgId,
			bomMaterilasObj: (state) => state.storeData.bomMaterilasObj,
		}),
		orgIdChange() {
			// 监听ID
			return this.$store.state && this.$store.state.org
				? this.$store.state.org.orgId
				: null;
		},
	},
	activated() {
		this.$refs.fileTable.clearSelection();
	},
	created: function () {
		this.Init();
	},
	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, 'yes');
			this.getDownOrg();
		},
	},
};
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderList.scss';
@import '@/assets/style/211/playCom.scss';
@import '@/assets/style/211/semiProdut.scss';
@import '@/assets/style/saleOrder/common.scss';
::v-deep(.el-table th.must > .cell::after) {
	content: '*';
	color: var(--el-color-danger) !important;
}
</style>
