<template>
	<div class="main-container order-mc-bg">
		<div
			class="sale-container"
			:style="{ height: containerHeight + 'px!important' }"
		>
			<toolBtn
				@actionhandel="actionhandel"
				:btnType="btnType"
				:isDisable="isDisable"
			></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
												v-model="supplierOrgId"
												filterable
												remote
												reserve-keyword
												placeholder="请选择供应组织或供应商"
												:clearable="true"
												@change="
													clearCom(
														supplierOrgId,
														'supplierOrgId'
													)
												"
												:remote-method="
													getSuppOrgSerach
												"
											>
												<el-option
													class="f_12"
													v-for="item in statusForm.supplierOrgs"
													@click="
														searchCom(
															supplierOrgId,
															'supplierOrgId'
														)
													"
													:key="item.id"
													:label="item.name"
													:value="item.id"
												></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label=" 物料">
											<el-input
												v-model.trim="material"
												placeholder="请输入物料编码/名称/规格型号"
												class="f_12"
												:input="
													clearCom(
														material,
														'material'
													)
												"
												@keyup.enter="
													searchCom(
														material,
														'material'
													)
												"
											></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-form-item label=" 父项物料">
											<el-input
												v-model.trim="ProduceMaterial"
												placeholder="请输入物料编码/名称/规格型号"
												class="f_12"
												:input="
													clearCom(
														ProduceMaterial,
														'ProduceMaterial'
													)
												"
												@keyup.enter="
													searchCom(
														ProduceMaterial,
														'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
												size="small"
												@click="resetSearch"
												>重置</el-button
											>
											<el-button
												type="primary"
												size="small"
												@click="searchList"
												>搜索</el-button
											>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<div
					class="sale-page-table-body"
					:style="{ height: heightNum + 'px' }"
				>
					<vxe-table
						border
						auto-resize
						:column-config="{ resizable: true }"
						ref="fileTable"
						header-row-class-name="table-header-row"
						row-class-name="table-body-row"
						v-loading="tableLoading"
						:max-height="heightNum"
						:cell-style="cellColor"
						:data="tableData"
						:row-config="{ isHover: true }"
						:edit-config="{ trigger: 'click', mode: 'cell' }"
						@checkbox-all="handelCheckBox"
						@checkbox-change="handleSelectionChange"
					>
						<vxe-column
							type="checkbox"
							width="40"
							align="center"
							fixed="left"
						></vxe-column>
						<vxe-column
							field="materialNumber"
							title="物料编码"
							align="left"
							width="172"
							fixed="left"
							show-overflow
						></vxe-column>
						<vxe-column
							field="materialName"
							title="物料名称"
							align="left"
							width="150"
							fixed="left"
							show-overflow
						></vxe-column>
						<vxe-column
							field="specification"
							title="规格型号(SKU)"
							align="left"
							width="280"
							show-overflow
						></vxe-column>
						<vxe-column
							field="materialBear"
							title="物料承担方"
							align="left"
							width="84"
							show-overflow
						></vxe-column>
						<vxe-column
							field="materialPropertyKey"
							title="物料属性"
							align="left"
							width="96"
							:edit-render="{}"
							show-overflow
						>
							<!-- <template #header>
                <span class="iconfont icon-bianji1 iconfont-mg"></span>物料属性
              </template> -->
							<template #default="{ row }">
								<span>{{
									getName(
										statusForm.materialPropertys,
										row.materialPropertyKey
									)
								}}</span>
							</template>
							<template #edit="{ row, rowIndex }">
								<vxe-select
									v-model="row.materialPropertyKey"
									placeholder=" "
									transfer
								>
									<vxe-option
										class="f_12"
										v-for="(
											value, key, index
										) in statusForm.materialPropertys"
										@click="
											upDataRow(
												rowIndex,
												row.materialPropertyKey,
												'materialPropertyKey'
											)
										"
										:key="key + index"
										:label="value"
										:value="key"
									></vxe-option>
								</vxe-select>
							</template>
						</vxe-column>
						<vxe-column
							field="supplyOrgOrSupplier"
							title="供应组织/供应商"
							align="left"
							width="172"
							:edit-render="{}"
							show-overflow
						>
							<template #default="{ row, rowIndex }">
								<el-select
									v-model="row.supplyOrgOrSupplier"
									filterable
									remote
									reserve-keyword
									placeholder=" "
									:remote-method="
										(query) => {
											getSuppOrg(query, rowIndex);
										}
									"
								>
									<el-option
										class="f_12"
										v-for="item in supplierList[rowIndex]"
										@click="
											detailsCom(
												row.supplyOrgOrSupplier,
												'supplyOrgId',
												'supplierId',
												rowIndex,
												item.name
											)
										"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</template>
						</vxe-column>
						<vxe-column
							field="deliveryDay"
							title="交期天数"
							align="center"
							width="83"
							show-overflow
						>
							<template #default="{ row, rowIndex }">
								<div class="el-input click-cell-ipt">
									<input
										:id="'deliveryDay' + rowIndex"
										v-model.lazy="row.deliveryDay"
										@blur="
											upDataRow(
												rowIndex,
												row.deliveryDay,
												'deliveryDay',
												row
											)
										"
										:maxlength="4"
										placeholder=" "
										class="el-input__inner"
									/>
								</div>
							</template>
						</vxe-column>
						<vxe-column
							field="currNeed"
							title="当前需求"
							align="right"
							width="100"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row }">{{
								(row.currNeed =
									row.currNeed === null ? 0 : row.currNeed)
							}}</template>
						</vxe-column>
						<vxe-column
							field="readyStock"
							title="应备库存"
							align="right"
							width="100"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row }">{{
								(row.readyStock =
									row.readyStock === null
										? 0
										: row.readyStock)
							}}</template>
						</vxe-column>
						<vxe-column
							field="realStock"
							title="实际库存"
							align="right"
							width="100"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row }">{{
								(row.realStock =
									row.realStock === null ? 0 : row.realStock)
							}}</template>
						</vxe-column>
						<vxe-column
							field="supplierStock"
							title="供应商库存"
							align="right"
							width="112"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row }">{{
								(row.supplierStock =
									row.supplierStock === null
										? 0
										: row.supplierStock)
							}}</template>
						</vxe-column>
						<vxe-column
							field="planNumber"
							title="备料中"
							align="right"
							width="100"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row }">{{
								(row.planNumber =
									row.planNumber === null
										? 0
										: row.planNumber)
							}}</template>
						</vxe-column>
						<vxe-column
							field="realStockStatus"
							title="库存状态(实际)"
							align="right"
							width="120"
							show-overflow
						>
							<template #default="{ row }">{{
								row.realStockStatus + '%'
							}}</template>
						</vxe-column>
						<vxe-column
							field="allStockStatus"
							title="库存状态(实际+备料中)"
							align="right"
							width="150"
							show-overflow
						>
							<template #default="{ row }">{{
								row.allStockStatus + '%'
							}}</template>
						</vxe-column>
						<vxe-column
							field="tariff"
							title="税率%"
							align="right"
							width="100"
							show-overflow
						>
							<template #default="{ row }">{{
								(row.tariff =
									row.tariff === null ? 0 : row.tariff)
							}}</template>
						</vxe-column>
						<vxe-column
							field="purchasePrice"
							title="含税单价"
							align="right"
							width="110"
							show-overflow
						>
							<template #default="{ row, rowIndex }">
								<div class="el-input click-cell-ipt">
									<input
										:id="'purchasePrice' + rowIndex"
										v-model.lazy="row.purchasePrice"
										@blur="
											upDataRow(
												rowIndex,
												row.purchasePrice,
												'purchasePrice'
											)
										"
										:maxlength="11"
										placeholder=" "
										class="el-input__inner"
									/>
								</div>
							</template>
						</vxe-column>
						<vxe-column
							field="stockId"
							title="下单仓库"
							align="left"
							width="150"
							show-overflow
						>
							<template #default="{ row }">
								<el-select
									v-model="row.stockId"
									placeholder=" "
								>
									<el-option
										class="f_12"
										v-for="item in statusForm.stocks"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</template>
						</vxe-column>
						<vxe-column
							field="remark"
							title="下单备注"
							align="left"
							width="280"
							show-overflow
						>
							<template #default="{ row, rowIndex }">
								<div class="el-input click-cell-ipt">
									<input
										:id="'remark' + rowIndex"
										v-model.lazy="row.remark"
										maxlength="2000"
										placeholder=" "
										class="el-input__inner"
									/>
								</div>
							</template>
						</vxe-column>
						<vxe-column
							field="number"
							title="应下单数量"
							align="right"
							width="120"
							fixed="right"
							show-overflow
							sort-type="number"
							sortable
						>
							<template #default="{ row, rowIndex }">
								<div class="el-input click-cell-ipt">
									<input
										v-model.lazy="row.number"
										@blur="
											saleNumber(
												rowIndex,
												row.number,
												'number',
												row.precision
											)
										"
										maxlength="19"
										placeholder
										class="el-input__inner"
									/>
								</div>
							</template>
						</vxe-column>
					</vxe-table>
				</div>
				<!-- 底部 -->
				<div class="sale-page-footer">
					<div class="footer-left"></div>
					<div class="footer-right">
						<el-pagination
							:page-sizes="pagingList"
							:page-size="pageSize"
							layout="slot,sizes,total, prev,pager, next,jumper"
							:total="totalItemNumber"
							popper-class="每页显示"
							:pager-count="5"
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
						>
							<span class="total-select-item">
								共选中
								<text
									style="
										text-align: center;
										color: #4178d5;
										padding: 0 1px;
									"
									>{{ selectItem }}</text
								>行
							</span>
						</el-pagination>
					</div>
					<div class="footer-pagination-total-page">
						<span>共{{ totalPageNumber }}页</span>
					</div>
				</div>
				<!-- 批量修改 -->
				<el-dialog 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
									v-model="details.deliveryDay"
									placeholder=" "
								></el-input>
							</span>
						</div>
						<div class="editDialog">
							<span> <i style="color: red">*</i>物料属性 </span>
							<span>
								<el-select
									v-model="details.materialPropertyKey"
									placeholder="请选择"
								>
									<el-option
										v-for="(
											value, key, index
										) in statusForm.materialPropertys"
										:label="value"
										:value="key"
										:key="key + index"
									></el-option>
								</el-select>
							</span>
						</div>
						<div class="editDialog">
							<span>
								<i style="color: red">*</i>供应组织/供应商
							</span>
							<span>
								<el-select
									v-model="details.supplyOrgOrSupplier"
									filterable
									remote
									reserve-keyword
									placeholder="请选择"
									:remote-method="getSuppOrgSerachEdit"
								>
									<el-option
										v-for="item in statusForm.supplierOrgsEdit"
										@click="
											pushDownCom(
												details.supplyOrgOrSupplier,
												'supplyOrgOrSupplier'
											)
										"
										:label="item.name"
										:value="item.id"
										:key="item.id"
									></el-option>
								</el-select>
							</span>
						</div>
						<div class="editDialog">
							<span> <i style="color: red">*</i>下单仓库 </span>
							<span>
								<el-select
									v-model="details.stockId"
									placeholder="请选择"
								>
									<el-option
										v-for="item in statusForm.stocks"
										:label="item.name"
										:value="item.id"
										:key="item.id"
									></el-option>
								</el-select>
							</span>
						</div>
					</div>
					<template #footer>
						<span class="dialog-footer">
							<el-button
								type="primary"
								size="small"
								@click="dialogDownVisible = false"
								>取消</el-button
							>
							<el-button
								type="primary"
								size="small"
								@click="sureDownOrder"
								>确定</el-button
							>
						</span>
					</template>
				</el-dialog>
				<!-- 下单结果 -->
				<el-dialog
					title="下单结果"
					v-model="dialogVisibleDwon"
					width="47.1%"
				>
					<div class="sale-page-table-body">
						<el-table
							class="table-box"
							:data="tableInfo"
							height="300"
							border
							:header-cell-class-name="headerRigthMethod"
							id="tableInfo-table"
						>
							<el-table-column
								prop="materialNumber"
								label="物料编码"
								width="150"
							></el-table-column>
							<el-table-column
								prop="materialName"
								label="物料名称"
								width="150"
							></el-table-column>
							<el-table-column
								prop="orderType"
								label="单据类型"
								width="150"
							></el-table-column>
							<el-table-column
								prop="orderNo"
								label="单编编号"
								width="150"
							></el-table-column>
							<el-table-column
								prop="isSuccess"
								label="状态"
								width="100"
							>
								<template #default="scope">
									<span>{{
										scope.row.isSuccess === true
											? '成功'
											: '失败'
									}}</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="msg"
								label="失败原因"
								width="130"
							></el-table-column>
						</el-table>
					</div>
					<template #footer>
						<span class="dialog-footer">
							<el-button
								type="primary"
								size="small"
								@click="
									handelhtmlToExcel(
										'tableInfo-table',
										'下单结果'
									);
									dialogVisible = false;
								"
								>导 出</el-button
							>
						</span>
					</template>
				</el-dialog>
			</div>
		</div>
	</div>
