<template>
	<view class="">
		<u-sticky offset-top="50">
			<u-subsection fontSize='25' mode='subsection' :list="list" :current="curNow" @change="sectionChange"
				activeColor='#157A2C'></u-subsection>
		</u-sticky>

		<view v-show="curNow===0">
			<u--form style="margin: 0 20px;" labelPosition="left" :model="form" ref="uForm" labelWidth='140rpx'>
				<u-form-item label="收货单编码" prop="receiveNo" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.receiveNo"></u--input>
				</u-form-item>
				<u-form-item label="订单编码" prop="orderNo" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.orderNo"></u--input>
				</u-form-item>
				<u-form-item label="制单人" prop="makerName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.makerName"></u--input>
				</u-form-item>
				<u-form-item label="供应商名称" prop="supplierName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.supplierName"></u--input>
				</u-form-item>
				<u-form-item label="供应商联系人" prop="linkName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.linkName"></u--input>
				</u-form-item>
				<u-form-item label="供应商电话" prop="linkPhone" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.linkPhone"></u--input>
				</u-form-item>
				<u-form-item label="车牌" prop="carNo" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.carNo"></u--input>
				</u-form-item>
				<u-form-item label="收货日期" prop="receiveDate" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.receiveDate"></u--input>
				</u-form-item>
				<u-form-item label="委外发货单编码" prop="outsourceSendCode" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.outsourceSendCode"></u--input>
				</u-form-item>
				<u-form-item label="附件" prop="receiveFiles" borderBottom>
					<fileMain v-model="form.receiveFiles" type="view"></fileMain>
				</u-form-item>
			</u--form>

		</view>
		<view v-show="curNow===1">
			<view v-for="(item,index) in form['productList']" :key="index">
				<u--form style="margin: 0 20px;" labelPosition="left" :model="form" ref="uForm" labelWidth='140rpx'>
					<u-row v-for="(key,index1) in tableField" :key="index1">
						<u-col :span="12">
							<u-form-item :label="key.label" prop="categoryName" borderBottom>
								<text>{{ key.formatter ? key.formatter(item) : (item[key.field] || '-') }}</text>
							</u-form-item>
						</u-col>

					</u-row>
				</u--form>
				<u-gap height="40" bgColor="#f0f0f0"></u-gap>
			</view>
		</view>
		<view v-show="curNow===2">
			<u--form style="margin: 0 20px;" labelPosition="left" :model="formData" ref="outForm" :rules="outRules" labelWidth='140rpx'>
				<u-form-item label="物品类型" prop="extInfo.assetType" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.extInfo.assetTypeName"></u--input>
				</u-form-item>
				<u-form-item label="入库类型" prop="bizType" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.bizTypeStr"></u--input>
				</u-form-item>
				<u-form-item label="单据来源" prop="sourceBizNo" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.sourceBizNo"></u--input>
				</u-form-item>
				<u-form-item label="入库时间" prop="storageTime" borderBottom>
					<uni-datetime-picker type="datetime" v-model="formData.storageTime" />
				</u-form-item>
				<u-form-item label="入库登记人" prop="extInfo.createUserName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.extInfo.createUserName"></u--input>
				</u-form-item>
				<u-form-item label="审核人" prop="approvalUserName" borderBottom>
					<u--input disabled style="width: 100%;" v-model="formData.approvalUserName"></u--input>
				</u-form-item>
				<u-form-item label="备注" prop="remark" borderBottom>
					<u--input style="width: 100%;" v-model="formData.remark"></u--input>
				</u-form-item>
			</u--form>
		</view>
		<view class="tab-content" v-show="curNow===3">
			<!-- 批量操作按钮 -->
			<view class="batch-actions" v-if="productList.length > 0">
				<u-button type="success" plain size="small" text="批量保存" @click="listSaveArrs" :disabled="packingList.length > 0"></u-button>
				<picker v-if="packingList.length === 0" class="info-picker" :value="warehouseIndex" :range="warehouseListOption" range-key="name" @change="(e) => handleWareHouse(e, productList)">
					<u-button type="success" plain size="small" text="批量选择仓库" v-if="packingList.length === 0"></u-button>
				</picker>
			</view>
			
			<view v-if="productList.length === 0" class="empty-tip" style="text-align: center; color: #999; font-size: 28rpx; padding: 100rpx 0;">
				暂无产品信息
			</view>
			<view v-else>
				<view class="product-card" v-for="(row, index) in productList" :key="index">
					<view class="card-header">
						<text class="product-name">{{ row.categoryName || '-' }}</text>
						<text class="product-code">{{ row.categoryCode || '-' }}</text>
						<!-- <text class="card-index">{{ index + 1 }}</text> -->
					</view>
					<view class="card-body">
						<!-- 批次号 - isSave为false时可编辑 -->
						<view class="info-row edit-row">
							<text class="info-label">批次号 <text class="required">*</text></text>
							<u--input v-if="!row.isSave" class="info-input" type="text" v-model="row.batchNo" placeholder="请输入批次号" />
							<text v-else class="info-value">{{ row.batchNo || '-' }}</text>
						</view>
						<!-- 数量 - isSave为false时可编辑 -->
						<view class="info-row edit-row">
							<text class="info-label">数量 <text class="required">*</text></text>
							<u--input v-if="!row.isSave" class="info-input" type="number" v-model="row.packingQuantity" placeholder="请输入数量" @input="computeNum(row, index, true)" />
							<text v-else class="info-value">{{ row.packingQuantity || '-' }}</text>
						</view>
						<!-- 单位选择 -->
						<view class="info-row edit-row">
							<text class="info-label">单位 <text class="required">*</text></text>
							<picker v-if="!row.isSave" class="info-picker" :value="row.packingUnitIndex" :range="row.packingSpecificationOption" range-key="conversionUnit" @change="(e) => onPackingUnitChange(e, row, index)">
								<view class="picker-value">{{ row.packingUnit || '请选择单位' }}</view>
							</picker>
							<text v-else class="info-value">{{ row.packingUnit || '-' }}</text>
						</view>
						<!-- 包装完好与否 -->
						<view class="info-row edit-row" v-if="isShowPackage">
							<text class="info-label">包装完好 <text class="required">*</text></text>
							<picker v-if="!row.isSave" class="info-picker" :value="row.ifPackageOkIndex" :range="packageOkOptions" range-key="label" @change="(e) => onPackageOkChange(e, row)">
								<view class="picker-value">{{ row.ifPackageOkLabel || '请选择' }}</view>
							</picker>
							<text v-else class="info-value">{{ row.ifPackageOk == 1 ? '是' : row.ifPackageOk == 0 ? '否' : '-' }}</text>
						</view>
						<!-- 拆包装责任人 -->
						<view class="info-row edit-row" v-if="isShowPackage">
							<text class="info-label">拆包责任人 <text class="required">*</text></text>
							<input v-if="!row.isSave" class="info-input" type="text" v-model="row.unpackUserName" placeholder="请选择" readonly @click="handHead(row, index)" />
							<text v-else class="info-value">{{ row.unpackUserName || '-' }}</text>
						</view>
						<!-- 只读字段 -->
						<view class="info-row">
							<text class="info-label">计量数量</text>
							<text class="info-value">{{ row.measureQuantity || '0' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">计量单位</text>
							<text class="info-value">{{ row.measureUnit || '-' }}</text>
						</view>
						<!-- 单重 -->
						<view class="info-row edit-row">
							<text class="info-label">单重</text>
							<u--input v-if="!row.isSave" class="info-input" type="digit" v-model="row.singleWeight" placeholder="请输入单重" :disabled="row.weightUnit == row.packingUnit" @input="inputsingleWeight(row, index)" />
							<text v-else class="info-value">{{ row.singleWeight || '0' }} {{ row.weightUnit || '' }}</text>
						</view>
						<!-- 总重 -->
						<view class="info-row edit-row">
							<text class="info-label">总重</text>
							<u--input v-if="!row.isSave" class="info-input" type="digit" v-model="row.weight" placeholder="请输入总重" :disabled="row.weightUnit == row.packingUnit" @input="inputWeight(row, index)" />
							<text v-else class="info-value">{{ row.weight || '0' }} {{ row.weightUnit || '' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">重量单位</text>
							<text class="info-value">{{ row.weightUnit || '-' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">生产要求</text>
							<text class="info-value">{{ row.productionRequirements || '-' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">包装规格</text>
							<text class="info-value">{{ row.packingSpecificationLabel ? row.packingSpecificationLabel.join(', ') : '-' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">允许拆包</text>
							<text class="info-value">{{ row.isUnpack == 1 ? '是' : '否' }}</text>
						</view>
						<!-- 仓库 - 必填 -->
						<view class="info-row edit-row">
							<text class="info-label">仓库 <text class="required">*</text></text>
							<picker v-if="!row.isSave" class="info-picker" :value="row.warehouseIndex" :range="warehouseListOption" range-key="name" @change="(e) => onWarehouseChange(e, row)">
								<view class="picker-value">{{ row.warehouseName || '请选择仓库' }}</view>
							</picker>
							<text v-else class="info-value" :class="{ 'red-text': !row.warehouseName }">{{ row.warehouseName || '请选择仓库' }}</text>
						</view>
						<!-- 供应商 -->
						<view class="info-row edit-row">
							<text class="info-label">供应商</text>
							<picker v-if="!row.isSave" class="info-picker" :value="row.supplierIndex" :range="row.supplierListOptions" range-key="name" @change="(e) => onSupplierChange(e, row)">
								<view class="picker-value">{{ row.supplierName || '请选择供应商' }}</view>
							</picker>
							<text v-else class="info-value">{{ row.supplierName || '-' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">供应商代号</text>
							<text class="info-value">{{ row.supplierCode || '-' }}</text>
						</view>
						<!-- 采购原因 -->
						<view class="info-row edit-row">
							<text class="info-label">采购原因</text>
							<u--input v-if="!row.isSave" class="info-input" type="text" v-model="row.purpose" placeholder="请输入采购原因" />
							<text v-else class="info-value">{{ row.purpose || '-' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">是否质检</text>
							<text class="info-value">{{ row.qualityControl == 1 ? '是' : '否' }}</text>
						</view>
						<!-- 生产日期 -->
						<view class="info-row edit-row">
							<text class="info-label">生产日期</text>
							<!-- <picker v-if="!row.isSave" class="info-picker" mode="date" :value="row.detailProductionDate" @change="(e) => onDateChange(e, row, 'detailProductionDate')">
								<view class="picker-value" :class="{ 'placeholder': !row.detailProductionDate }">{{ row.detailProductionDate || '请选择日期' }}</view>
							</picker> -->
							<uni-datetime-picker v-if="!row.isSave" type="datetime" v-model="row.detailProductionDate" />
							<text v-else class="info-value">{{ row.detailProductionDate || '-' }}</text>
						</view>
						<!-- 采购日期 -->
						<view class="info-row edit-row">
							<text class="info-label">采购日期</text>
							<!-- <picker v-if="!row.isSave" class="info-picker" mode="date" :value="row.detailPurchaseDate" @change="(e) => onDateChange(e, row, 'detailPurchaseDate')">
								<view class="picker-value" :class="{ 'placeholder': !row.detailPurchaseDate }">{{ row.detailPurchaseDate || '请选择日期' }}</view>
							</picker> -->
							<uni-datetime-picker v-if="!row.isSave" type="datetime" v-model="row.detailPurchaseDate" />
							<text v-else class="info-value">{{ row.detailPurchaseDate || '-' }}</text>
						</view>
						<!-- 失效日期 -->
						<view class="info-row edit-row">
							<text class="info-label">失效日期</text>
							<!-- <picker v-if="!row.isSave" class="info-picker" mode="date" :value="row.detailExpireDate" @change="(e) => onDateChange(e, row, 'detailExpireDate')">
								<view class="picker-value" :class="{ 'placeholder': !row.detailExpireDate }">{{ row.detailExpireDate || '请选择日期' }}</view>
							</picker> -->
							<uni-datetime-picker v-if="!row.isSave" type="datetime" v-model="row.detailExpireDate" />
							<text v-else class="info-value">{{ row.detailExpireDate || '-' }}</text>
						</view>
						<!-- 机型 - 多选 -->
						<view class="info-row edit-row">
							<text class="info-label">机型</text>
							<view v-if="!row.isSave" class="color-picker-trigger" @click="openModelPicker(row, index)">
								<text class="picker-value" :class="{ 'placeholder': !row.modelKey }">{{ row.modelKey || '请选择机型' }}</text>
							</view>
							<text v-else class="info-value">{{ row.modelKeyNames || '-' }}</text>
						</view>
						<!-- 颜色 - 多选 -->
						<view class="info-row edit-row">
							<text class="info-label">颜色</text>
							<view v-if="!row.isSave" class="color-picker-trigger" @click="openColorPicker(row, index)">
								<text class="picker-value" :class="{ 'placeholder': !row.colorKey }">{{ row.colorKey || '请选择颜色' }}</text>
							</view>
							<text v-else class="info-value">{{ row.colorKey || '-' }}</text>
						</view>
					</view>
					<view class="card-footer">
						<view class="action-buttons">
							<u-button v-if="!row.isSave" type="primary" size="small" text="保存" @click="listSave(row, index)"></u-button>
							<u-button v-else type="primary" size="small" text="编辑" @click="editProductList(row, index)"></u-button>
							<u-button type="error" size="small" text="删除" @click="listDel(row, index)"></u-button>
						</view>
					</view>
				</view>
			</view>
			
			<view class="add" @click="addProduct">
				<u-icon name="plus" color="#fff"></u-icon>
			</view>
		</view>
		<view class="tab-content" v-show="curNow===4">
			<!-- 包装明细 -->
			<view v-if="showPackingList.length > 0" class="packing-section">
				<view class="section-title">
					<text>包装明细</text>
				</view>
				<view class="packing-card" v-for="(item, index) in showPackingList" :key="'pkg-' + index">
					<view class="info-row">
						<text class="info-label">编码</text>
						<text class="info-value">{{ item.categoryCode || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">名称</text>
						<text class="info-value">{{ item.categoryName || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">批次号</text>
						<text class="info-value">{{ item.batchNo || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">包装编码</text>
						<text class="info-value">{{ item.packageNo || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">包装数量</text>
						<text class="info-value">{{ item.packingQuantity || '0' }} {{ item.packingUnit || '' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">计量数量</text>
						<text class="info-value">{{ item.measureQuantity || '0' }} {{ item.measureUnit || '' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">仓库</text>
						<text class="info-value">{{ item.warehouseName || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">物料代号</text>
						<text class="info-value">{{ item.materielDesignation || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">客户代号</text>
						<text class="info-value">{{ item.clientCode || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">重量</text>
						<text class="info-value">{{ item.weight || '0' }} {{ item.weightUnit || '' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">生产日期</text>
						<text class="info-value">{{ item.productionDate || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">采购日期</text>
						<text class="info-value">{{ item.purchaseDate || '-' }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 选择颜色 -->
		<ba-tree-picker ref="colorTreePicker" :multiple="true" @select-change="onColorConfirm" title="选择颜色"
			:localdata="colorTreeData" valueKey="id" textKey="name" childrenKey="child" />
		<!-- 选择机型 -->
		<ba-tree-picker ref="modelTreePicker" :multiple="true" @select-change="onModelConfirm" title="选择机型"
			:localdata="modelTreeData" valueKey="id" textKey="name" childrenKey="child" />
	</view>
</template>

<script>
	import {
		purchaseOrderReceiveGetByIdAPI
	} from '@/api/wt/index.js'
	import { sceneState, qualityResultsOptions, qualityStatus, qualityResults } from '@/enum/dict.js'
	import fileMain from "@/pages/doc/index.vue"
	import { parameterGetByCode } from '@/api/mainData/index.js'
	import { getListByNameOrModeType, getCode, contactQueryByCategoryIdsAPI, getCategoryPackageDisposition, getProduceTreeByPid, warehouseDefinitionList, getAssetNum, getWarehouseList, isVerifyRepeatIsStock } from '@/api/warehouseManagement/index.js'
	import { mapGetters, mapActions } from 'vuex'
	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	import { unary } from 'lodash'
	export default {
		components: {
			fileMain,
			baTreePicker
		},
		props: {
			businessId: {
				default: ''
			},
			taskDefinitionKey: {
				default: ''
			},
		},
		computed: {
			...mapGetters(['dict', 'getDict', 'getDictValue']),
			// 机型选项
			modelOptions() {
				return this.dict?.product_model_key || []
			},
			// 颜色选项（数组）
			colorOptions() {
				return this.dict?.product_color_key || []
			},
			// 颜色选项（树形结构，用于 ba-tree-picker）
			colorTreeData() {
				console.log('colorOptions~~~', this.colorOptions)
				return this.colorOptions.map(item => ({
					id: item.dictCode,
					name: item.dictValue
				}))
			},
			// 机型选项（数组）
			modelOptions() {
				return this.dict?.product_model_key || []
			},
			// 机型选项（树形结构，用于 ba-tree-picker）
			modelTreeData() {
				return this.modelOptions.map(item => ({
					id: item.dictCode,
					name: item.dictValue
				}))
			},
			list() {
				return this.showPackingList.length > 0 ? ['收货信息', '物品清单', '入库信息', '产品信息', '包装明细'] : ['收货信息', '物品清单', '入库信息', '产品信息']
			},
			tableField() {
				const priceField = [
					{ label: '单价', field: 'singlePrice' },
					{ label: '不含税单价', field: 'notaxSinglePrice' },
					{ label: '折后单价', field: 'discountSinglePrice' },
					{ label: '合计', field: 'totalPrice' },
					{ label: '折后合计', field: 'discountTotalPrice' },
				]
				const baseField = [
					{ label: '名称', field: 'productName' },
					{ label: '编码', field: 'productCode' },
					{ label: '类型', field: 'productCategoryName' },
					{ label: '批次号', field: 'batchNo' },
					{ label: '规格', field: 'specification' },
					{ label: '型号', field: 'modelType' },
					{ label: '包装规格', field: 'packingSpecification' },
					{ label: '供应商代号', field: 'supplierMark' },
					{ label: '仓库名称', field: 'warehouseName' },
					{ label: '收货数量', field: 'purchaseCount', formatter: (row) => (row.purchaseCount || '-') + row.purchaseUnit },
					{ label: '单重', field: 'singleWeight', formatter: (row) => row.singleWeight ? row.singleWeight + ' ' + row.weightUnit : '-' },
					{ label: '发货总重', field: 'sendTotalWeight', formatter: (row) => row.sendTotalWeight ? row.sendTotalWeight + ' ' + row.weightUnit : '-' },
					{ label: '收货总重', field: 'receiveTotalWeight', formatter: (row) => row.receiveTotalWeight ? row.receiveTotalWeight + ' ' + row.weightUnit : '-' },
					{ label: '增重重量', field: 'increaseTotalWeight', formatter: (row) => row.increaseTotalWeight ? row.increaseTotalWeight + ' ' + row.weightUnit : '-' },
					{ label: '计量数量', field: 'totalCount', formatter: (row) => (row.totalCount || '-') + row.measuringUnit },
					{ label: '是否来料检验', field: 'isComeCheck', formatter: (row) => row.isComeCheck == 1 ? '是' : '否' },
				]
				return this.taskDefinitionKey == 'storeManagerApprove' && this.isHidePrice == 0 ? baseField : [...baseField, ...priceField]
			},
			tableField2() {
				return [
					{ label: '名称', field: 'categoryName' },
					{ label: '编码', field: 'categoryCode' },
					{ label: '型号', field: 'categoryModel' },
					{ label: '规格', field: 'specification' },
					{ label: '牌号', field: 'brandNum' },
					{ label: '批次号', field: 'batchNo' },
					{ label: '数量', field: 'packingQuantity' },
					{ label: '单位', field: 'packingUnit' },
					{ label: '单重', field: 'singleWeight' },
					{ label: '总重', field: 'weight' },
					{ label: '重量单位', field: 'weightUnit' },
					{ label: '供应商', field: 'supplierId' },
					{ label: '仓库', field: 'warehouseName' },
					{ label: '颜色', field: 'colorKey' },
					{ label: '机型', field: 'modelKey' },
					{ label: '采购原因', field: 'purpose' },
					{ label: '生产日期', field: 'detailProductionDate' },
					{ label: '采购日期', field: 'detailPurchaseDate' },
					{ label: '失效日期', field: 'detailExpireDate' },
					{ label: '是否质检', field: 'qualityControl' },
					{ label: '包装规格', field: 'packingSpecificationLabel' },
					{ label: '允许拆包', field: 'isUnpack' },
					{ label: '计量数量', field: 'measureQuantity' },
					{ label: '计量单位', field: 'measureUnit' },
					{ label: '生产要求', field: 'weightUnit' },
					{ label: '供应商名称', field: 'supplierName' },
					{ label: '供应商代号', field: 'supplierCode' },
					{ label: '产地', field: 'supplierCode' },
				]
			}
		},
		data() {
			return {
				form: {},
				userInfo: {},
				formData: {
					bizType: '',
					bizTypeStr: '',
					storageTime: '',
					qualityControl: '',
					extInfo: {
						assetType: [],
						assetTypeName: ''
					}
				},
				isHidePrice: 0,
				warehouseIndex: 0,
				curNow: 0,
				packingSpecificationOption: [],
				productList: [],
				packingList: [],
				showPackingList: [],
				goodsLists: [],
				outRules: {},
				sceneState,
				qualityResultsOptions,
				qualityStatus,
				qualityResults,
				isWrapTable: true,
				pageSize: 20,
				pickingPageNum: 1,
				visibleDialog: false,
				title: '选择产品',
				loadTree: true,
				isShowPackage: false,
				packageOkOptions: [
				{ label: '是', value: 1 },
				{ label: '否', value: 0 }
			],
			// colorTreeData: [], // 颜色树形数据
			currentColorRow: null, // 当前选择颜色的行
			currentColorIndex: -1, // 当前选择颜色的行索引
			// 机型相关
			currentModelRow: null, // 当前选择机型的行
			currentModelIndex: -1, // 当前选择机型的行索引
		}
		},
		beforeDestroy() {
			uni.$off('setSelectList')
		},
		created() {
			uni.$on('setSelectList', async data => {
				// uni.removeStorageSync('productList')
				console.log('setSelectList~~~', data)
				if (data?.length) {
					// 获取批次号
					const batchNo = await getCode('lot_number_code');
					// 获取供应商
					const supplierList = await contactQueryByCategoryIdsAPI({
						categoryIds: data.map((item) => item.id)
					});
					// 获取包装规格
					let packingSpecification = await getCategoryPackageDisposition({
						categoryIds: data.map((item) => item.id)
					});
					this.packingSpecificationOption = data.map((item) => {
						return packingSpecification
							.filter((ite) => item.id == ite.categoryId)
							.sort((a, b) => a.sort - b.sort);
					});

					const newSpecificationOption = this.packingSpecificationOption;
					let productList = data.map((item, index) => {
						// 显示规格
						let packingSpecificationLabel = this.packingSpecificationOption[index].map((item) => {
							if (item.sort > 0) {
								return `${item.packageCell}${item.packageUnit}/${item.conversionUnit}`;
							}
						}).filter((item) => !!item);

						return {
							index:
							this.productList.length - 1 > -1
								? this.productList[this.productList.length - 1].index + index + 1 : this.productList.length + index,
							categoryId: item.id, // 物品id
							categoryName: item.name, // 物品名称
							categoryCode: item.code, // 物品编码
							categoryModel: item.modelType, // 物品型号
							specification: item.specification, // 规格
							modelKey: item.modelKey ? item.modelKey : '', // 机型
							colorKey: item.colorKey ? item.colorKey : '', // 颜色
							brandNum: item.brandNum, // 牌号
							batchNo: batchNo, // 批次号
							supplierListOptions: supplierList[item.id], // 供应商列表
							supplierId: '', // 供应商id
							supplierCode: item.supplierCode, // 供应商代号
							supplierName: item.supplierName, // 供应商名称
							measureType: item.measureType, // 计量类型
							approvalNumber: item.approvalNumber, // 批准文号
							packingSpecification: item.packingSpecification, // 包装规格
							packingSpecificationOption: newSpecificationOption[index], // 包装规格选项
							packingSpecificationLabel: packingSpecificationLabel, // 包装规格显示
							minPackingQuantity: '', // 最小包装单元数量
							packingQuantity: '', // 包装数量
							packingUnit: item.measuringUnit, // 单位
							packingUnitId: newSpecificationOption[index].find(
								(v) => v.conversionUnit == item.measuringUnit
							)?.id, // 单位
							measureQuantity: 0, // 计量数量
							measureUnit: item.measuringUnit, // 计量单位
							netWeight: item.netWeight > -1 ? item.netWeight : 0, // 净重
							weight: 0, // 重量
							singleWeight: item.measuringUnit != 'KG' ? item.netWeight : 0, // 单重
							pricingWay: item.pricingWay,
							weightUnit: item.weightUnit, // 重量单位
							totalMoney: item.totalPrice, // 总价
							unitPrice: item.unitPrice, // 单价
							purpose: '', // 用途
							isUnpack: item.isUnpack // 是否允许拆包
						};
					});
					this.productList = this.productList.concat(productList);
				}
			})
		},
		async mounted() {
			this.userInfo = uni.getStorageSync('userInfo')
			await this.requestDict('产地')
			await this.requestDict('不拆物料层规格')
			await this.requestDict('物品颜色')
			await this.requestDict('物品机型')
			await this.getListItems()
			await this.getwarehouseList()
			await parameterGetByCode({ code: 'eom_purchase_invoice_approval_price' }).then((res) => {
				this.isHidePrice = res.value;
			});
			await this.getDetailData(this.businessId);
			await this.getNowFormatDate();
		},
		watch: {
			packingList: {
				handler(newVal) {
					this.showPackingList = newVal.slice(0, this.pageSize * (this.pickingPageNum > 0 ? this.pickingPageNum : 1));
					this.pickingPageNum = Math.ceil(this.showPackingList.length / this.pageSize);
				},
				deep: true
			}
		},
		methods: {
			...mapActions('dict', ['requestDict']),
			// 获取当前时间 YYYY-MM-DD HH:mm:ss
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			//获取仓库
			async getwarehouseList() {
				let res = await getWarehouseList()
				this.warehouseListOption = res.data.map(item => {
					return {
						id: item.id,
						name: item.name
					}
				})
			},
			handleWareHouse(e, row) {
				const val = e.detail.value;
				const warehouseItem = this.warehouseListOption[val];
				if (warehouseItem) {
					this.productList.forEach((item, index) => {
						this.$set(this.productList[index], 'warehouseId', warehouseItem.id);
						this.$set(this.productList[index], 'warehouseName', warehouseItem.name);
						this.$set(this.productList[index], 'warehouseIds', [warehouseItem.id]);
						this.$set(this.productList[index], 'warehouseNames', [warehouseItem.name]);
					});
				}
			},
			// 获取物品列表
			async getListItems() {
				const res = await getProduceTreeByPid({});
				this.goodsLists = res;
			},
			sectionChange(index) {
				this.curNow = index;
			},
			async getDetailData(id) {
				const data = await purchaseOrderReceiveGetByIdAPI(id);
				this.form = data;
				this.initFormData()
			},
			initFormData() {
				const defaultTime = '00:00:00';
				this.formData.type = 1;
				this.formData.bizType = this.form.outsourceSendCode ? 10 : 2;
				const currentTime = this.getCurrentTime();
				if (this.formData.bizType == 2 || this.formData.bizType == 6) {
					this.formData.storageTime = this.form.receiveDate
						? `${this.form.receiveDate} ${defaultTime}`
						: currentTime;
				} else {
					this.formData.storageTime = currentTime;
				}

				this.formData.bizTypeStr = sceneState.find(item => item.code == this.formData.bizType)?.label || ''
				if (this.form.receiveNo != null && this.form.receiveNo != '') {
					this.$set(this.formData, 'sourceBizNo', this.form.receiveNo);
				} else {
					uni.showToast({ title: '未获取到单据来源！', icon: 'none' });
				}

				this.formData.extInfo.createUserId = this.form.createUserId || this.userInfo.userId || '';
				this.formData.extInfo.createUserName = this.form.createUserName || this.userInfo.name || '';
				this.formData.extInfo.deliveryPhone = this.userInfo.phone || '';
				this.formData.createUserId = this.form.createUserId || this.userInfo.userId || '';
				this.formData.createUserName = this.form.createUserName || this.userInfo.name || '';
				this.formData.extInfo.deptName = this.form.deptName || this.userInfo.deptName || '';
				this.formData.approvalUserName = this.form.approvalUserName || this.userInfo.name;
				this.formData.approvalUserId = this.form.approvalUserId || this.userInfo.userId;

				if (this.form.productList?.length > 0) {
					let detailPurchaseDate;
					if (this.formData.bizType == '2' || this.formData.bizType == '10') {
						detailPurchaseDate = this.form.purchaseDate || `${this.form.receiveDate} ${defaultTime}`;
					}

					let codeList = this.form.productList.map((item) => item.productCode || item.categoryCode);
					getListByNameOrModeType({ codeList }).then(async (res) => {
						if (res.length <= 0) {
							uni.showToast({ title: '未获取到物品信息！', icon: 'none' });
							return;
						}

						this.formData.extInfo.assetType = Array.from(new Set(res.map((item) => item.categoryLevelPathIdParent)));
						this.formData.extInfo.assetTypeName = this.formData.extInfo.assetType.map(id => {
							const item = this.goodsLists.find(g => g.id == id);
							return item?.name || id;
						}).join(',');

						const batchNo1 = await getCode('lot_number_code');
						const supplierList = await contactQueryByCategoryIdsAPI({ categoryIds: res.map((item) => item.id) });
						let packingSpecification = await getCategoryPackageDisposition({ categoryIds: res.map((item) => item.id) });

						this.packingSpecificationOption = res.map((item) => {
							return packingSpecification.filter((ite) => item.id == ite.categoryId).sort((a, b) => a.sort - b.sort);
						});

						this.productList = res.map((item, index) => {
							let filtersItem = this.form.productList.find((detailItem) => item.code == detailItem.productCode || item.code == detailItem.categoryCode);

							let packingSpecificationLabel = this.packingSpecificationOption[index].map((item) => {
								if (item.sort > 0) {
									return `${item.packageCell}${item.packageUnit}/${item.conversionUnit}`;
								}
							}).filter((item) => !!item);

							const newSpecificationOption = this.packingSpecificationOption;

							let warehouseId = filtersItem.warehouseId;
							let warehouseName = filtersItem.warehouseName;
							let measureQuantity = filtersItem.totalCountNew || filtersItem.totalCount || 0;
							if ((filtersItem.sendTotalWeight || filtersItem.receiveTotalWeight) && item.weightUnit == item.measuringUnit) {
								measureQuantity = filtersItem.sendTotalWeight || filtersItem.receiveTotalWeight;
							}
							let packingQuantity = filtersItem.totalCountNew || filtersItem.purchaseCount || filtersItem.totalCount || 0;
							let packingUnit = filtersItem.purchaseUnit || filtersItem.measuringUnit || '';
							let unitPrice = filtersItem.singlePrice || 0;
							let pricingWay = filtersItem.pricingWay || '';
							let singleWeight = filtersItem.singleWeight || 0;
							let weight = filtersItem.sendTotalWeight || filtersItem.receiveTotalWeight || singleWeight * measureQuantity;
							let warehouseIds = [];
							let warehouseNames = [];
							for (let i = 0; i < filtersItem.totalCount; i++) {
								warehouseIds.push(filtersItem.warehouseId);
								warehouseNames.push(filtersItem.warehouseName);
							}
							let totalMoney = filtersItem.totalPrice || 0;
							let batchNo = filtersItem.batchNo || batchNo1;

							return {
								index: this.productList.length + index,
								categoryId: item.id,
								categoryName: item.name,
								categoryCode: item.code,
								categoryModel: item.modelType,
								specification: item.specification,
								brandNum: item.brandNum,
								batchNo: batchNo,
								supplierListOptions: supplierList[item.id],
								supplierId: this.form.supplierId,
								productionRequirements: filtersItem.productionRequirements,
								supplierCode: this.formData.bizType == 2 || this.formData.bizType == 7 ? filtersItem.supplierMark : item.supplierCode,
								supplierName: this.form.supplierName,
								approvalNumber: item.approvalNumber,
								packingSpecification: item.packingSpecification,
								packingSpecificationOption: newSpecificationOption[index],
								packingSpecificationLabel: packingSpecificationLabel,
								packingQuantity: this.form.productList[index] && this.form.productList[index].isAllPackageData == 1
									? this.form.productList[index].packingCount : packingQuantity,
								packingUnit: this.form.productList[index] && this.form.productList[index].isAllPackageData == 1
									? this.form.productList[index].packingUnit : packingUnit,
								measureQuantity: this.form.productList[index] && this.form.productList[index].isAllPackageData == 1
									? this.form.productList[index].quantity : measureQuantity,
								measureUnit: this.form.productList[index] && this.form.productList[index].isAllPackageData == 1
									? this.form.productList[index].measuringUnit : item.measuringUnit,
								packingUnitId: filtersItem.purchaseUnitId || filtersItem.saleUnitId,
								modelKey: filtersItem.modelKey ? filtersItem.modelKey : '',
								colorKey: filtersItem.colorKey ? filtersItem.colorKey : '',
								measureType: item.measureType,
								netWeight: item.netWeight > -1 ? item.netWeight : 0,
								singleWeight: singleWeight || 0,
								weight: weight || 0,
								weightUnit: item.weightUnit,
								totalMoney: totalMoney,
								unitPrice: item.unitPrice || unitPrice,
								pricingWay: pricingWay,
								purpose: '',
								detailPurchaseDate,
								detailExpireDate: this.form.productList.find((product) => product.productId == item.id)?.guaranteePeriodDeadline,
								detailProductionDate: this.form.productList.find((product) => product.productId == item.id)?.productionDate,
								provenance: filtersItem.provenance,
								isUnpack: item.isUnpack,
								warehouseId,
								warehouseName,
								warehouseIds,
								warehouseNames,
								qualityControl: filtersItem?.isComeCheck
							};
						});
						
						this.$nextTick(() => {
							this.batchSave();
						});
					});
				}
			},
			// 赋值入库时间
			getNowFormatDate() {
				const obj = this.getNowDate();
				const defaultTime = '00:00:00';
				const currentTime = `${obj.hour}:${obj.minute}:${obj.second}`;

				if (this.formData.bizType === 2 || this.formData.bizType === '2' || this.formData.bizType === 6 || this.formData.bizType === '6') {
					this.formData.storageTime = this.form.receiveDate
						? `${this.form.receiveDate} ${defaultTime}`
						: `${obj.year}-${obj.month}-${obj.strDate} ${currentTime}`;
				} else {
					this.formData.storageTime = `${obj.year}-${obj.month}-${obj.strDate} ${currentTime}`;
				}
			},
			// 获取当前时间函数
			getNowDate() {
				let date = new Date(),
					obj = {
						year: date.getFullYear(),
						month: date.getMonth() + 1,
						strDate: date.getDate(),
						hour: date.getHours(),
						minute: date.getMinutes(),
						second: date.getSeconds()
					};
				Object.keys(obj).forEach((key) => {
					if (obj[key] < 10) obj[key] = `0${obj[key]}`;
				});
				return obj;
			},
			changeCount(number) {
				// 移动端兼容的数字转字符串方法，避免浮点数精度显示问题
				const num = Number(number || 0);
				return isNaN(num) ? '0' : String(num);
			},
			selectSupplier(val, row) {
				row.supplierId = val;
				row.supplierName = row.supplierListOptions.filter((item) => item.id == val)[0]?.name;
				row.supplierCode = row.supplierListOptions.filter((item) => item.id == val)[0]?.serialNo;
			},
			inputsingleWeight(row, index) {
				if (row.measureUnit == row.weightUnit) {
					row.weight = row.singleWeight * row.packingQuantity;
					row.measureQuantity = row.weight;
				} else {
					row.weight = row.singleWeight * row.measureQuantity;
				}
			},
			inputWeight(row, index) {
				if (row.measureUnit == row.weightUnit) {
					row.measureQuantity = row.weight;
					row.singleWeight = Math.trunc((row.measureQuantity / row.packingQuantity) * 10000) / 10000;
				} else {
					row.singleWeight = row.measureQuantity ? row.weight / row.measureQuantity : 0;
				}
			},
			// 计算最小单元数量
			async computeNum(row, index, isClear) {
				let data = row.packingSpecificationOption.find((item) => item.id == row.packingUnitId);
				if (data) {
					row.packingUnit = data.conversionUnit;
				}
				
				if (isClear && row.packingQuantity < 0) {
					this.$set(this.productList[index], 'packingQuantity', 1);
				}
				
				if (row.packingQuantity && row.packingUnit) {
					const res = await warehouseDefinitionList({});
					if (res.length == 1) {
						let name = res[0]?.factoryName + '-' + res[0]?.name;
						this.$set(this.productList[index], 'warehouseId', res[0].id);
						this.$set(this.productList[index], 'warehouseName', name);
					} else {
						this.$set(this.productList[index], 'warehouseId', '');
						this.$set(this.productList[index], 'warehouseName', '');
					}
					
					let startIndex = row.packingSpecificationOption.findIndex((ite) => {
						return row.measuringUnit == ite.packingUnit && ite.packingUnit != ite.conversionUnit;
					});
					let endIndex = row.packingSpecificationOption.findIndex((ite) => data.id == ite.id);
					
					let total = Number(row.packingQuantity);
					if (row.packingUnit == row.measureUnit && row.measureUnit == '立方' && row.netWeight) {
						total = Number(row.packingQuantity) * row.netWeight;
					} else {
						for (; 0 < endIndex; endIndex--) {
							total = this.$math.format(row.packingSpecificationOption[endIndex].packageCell * total, 14);
						}
					}
					
					row.measureQuantity = this.changeCount(total);
					
					let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)?.dictValue;
					let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)?.dictValue;
					
					if (packingBoolen && measureBoolen && row.packingUnit != 'L') {
						row.weight = total;
					}
					
					let weight = 0;
					if (row.measureUnit == row.weightUnit) {
						weight = row.measureQuantity;
						if (row.weightUnit == row.packageUnit) {
							row.singleWeight = 0;
						} else {
							row.singleWeight = Math.trunc((row.measureQuantity / row.packingQuantity) * 10000) / 10000;
						}
					} else if (row.singleWeight) {
						weight = row.measureQuantity * Number(row.singleWeight);
					}
					this.$set(this.productList[index], 'weight', weight);
				}
			},
			// 添加产品
			addProduct() {
				if (this.formData.extInfo.assetType.length <= 0) {
					return uni.showToast({ title: '请选择物品类型', icon: 'none' });
				}
				if (!this.formData.bizType) {
					return uni.showToast({ title: '请选择入库类型', icon: 'none' });
				}
				this.visibleDialog = true;
				uni.navigateTo({
					url: '/pages/warehouse/enterHouse/selectEnterType?assetType=' + this.formData.extInfo.assetType
				})
			},
			// 批量保存
			async batchSave() {
				try {
					for (let i = 0; i < this.productList.length; i++) {
						const row = this.productList[i];
						if (!row.isSave) {
							await this.listSave(row, i);
						}
					}
				} catch (error) {
					console.log('保存失败', error);
				}
			},
			listSave(row, index) {
				// 必填项校验
				if (!row.batchNo) {
					uni.showToast({ title: '请填写批次号', icon: 'none' });
					return;
				}
				if (!row.packingQuantity && row.packingQuantity !== 0) {
					uni.showToast({ title: '请填写数量', icon: 'none' });
					return;
				}
				if (!row.packingUnit) {
					uni.showToast({ title: '请选择单位', icon: 'none' });
					return;
				}
				if (!row.warehouseId) {
					uni.showToast({ title: '请选择仓库', icon: 'none' });
					return;
				}
			},
			// 物品批量保存前校验
			validateForm() {
				return new Promise((resolve, reject) => {
					for (let i = 0; i < this.productList.length; i++) {
						const row = this.productList[i];
						// 已保存的不需要校验
						if (row.isSave) continue;

						if (!row.batchNo) {
							uni.showToast({ title: `第${i + 1}行：请填写批次号`, icon: 'none' });
							reject(new Error('批次号必填'));
							return;
						}
						if (!row.packingQuantity && row.packingQuantity !== 0) {
							uni.showToast({ title: `第${i + 1}行：请填写数量`, icon: 'none' });
							reject(new Error('数量必填'));
							return;
						}
						if (!row.packingUnit) {
							uni.showToast({ title: `第${i + 1}行：请选择单位`, icon: 'none' });
							reject(new Error('单位必填'));
							return;
						}
						if (!row.warehouseId) {
							uni.showToast({ title: `第${i + 1}行：请选择仓库`, icon: 'none' });
							reject(new Error('仓库必填'));
							return;
						}
					}
					resolve();
				});
			},
			listSave(row, index) {
				// 必填项校验
				if (!row.batchNo) {
					uni.showToast({ title: '请填写批次号', icon: 'none' });
					return;
				}
				if (!row.packingQuantity && row.packingQuantity !== 0) {
					uni.showToast({ title: '请填写数量', icon: 'none' });
					return;
				}
				if (!row.packingUnit) {
					uni.showToast({ title: '请选择单位', icon: 'none' });
					return;
				}
				if (!row.warehouseId) {
					uni.showToast({ title: '请选择仓库', icon: 'none' });
					return;
				}

				// 判断单位和计量单位是否为不拆物料层规格
				let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)?.dictValue;
				let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)?.dictValue;
				let packingNum = 0;

				if (packingBoolen) {
					if (!row.isUnpack && row.packingUnit == '立方') {
						packingNum = 1;
					} else {
						let filterArr = row.packingSpecificationOption.filter((item) => {
							return item.packageUnit == row.packingUnit && item.packageUnit != item.conversionUnit;
						});
						if (filterArr?.length) {
							packingNum = Math.ceil(row.packingQuantity / filterArr[0].packageCell);
						}
					}
				}
				
				let measureNum = row.packingQuantity;
				let num = 0;
				if (measureBoolen) {
					let splitIndex = row.packingSpecificationOption.findIndex((item) =>
						item.conversionUnit == row.packingUnit && item.packageUnit != item.conversionUnit
					);
					for (; splitIndex > 1; splitIndex--) {
						measureNum = this.$math.format(measureNum * row.packingSpecificationOption[splitIndex].packageCell, 14);
					}
				} else {
					if (row.packingSpecificationOption[1]?.packageCell) {
						num = Math.ceil(row.measureQuantity / row.packingSpecificationOption[1]?.packageCell);
					} else {
						num = row.packingQuantity;
					}
				}

				if (row.packingSpecificationLabel?.length < 1) {
					uni.showToast({ title: '请到主数据维护包装组信息！', icon: 'none' });
					return;
				}
				
				// 不拆包
				if (!row.isUnpack) {
					if (row.packingUnit != row.measureUnit) {
						getAssetNum([{ assetCode: row.categoryCode + row.index, batchNum: row.batchNo, num: row.packingQuantity }]).then(() => {});
					} else {
						getAssetNum([{ assetCode: row.categoryCode + row.index, batchNum: row.batchNo, num: 0 }]).then(() => {});
					}
				} else {
					if (!packingNum) {
						if (row.packingUnitId) {
							let splitIndex = row.packingSpecificationOption.findIndex((item) => item.id == row.packingUnitId);
							if (splitIndex == 0) {
								packingNum = Math.ceil(row.measureQuantity / row.packingSpecificationOption[1]?.packageCell);
							}
							if (splitIndex == 1) {
								packingNum = row.packingQuantity;
							}
							for (; splitIndex > 1; splitIndex--) {
								packingNum = Math.ceil(row.packingQuantity * row.packingSpecificationOption[splitIndex].packageCell);
							}
						} else {
							packingNum = Math.ceil(row.measureQuantity / row.packingSpecificationOption[1]?.packageCell);
						}
					}
					getAssetNum([{ assetCode: row.categoryCode + row.index, batchNum: row.batchNo, num: packingNum }]).then(() => {});
				}
				
				this.$set(this.productList[index], 'isSave', true);
				this.$set(this.productList[index], 'warehouseId', row.warehouseId);
				this.$set(this.productList[index], 'warehouseName', row.warehouseName);
				this.$set(this.productList[index], 'warehouseIds', row.warehouseId);
				this.$set(this.productList[index], 'warehouseNames', row.warehouseName);
			},
			editProductList(row, index) {
				this.$set(this.productList[index], 'isSave', false);
			},
			deleteProductList(row, index) {
				uni.showModal({
					title: '提示',
					content: '确定删除该产品吗？',
					success: (res) => {
						if (res.confirm) {
							this.productList.splice(index, 1);
						}
					}
				});
			},
			saveProductList(row, index) {
				this.listSave(row, index);
			},
			addStock() {
				this.addProduct();
			},
			// 入库
			async getReturnStorage() {
				if (this.productList.length <= 0) {
					uni.showToast({ title: '请先添加产品信息', icon: 'none' });
					return;
				}
				let boolen = this.productList.every((item) => item.isSave);
				if (!boolen) {
					uni.showToast({ title: '请先保存所有产品信息', icon: 'none' });
					return;
				}
				if (this.isShowPackage) {
					const userNameLength = this.productList.filter(
						(item) => !item.unpackUserName
					).length;
					const packgeLength = this.productList.filter(
						(item) => !item.ifPackageOk
					).length;
					if (userNameLength || packgeLength) {
						uni.showToast({ title: '请先填写拆包装责任人和包装完好与否', icon: 'none' });
						return;
					}
				}
				// 处理包装数据
				let _packingList = [];
				_packingList = this.packingList.map((packingItem) => {
					let _taskId = null;
					let _workOrderId = null;
					// if ([1].includes(this.formData.bizType)) {
					// 	_workOrderId = this.detailList[0]?.workOrderId;
					// 	_taskId = this.detailList[0]?.taskId;
					// } else {
						_workOrderId = this.form.productList[0]?.workOrderId;
						_taskId = this.form.productList[0]?.taskId;
					// }
					// if (packingItem.modelKey) {
					// 	packingItem.modelKey = packingItem.modelKey.toString();
					// }
					// if (packingItem.colorKey) {
					// 	packingItem.colorKey = packingItem.colorKey.toString();
					// }
					return {
						...packingItem,
						workOrderId: _workOrderId,
						taskId: _taskId,
						outsourceBatchNo: this.form.productList[0]?.batchNo,
						outsourceCode: this.form.productList[0]?.sourceCode,
						// materialDetailList: this.materialList.filter(
						// (item) => item.parentIndex === packingItem.index
						// )
					};
				});

				// 处理产品数据
				this.productList = this.productList.map((productItem) => {
					// if (productItem.modelKey) {
					// 	productItem.modelKey = productItem.modelKey.toString();
					// }
					// if (productItem.colorKey) {
					// 	productItem.colorKey = productItem.colorKey.toString();
					// }
					return {
						...productItem,
						outInDetailRecordRequestList: _packingList.filter(
							(item) => item.parentIndex === productItem.index
						)
					};
				});
				this.formData.outInDetailList = this.productList;
				let obj = uni.$u.deepClone(this.formData);

				// 处理物品类型assetType
				obj.extInfo.assetType = obj.extInfo.assetType.join(',');
				obj.extInfo.documentSource = this.formData.sourceBizNo;
				obj.extInfo.deptName = this.formData.extInfo.deptName;
				obj.extInfo.supplierName = this.form.supplierName;
				obj.extInfo.deliveryPhone = this.formData.extInfo.deliveryPhone;

				// 处理仓库id
				let warehouseId = [];
				let warehouseName = [];
				let warehouseIds = this.productList.map((item) => item.warehouseIds).flat();
				let warehouseNames = this.productList.map((item) => item.warehouseNames).flat();
				warehouseIds.forEach((item, index) => {
					if (!warehouseId.includes(item)) {
						warehouseId.push(item);
						warehouseName.push(warehouseNames[index]);
					}
				});
				obj.warehouseIds = warehouseId;
				obj.warehouseNames = warehouseName;
				obj._packingList = _packingList;
				const isVerifyData = await isVerifyRepeatIsStock({
					categoryCodes: this.productList.map((item) => item.categoryCode),
					batchNos: this.productList.map((item) => item.batchNo)
				});

				return new Promise((resolve, reject) => {
					if (isVerifyData?.length) {
						uni.showModal({
							title: '提示',
							content: `当前批次：${isVerifyData[0].batchNo},物品${isVerifyData
								.map((item) => item.categoryName)
								.join(',')}已有入库记录，是否继续入库！`,
							confirmText: '是',
							cancelText: '否',
							success: (res) => {
								if (res.confirm) {
									resolve(obj);
								} else {
									resolve(false);
								}
							}
						});
					} else {
						resolve(obj);
					}
				});
			},
			// 获取表数据
			getTableValue() {
				return new Promise(async (resolve, reject) => {
					try {
						const returnStorageData = await this.getReturnStorage();
						resolve({
							form: this.form,
							returnStorageData,
						});
					} catch(e) {
						reject(e);
					}
				});
			},
			// 单位选择变化
			onPackingUnitChange(e, row, index) {
				const val = e.detail.value;
				const item = row.packingSpecificationOption[val];
				if (item) {
					row.packingUnitId = item.id;
					row.packingUnit = item.conversionUnit;
					this.computeNum(row, index);
				}
			},
			// 包装完好选择变化
			onPackageOkChange(e, row) {
				const val = e.detail.value;
				row.ifPackageOkIndex = val;
				row.ifPackageOk = this.packageOkOptions[val].value;
				row.ifPackageOkLabel = this.packageOkOptions[val].label;
			},
			// 仓库选择变化
			onWarehouseChange(e, row) {
				const val = e.detail.value;
				const item = this.warehouseListOption[val];
				if (item) {
					row.warehouseId = item.id;
					row.warehouseName = item.name;
					row.warehouseIndex = val;
				}
			},
			// 供应商选择变化
			onSupplierChange(e, row) {
				const val = e.detail.value;
				const item = row.supplierListOptions[val];
				if (item) {
					row.supplierId = item.id;
					row.supplierName = item.name;
					row.supplierCode = item.serialNo;
				}
			},
			// 打开颜色选择器
			openColorPicker(row, index) {
				this.currentColorRow = row;
				this.currentColorIndex = index;
				// 获取已选中的颜色 ID 列表
				const selectedIds = row.colorKey ? row.colorKey.split(',') : [];
				// 初始化选择器
				this.$nextTick(() => {
					const picker = this.$refs.colorTreePicker;
					picker._initTree();
					// 设置已选中的项
					if (selectedIds.length > 0) {
						picker.treeList.forEach(item => {
							if (selectedIds.includes(item.id)) {
								item.checkStatus = 2;
								item.orCheckStatus = 2;
							}
						});
					}
					picker._show();
				});
			},
			// 颜色选择确认
			onColorConfirm(data, name, allList) {
				console.log('selectedList~~~', allList)
				if (allList && allList.length > 0) {
					const ids = allList.map(item => item.id).join(',');
					const names = allList.map(item => item.name).join(',');
					// 使用 $set 确保数据更新到 productList 中
					this.$set(this.productList[this.currentColorIndex], 'colorKey', ids);
					// 同时更新 currentColorRow 引用
					this.currentColorRow.colorKey = ids;
				} else {
					this.$set(this.productList[this.currentColorIndex], 'colorKey', '');
					this.currentColorRow.colorKey = '';
				}
			},
			// 打开机型选择器
			openModelPicker(row, index) {
				this.currentModelRow = row;
				this.currentModelIndex = index;
				// 获取已选中的机型 ID 列表
				const selectedIds = row.modelKey ? row.modelKey.split(',') : [];
				// 初始化选择器
				this.$nextTick(() => {
					const picker = this.$refs.modelTreePicker;
					picker._initTree();
					// 设置已选中的项
					if (selectedIds.length > 0) {
						picker.treeList.forEach(item => {
							if (selectedIds.includes(item.id)) {
								item.checkStatus = 2;
								item.orCheckStatus = 2;
							}
						});
					}
					picker._show();
				});
			},
			// 机型选择确认
			onModelConfirm(data, name, allList) {
				if (allList && allList.length > 0) {
					const ids = allList.map(item => item.id).join(',');
					const names = allList.map(item => item.name).join(',');
					// 使用 $set 确保数据更新到 productList 中
					this.$set(this.productList[this.currentModelIndex], 'modelKey', ids);
					// 同时更新 currentModelRow 引用
					this.currentModelRow.modelKey = ids;
				} else {
					this.$set(this.productList[this.currentModelIndex], 'modelKey', '');
					this.currentModelRow.modelKey = '';
				}
			},
			// 日期选择变化
			onDateChange(e, row, field) {
				row[field] = e.detail.value;
			},
			 //入库明细删除
			listDel(row, index) {
				this.productList.splice(index, 1);
				this.deletePackingAndMaterial(row);
			},
			// 根据产品信息删除包装和物料
			deletePackingAndMaterial(row) {
				// 删除包装(去掉不相同的包装)
				this.packingList = this.packingList.filter(
					(item) => item.parentIndex !== row.index
				);
				this.showPackingList = this.showPackingList.filter(
					(item) => item.parentIndex !== row.index
				);
				this.pickingPageNum = Math.ceil(
					this.showPackingList.length / this.pageSize
				);
				// 删除物料(获取相同物料)
				// let packingIndexs = this.packingList.map((item) => item.index);
				// this.materialList = this.materialList.filter((item) =>
				// 	packingIndexs.includes(item.parentIndex)
				// // );
				// this.showMaterialList = this.showMaterialList.filter((item) =>
				// 	packingIndexs.includes(item.parentIndex)
				// );
				// this.materielPageNum = Math.ceil(
				// 	this.showMaterialList.length / this.pageSize
				// );
			},
			// 产品批量保存
			async listSaveArrs() {
				this.validateForm()
				.then(async () => {
					// 批量获取包装编码并处理
					let packingCodePrams = this.productList.map((row) => {
					// 判断单位和计量单位是否为不拆物料层规格
					let packingBoolen = !!this.getDict(
						'不拆物料层规格',
						row.packingUnit
					).dictValue;
					let measureBoolen = !!this.getDict(
						'不拆物料层规格',
						row.measureUnit
					).dictValue;
					let num = 0;
					if (packingBoolen) {
						let filterArr = row.packingSpecificationOption.filter(
						(item) => {
							return (
							item.packageUnit == row.packingUnit &&
							item.packageUnit != item.conversionUnit
							);
						}
						);
						num = Math.ceil(row.packingQuantity / filterArr[0].packageCell);
					}
					if (row.isSave) {
						return {};
					} else {
						// 处理单位为KG类的情况
						if (packingBoolen) {
						return {
							assetCode: row.categoryCode + row.index,
							batchNum: row.batchNo,
							num
						};
						} else {
						if (row.isUnpack == 1) {
							if (measureBoolen) {
							// 处理单位不为KG类,计量单位为KG类的情况
							let num = row.packingQuantity;
							let splitIndex = row.packingSpecificationOption.findIndex(
								(item) =>
								item.conversionUnit == row.packingUnit &&
								item.packageUnit != item.conversionUnit
							);
							for (; splitIndex > 1; splitIndex--) {
								num = this.$math.format(
								num *
									row.packingSpecificationOption[splitIndex]
									.packageCell,
								14
								);
							}
							return {
								assetCode: row.categoryCode + row.index,
								batchNum: row.batchNo,
								num
							};
							} else {
							// 处理拆包到最小包装单元数量的情况
							return {
								assetCode: row.categoryCode + row.index,
								batchNum: row.batchNo,
								num: row.measureQuantity
							};
							}
						} else {
							return {
							assetCode: row.categoryCode + row.index,
							batchNum: row.batchNo,
							num
							};
						}
						}
					}
					});
					console.log('packingCodePrams', packingCodePrams);
					let filterPackingCodePrams = packingCodePrams.filter(
					(item) => item.assetCode
					);
					console.log('filterPackingCodePrams', filterPackingCodePrams);
					let { data } = await getAssetNum(filterPackingCodePrams);

					let packingCodeList = [];
					packingCodePrams.forEach((item, index) => {
						packingCodeList[index] = data.filter(
							(ite) => ite.assetCode == item.assetCode
						);
					});
					// 批量生成包装
					this.productList.map((row, index) => {
						if (!row.isSave) {
							this.generateWrappers(row, index, packingCodeList[index]);
							this.$set(this.productList[index], 'isSave', true);
						}
					});
					// 加载虚拟列表数据(分页)
					// this.pickingFetchData();
					// this.materielFetchData();
				})
				.catch((err) => {
					console.log(err);
				});
			},
			// 生成包装
			generateWrappers(row, productIndex, packingCodeList) {
				console.log(packingCodeList, 'packingCodeList', row.measureType);
				if (!row.measureType)
				return uni.showToast({
					title: '请到主数据维计量类型！',
					icon: 'none'
				});

				console.log('包装数据--------', row);
				// console.log('包装规格----', row.packingSpecificationOption);
				console.log('计量单位----', row.measureUnit);
				let packingList = [];
				// let obj = this.getNowDate();
				let productionDate = row.detailProductionDate || '';
				let purchaseDate = row.detailPurchaseDate || '';
				let expireDate = row.detailExpireDate || '';
				console.log(expireDate, 'expireDate');
				console.log(
				this.formData.bizType,
				'bizTypebizTypebizTypebizTypebizTypebizTypebizTypebizTypebizTypebizTypebizType'
				);
				if (this.formData.bizType == '1') {
					// 生产入库
					productionDate = this.getNowDate();
					// this.curDateType = 'productionDate';
				}

				// 判断单位和计量单位是否为不拆物料层规格
				let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit).dictValue;
				let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit).dictValue;

				let num = row.packingQuantity;
				let filterArr = [];
				// 处理单位为KG类的情况
				if (packingBoolen) {
					console.log(
						packingBoolen,
						'packingBoolenpackingBoolenpackingBoolenpackingBoolenpackingBoolenpackingBoolen'
					);
					if (!row.isUnpack && row.packingUnit == '立方') {
						num = 1;
					} else {
						filterArr = row.packingSpecificationOption.filter((item) => {
						return (
							item.packageUnit == row.packingUnit &&
							item.packageUnit != item.conversionUnit
						);
						});
						num = Math.ceil(row.packingQuantity / filterArr[0]?.packageCell);
					}
				} else {
					// if (row.isUnpack == 1) {
					if (measureBoolen) {
						// 处理单位不为KG类,计量单位为KG类的情况
						let splitIndex = row.packingSpecificationOption.findIndex(
							(item) =>
								item.conversionUnit == row.packingUnit &&
								item.packageUnit != item.conversionUnit
						);
						for (; splitIndex > 1; splitIndex--) {
							num = this.$math.format(
								num * row.packingSpecificationOption[splitIndex].packageCell,
								14
							);
						}
					} else {
						if (row.packingSpecificationOption[1]?.packageCell) {
							num = Math.ceil(
								row.measureQuantity /
								row.packingSpecificationOption[1]?.packageCell
							);
							filterArr = row.packingSpecificationOption.filter((item) => {
								return (
								item.packageUnit == row.packingUnit &&
								item.packageUnit != item.conversionUnit
								);
							});
						}
					}
				}
				console.log('num-----------', num);

				for (let index = 0; index < packingCodeList.length; index++) {
					let measureQuantity = 1;
					let packingQuantity = 1;
					let packingUnit = row.packingUnit;

					// 处理单位为KG类,计算每桶KG值
					if (packingBoolen) {
						measureQuantity = Number(row.packingQuantity) > this.$math.format(filterArr[0].packageCell * (index + 1), 14) ? filterArr[0].packageCell : Numbe(row.packingQuantity) - this.$math.format(filterArr[0].packageCell * index, 14);
						console.log(measureQuantity, 'measureQuantit1111y');
					} else {
						console.log('1 拆--------', measureBoolen);
						//计量单位等于重量单位并且有总重 计量数量=总重/包装数

						if (row.weightUnit == row.measureUnit && row.weight) {
							measureQuantity = Math.trunc((row.weight / packingCodeList.length) * 10000) / 10000;
						} else if (measureBoolen) {
							let splitIndex = row.packingSpecificationOption.findIndex((item) =>
								item.conversionUnit == row.packingUnit &&
								item.packageUnit != item.conversionUnit
							);
							for (; splitIndex > 0; splitIndex--) {
								measureQuantity = this.$math.format(
									measureQuantity *
										row.packingSpecificationOption[splitIndex].packageCell,
									14
								);
							}
						} else {
							measureQuantity = row.packingSpecificationOption[1].packageCell;
						}
						console.log(measureQuantity, 'measureQuantity');
					}
					let clientCode = '';
					if (this.bizType == 2) {
						clientCode = row?.customerMark;
					} else if (this.bizType != 2) {
						clientCode = row.extInfo?.clientCode;
					}

					console.log(filterArr[0], 'filterArr[0]');
					let status = null;
					if (row.qualityControl == 1) {
						status = 0;
					} else {
						status = 2;
					}
					let item = {
						index: row.index + '-' + index, // 包装索引
						warehouseId: row.warehouseId, // 仓库id
						warehouseName: row.warehouseName, // 仓库名称
						categoryName: row.categoryName, // 产品名称
						categoryCode: row.categoryCode, // 产品编码
						categoryModel: row.categoryModel, // 物品型号
						specification: row.specification, // 规格
						supplierCode: row.supplierCode, // 供应商编码
						supplierName: row.supplierName, // 供应商名称
						brandNum: row.brandNum, // 牌号
						parentIndex: row.index, // 产品索引
						batchNo: row.batchNo, // 批次号
						packageNo: packingCodeList[index]?.onlyCode, // 包装编码
						packingQuantity: packingQuantity, // 包装数量
						modelKey: row.modelKey, // 机型
						colorKey: row.colorKey, //颜色
						measureQuantity: measureQuantity, // 计量数量
						measureUnit: row.isUnpack
						? measureBoolen
							? row.packingSpecificationOption[1]
							? row.packingSpecificationOption[1].packageUnit
							: row.packingSpecificationOption[0].packageUnit
							: row.measureUnit
							: row.measureUnit, // 计量单位
						weight: 0, // 重量
						packingSpecificationOption: row.packingSpecificationOption, // 包装规格
						weightUnit: row.weightUnit, // 重量单位
						netWeight: row.netWeight, // 净重
						barcodes: '', // 发货条码
						clientCode: clientCode, // 客户代号
						materielDesignation: row.extInfo ? row.extInfo.materielCode : '', // 物料代号
						engrave: '', // 刻码
						isUnpack: row.isUnpack, // 是否允许拆包
						productionDate: productionDate, // 生产日期
						purchaseDate: purchaseDate, // 采购时间
						expireDate: expireDate, //失效日期
						result: 1, // 结果(1合格 2不合格)
						qualityControl: row.qualityControl,
						status: status // 状态(0=未质检 1待检 2已检)
					};

					if (row.isUnpack) {
						// 第二层条件: packingBoolen
						if (packingBoolen) {
							// 空值保护: 确保 filterArr[0] 存在
							item.packingUnit = row.packingSpecificationOption[1].conversionUnit;
						} else {
							// 第三层条件: measureBoolen
							if (measureBoolen) {
								// 处理 packingSpecificationOption 的索引
								const option =
								row.packingSpecificationOption?.[1] ||
								row.packingSpecificationOption?.[0];
								item.packingUnit = option?.conversionUnit;
							} else {
								item.packingUnit =
								row.packingSpecificationOption[1].conversionUnit;
							}
						}
					}
					let outBoolen = !!this.getDict('不拆物料层规格', item.measureUnit).dictValue;
					//计量单位等于重量单位
					if (row.weightUnit == row.measureUnit) {
						item.weight = item.measureQuantity
						? Number(item.measureQuantity)
						: 0;
					} else if (outBoolen) {
						// 计量单位为KG类，直接替换

						item.weight = item.measureQuantity
						? Number(item.measureQuantity)
						: 0;
					} else {
						console.log('计量单位为不为KG类======================');
						// 计量单位为不为KG类，重新统计计算
						let inBoolen = !!this.getDict('不拆物料层规格', item.packingSpecificationOption[0].packageUnit).dictValue;
						let startIndex = item.packingSpecificationOption.findIndex(
							(ite) => {
								return (
								item.measureUnit == ite.packingUnit &&
								ite.packingUnit != ite.conversionUnit
								);
							}
						);

						let endIndex = item.packingSpecificationOption.findIndex(
						(ite) => item.packingUnit == ite.conversionUnit
						);
						if (measureBoolen) {
							let total = item.packingQuantity ? Number(item.packingQuantity) : 0;
							for (; startIndex < endIndex; endIndex--) {
								total = this.$math.format(item.packingSpecificationOption[endIndex].packageCell * total, 14);
							}
							if (inBoolen) {
								// 第二层为KG类
								item.weight = total ? Number(total) : 0;
							} else {
								// 第二层不为KG类
								item.weight = this.$math.format(total * item.netWeight, 14);
							}
						} else if (!measureBoolen) {
							if (inBoolen) {
								// 第二层为KG类
								item.weight = item.measureQuantity ? Number(item.measureQuantity) : 0;
							} else {
								// 第二层不为KG类
								if (row.singleWeight && item.measureQuantity) {
									item.weight = Number(item.measureQuantity) * Number(row.singleWeight);
								} else {
									item.weight = 0;
								}
							}
						}
					}
					packingList.push(item);
					console.log(
						packingList,
						'packingList！！！！！！！！！！！！！！！！！！拆'
					);
				}

				// 单独点击保存并插入对应位置(包装)
				if (productIndex == 0) {
					this.packingList.splice(productIndex, 0, ...packingList);
				} else {
					let packingIndex = this.packingList.findLastIndex(
						(item) =>
						item.parentIndex == this.productList[productIndex - 1].index
					);
					this.packingList.splice(packingIndex + 1, 0, ...packingList);
				}
				let remainder = 0;
				if (row.weightUnit != row.measureUnit) {
					remainder =
						row.measureQuantity %
						row.packingSpecificationOption[1]?.packageCell;
				}

				if (remainder > 0) {
					let onlyCode = packingCodeList[packingCodeList.length - 1]?.onlyCode;
					let index = this.packingList.findIndex(
						(packingItem) => packingItem.packageNo == onlyCode
					);
					this.$set(this.packingList[index], 'measureQuantity', remainder);
					if (row.singleWeight) {
						this.$set(
							this.packingList[index],
							'weight',
							row.singleWeight * remainder
						);
					}
				}

			},
		}
	}
</script>

<style scoped>
.add {
	width: 96rpx;
	height: 96rpx;
	border-radius: 48rpx;
	background: #3c9cff;
	position: fixed;
	bottom: 100rpx;
	right: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 99;
}
/* 产品卡片样式 */
.product-card {
	background: #fff;
	margin: 20rpx;
	border-radius: 12rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}
.product-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}
.product-code {
	font-size: 26rpx;
	color: #333;
}
.card-body {
	padding: 0;
}
.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}
.info-row:last-child {
	border-bottom: none;
}
.info-label {
	font-size: 28rpx;
	color: #666;
	min-width: 160rpx;
}
.info-value {
	font-size: 28rpx;
	color: #333;
	text-align: right;
	flex: 1;
}
.red-text {
	color: #ff0000 !important;
}
.card-footer {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1rpx solid #eee;
}
.action-buttons {
	display: flex;
	gap: 20rpx;
}
/* 包装明细样式 */
.packing-section {
	margin-top: 40rpx;
	padding: 0 20rpx;
}
.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	padding: 20rpx 0;
}
.packing-card {
	background: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}
/* 批量操作按钮 */
.batch-actions {
	display: flex;
	gap: 20rpx;
	padding: 20rpx;
	background: #f8f8f8;
	margin-bottom: 20rpx;
}
/* 卡片序号 */
.card-index {
	font-size: 24rpx;
	color: #999;
	background: #f0f0f0;
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
}
/* 编辑行样式 */
.edit-row {
	background: #fafafa;
}
/* 必填标识 */
.required {
	color: #ff0000;
}
/* 输入框样式 */
.info-input {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #333;
	padding: 8rpx 0;
}
/* picker选择器样式 */
.info-picker {
	flex: 1;
	/* text-align: right; */
}
.picker-value {
	font-size: 28rpx;
	color: #333;
	padding: 16rpx 32rpx 16rpx 16rpx;
	/* background: #f0f0f0; */
	border-radius: 8rpx;
	display: inline-block;
	min-width: 160rpx;
	/* text-align: center; */
	position: relative;
	width: 100%;
	border: 1rpx solid #dadbde;
}
.picker-value::after {
	content: '';
	position: absolute;
	right: 8rpx;
	top: 50%;
	transform: translateY(-50%);
	border: 8rpx solid transparent;
	border-top-color: #666;
}
.picker-value.placeholder {
	color: #999;
	/* background: #e8e8e8; */
}
/* 仓库选择样式 */
.warehouse-select {
	flex: 1;
	text-align: right;
	padding: 8rpx 0;
}
/* 多选组件样式 */
.multi-select-container {
	flex: 1;
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	padding: 8rpx 0;
}
.multi-select-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: #f0f0f0;
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
}
.multi-select-label {
	color: #333;
}
/* 颜色选择器触发器样式 */
.color-picker-trigger {
	flex: 1;
	display: flex;
	justify-content: flex-end;
}
</style>