</template>
<script>
import { mapState } from 'vuex';
import { exporthandel, htmlToExcel } from '@/utils/pubulic.js';
import { getArrayName, getObjectName } from '@/utils/takeMethods.js';
export default {
	name: 'SupplySemiProdut',
	inject: ['reload'],
	data() {
		return {
			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,
			tableLoading: false,
			dialogDownVisible: false, // 批量修改
			titleSku: 'ORICO-PHM-25-BK-EP',
			pageSize: 50, // 页数
			containerHeight: '', // body容器高度
			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: {
		Init() {
			this.windowHeight = document.documentElement.clientHeight; // 计算表格高度和底部位置
			this.heightNum = this.windowHeight - 258; // 计算表格高度
			this.containerHeight = this.windowHeight - 102; // 计算容器的高度
			// this.getList(this.search, 'yes') // 获取列表
			this.getDownOrg(); // 获取下单组织
			this.$http.get('Materials/GetStatus').then((r) => {
				if (r.status == 200) {
					this.statusForm.materialPropertys =
						r.data.materialPropertyType;
				}
			});
		},
		// 清0
		valueRemoveZero(index, key) {
			if (
				this.tableData[index][key]
					.toString()
					.charAt(this.tableData[index][key].toString().length - 1) !=
				'.'
			) {
				return this.tableData[index][key] * 1;
			} else {
				return this.tableData[index][key];
			}
		},
		getName(arr, val) {
			return getObjectName(arr, val);
		},
		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);
			dialogVisibleDwon = false;
		},
		taxPriceNumberRex(rowIndex, val, key) {
			let numD = '';
			let count = '\\d';
			for (let index = 0; index < 4; index++) {
				numD = numD + count;
			}
			let reg = '/^(-)*(\\d+)\\.(' + numD + ').*$/';
			if (val) {
				this.tableData[rowIndex][key] = val
					.toString()
					.replace(/[^\d.]/g, '')
					.replace(/\.{2,}/g, '.')
					.replace(/^\./g, '')
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
					.replace(eval(reg), '$1$2.$3');
			}
		},
		saleNumber(index, val, key, precision) {
			if (val) {
				if (precision == 0 || precision == null) {
					this.tableData[index][key] = val
						.toString()
						.replace(/\D/g, '');
				} 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, '');
			}
		},
		upDataRow(ind, val, key, row) {
			if (key === 'purchasePrice') {
				let _value = document.getElementById(key + ind).value;
				document.getElementById(key + ind).value = _value;
				this.tableData[ind][key] = _value;
				this.taxPriceNumberRex(ind, this.tableData[ind][key], key);
				this.requestDataRow(ind, this.tableData[ind][key], key);
				this.tableData[ind][key] = this.valueRemoveZero(ind, key);
				document.getElementById(key + ind).value =
					this.tableData[ind][key];
			} else if (key === 'deliveryDay') {
				let _value = document.getElementById(key + ind).value;
				document.getElementById(key + ind).value = _value;
				this.tableData[ind][key] = _value;
				this.saleNum(ind, this.tableData[ind][key], key);
				if (
					this.tableData[ind][key]
						.toString()
						.charAt(this.tableData[ind][key].length - 1) != '.'
				) {
					this.requestDataRow(ind, this.tableData[ind][key], key);
				}
				this.tableData[ind][key] = this.valueRemoveZero(ind, key);
				document.getElementById(key + ind).value =
					this.tableData[ind][key];
			} else {
				this.requestDataRow(ind, val, key);
			}
		},
		requestDataRow(ind, val, key) {
			let tempMaterialPropertyKey = [];
			let tempMaterialId = [];
			let tempSupplyOrgId = [];
			let tempSupplierId = [];
			let tempDeliveryDay = [];
			let tempPurchasePrice = [];
			let requestData = {
				details: [
					{
						materialPropertyType: '',
						ProduceMaterial: '',
						supplyOrgId: '',
						supplierId: '',
						deliveryDay: '',
						purchasePrice: '',
						orgId: '',
					},
				],
			};
			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[ind];
			requestData.details[0].ProduceMaterial = tempMaterialId[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 &&
				this.$store.state.org &&
				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
					.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
					.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
					.get('HalfProduct/GetSupplierAndOrganizationsList', query)
					.then((r) => {
						if (r.status === 200) {
							this.supplierList[index] = r.data;
						}
					});
			}
		},
		detailsCom(val, keyZ, keyG, rowIndex, name) {
			if (val != '' || val != null || val != 'undefined') {
				if (val.substr(0, 1) == 'g') {
					// supplierId  供应商
					this.tableData[rowIndex].supplierId = Number(val.substr(1));
					this.tableData[rowIndex].supplyOrgId = null;
				} else {
					// supplyOrgId 供应组织
					this.tableData[rowIndex].supplierId = null;
					this.tableData[rowIndex].supplyOrgId = Number(
						val.substr(1)
					);
				}
				this.tableData[rowIndex].supplyOrgOrSupplier = name;
			} else {
				this.tableData[rowIndex].supplierId = null;
				this.tableData[rowIndex].supplyOrgId = null;
				this.tableData[rowIndex].supplyOrgOrSupplier = null;
			}
			let tempMaterialPropertyKey = [];
			let tempMaterialId = [];
			let tempSupplyOrgId = [];
			let tempSupplierId = [];
			let tempDeliveryDay = [];
			let tempPurchasePrice = [];
			let requestData = {
				details: [
					{
						materialPropertyType: '',
						ProduceMaterial: '',
						supplyOrgId: '',
						supplierId: '',
						deliveryDay: '',
						purchasePrice: '',
						orgId: '',
					},
				],
			};
			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[rowIndex];
			requestData.details[0].ProduceMaterial = tempMaterialId[rowIndex];
			requestData.details[0].supplyOrgId = tempSupplyOrgId[rowIndex];
			requestData.details[0].supplierId = tempSupplierId[rowIndex];
			requestData.details[0].deliveryDay = tempDeliveryDay[rowIndex];
			requestData.details[0].purchasePrice = tempPurchasePrice[rowIndex];
			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: '',
							orgId: '',
							materialPropertyType: '',
							supplyOrgId: '',
							supplierId: '',
							deliveryDay: '',
							purchasePrice: '',
						},
					],
				};
				for (
					let index = 0;
					index < this.multipleSelection.length - 1;
					index++
				) {
					pushData.details.push({
						ProduceMaterial: '',
						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.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 && 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') {
				// 批量修改
				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';
		},
		// 全选
		handelCheckBox(event) {
			let val = event.records;
			this.selectItem = val.length;
			this.multipleSelection = val;
			this.recordCurrIndex = this.multipleSelection.map((it) => it.index);
		},
		// 单选
		handleSelectionChange(event) {
			let val = event.records;
			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.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') {
											this.tableData[index].supplierId =
												Number(val.substr(1));
											this.tableData[index].supplyOrgId =
												null;
										} else {
											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;
										}
									});
								}
							});
						}
						this.totalItemNumber = req.totalCount;
						this.totalPageNumber = Math.ceil(
							this.totalItemNumber / this.pageSize
						);
					}
				});
		},
		searchList() {
			// 搜索
			this.getList(this.search);
		},
		cellColor({ row, column, columnIndex }) {
			column.index = columnIndex;
			let rowstyle = {};
			if (columnIndex == 13) {
				if (row.realStockStatus >= 120) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#A0A0A0';
					return rowstyle;
				}
				if (row.realStockStatus < 120 && row.realStockStatus >= 100) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#77CB44';
					return rowstyle;
				}
				if (row.realStockStatus < 100 && row.realStockStatus > 0) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#F33B3B';
					return rowstyle;
				}
				if (row.realStockStatus == 0) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#000';
					return rowstyle;
				}
			}
			if (columnIndex == 14) {
				if (row.allStockStatus >= 120) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#A0A0A0';
					return rowstyle;
				}
				if (row.allStockStatus < 120 && row.allStockStatus >= 100) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#77CB44';
					return rowstyle;
				}
				if (row.allStockStatus < 100 && row.allStockStatus > 0) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#F33B3B';
					return rowstyle;
				}
				if (row.allStockStatus == 0) {
					rowstyle.color = '#fff';
					rowstyle.backgroundColor = '#000';
					return rowstyle;
				}
			}
		},
		pushDownCom(val, key, type) {
			if (key === 'supplyOrgOrSupplier') {
				if (val != '') {
					if (val.substr(0, 1) == 'g') {
						this.details.supplierId = Number(val.substr(1));
						this.details.supplyOrgId = null;
					} else {
						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') {
						this.search.supplierId = Number(val.substr(1));
						this.search.supplyOrgId = null;
						delete this.search.supplyOrgId;
					} else {
						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;
			}
		},
		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 && 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 = [];
			}
		},
		getDownOrg() {
			if (this.$store.state && this.$store.state.org) {
				this.$http
					.get(
						'SysConfig/GetWarehouseByOrg/' +
							this.$store.state.org.orgId
					)
					.then((r) => {
						if (r.status == 200) {
							this.statusForm.stocks = r.data;
						}
					});
			}
		},
	},
	computed: {
		...mapState({
			orgIdArr: (state) => state.user.orgIdArr,
		}),
		orgIdChange() {
			// 监听ID
			return this.$store.state.org ? this.$store.state.org.orgId : null;
		},
	},
	activated() {
		this.$refs.fileTable.clearAll();
	},
	created: function () {
		this.Init();
	},
	watch: {
		orgIdChange: function (newVale, oldValue) {
			// 监听组织
			this.search.orgId = 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';
</style>
