<template>
	<view class="task-form-container">
		<u-sticky offset-top="50">
			<u-subsection fontSize='25' mode='subsection' :list="list" :current="curNow" @change="sectionChange"
				activeColor='#157A2C' bgColor='#fff'></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="docNo" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.docNo"></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="contactName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.contactName"></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="receiveAddress" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.receiveAddress"></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="replied" borderBottom>
					<u--input style="width: 100%;" disabled v-model="form.repliedStr"></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>

		</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" 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>
								<!-- <u--input style="width: 100%;" :title='item[key.field]' disabled
									v-model="item[key.field]"></u--input> -->
									{{ key.formatter ? key.formatter(item) : item[key.field] }}
							</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="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="extInfo.assetType" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.extInfo.assetTypeName"></u--input>
				</u-form-item>
				<u-form-item label="出库时间" prop="storageTime" borderBottom>
					<!-- <u--input style="width: 100%;" disabled v-model="formData.storageTime"></u--input> -->
					 <!-- <uni-datetime-picker :end="finishTime" type="datetime" slot="value" v-model="formData.storageTime"
				@change="starTimeChange"> -->
					<uni-datetime-picker type="datetime" v-model="formData.storageTime" @change="changeStorageTime" />
			<!-- </uni-datetime-picker> -->
				</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="extInfo.verifyDeptName" borderBottom required>
					<u--input style="width: 100%;" v-model="formData.extInfo.verifyDeptName" @click.native="openDepartmentPicker"></u--input>
					<!-- <view :style="{ color: formData.extInfo.verifyDeptName ? 'black' : '#c0c4cc' }" class="assetType_box"
					@click="openDepartmentPicker">
					{{ formData.extInfo.verifyDeptName ? formData.extInfo.verifyDeptName : '请选择领料部门' }}
				</view> -->
				</u-form-item>
				<u-form-item label="领料人" prop="fromUser" borderBottom required>
					<u--input style="width: 100%;" v-model="formData.fromUser" @click.native="openUserPicker"></u--input>
					 <!-- <view :style="{ color: formData.fromUser ? 'black' : '#c0c4cc' }" class="assetType_box"
					@click="openUserPicker">
					{{ formData.fromUser ? formData.fromUser : '请选择领料人' }}
				</view> -->
				</u-form-item>
				<u-form-item label="客户名称" prop="clientName" borderBottom>
					<u--input style="width: 100%;" disabled v-model="formData.clientName"></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>
			<ba-tree-picker ref="departmentPicker" :multiple="false" @select-change="departmentConfirm" title="选择领料部门"
			:localdata="departmentOption" valueKey="id" textKey="name" childrenKey="children" />
			<!-- 选择领料人 -->
			<ba-tree-picker ref="userPicker" :multiple="false" @select-change="userConfirm" title="选择领料人"
				:localdata="userOption" valueKey="id" textKey="name" childrenKey="children" />
		</view>
		<view class="tab-content" v-show="curNow===3">
			<!-- <u-row v-if="isEdit">
				<u-col :span="3" offset="9">
					<u-button type="primary" size="small" text="添加" @click="addStock(item, index)"></u-button>
				</u-col>
			</u-row> -->
			<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 v-for="(item, index) in productList" :key="index">
					<u--form style="margin: 0 20px;" labelPosition="left" :model="form" labelWidth='140rpx'>
						<u-row v-for="(key,index1) in tableField2" :key="index1">
							<u-col :span="12">
								<u-form-item :label="key.label" borderBottom>
									<text>{{ key.formatter ? key.formatter(item) : item[key.field] }}</text>
								</u-form-item>
							</u-col>
						</u-row>
						<u-row v-if="isEdit">
							<u-col :span="3" offset="9">
								<u-button type="error" size="small" text="删除" @click="deleteProductList(item, index)"></u-button>
							</u-col>
						</u-row>
					</u--form>
					<u-gap height="40" bgColor="#f0f0f0"></u-gap>
				</view>
			</view>
			<view v-if="isEdit" class="add" @click="addStock">
				<u-icon name="plus" color="#fff"></u-icon>
			</view>
		</view>
		<view v-show="curNow===4">
			<view v-if="packingList.length === 0" class="empty-tip" style="text-align: center; color: #999; font-size: 28rpx; padding: 100rpx 0;">
				暂无包装清单数据
			</view>
			<view v-else>
				<view v-for="(item, index) in packingList" :key="index">
					<u--form style="margin: 0 20px;" labelPosition="left" :model="form" labelWidth='140rpx'>
						<u-row v-for="(key,index1) in tableField3" :key="index1">
							<u-col :span="12">
								<u-form-item :label="key.label" 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>
	</view>
</template>

<script>
	import { getByIdOnlyReplaceAPI, getUserById } from '@/api/wt/index.js'
	import { outputSceneState } from '@/enum/dict.js'
	import { parameterGetByCode } from '@/api/mainData/index.js'
	import { toTreeData } from '@/utils/utils.js'
	import { listOrganizations, getUserPage } from '@/api/common'
	import { getHierarchyFifo, getProduceTreeByPid } from '@/api/warehouseManagement/index.js'
	export default {
		props: {
			businessId: {
				default: ''
			},
			taskDefinitionKey: {
				default: ''
			},
			bizType: {
				default: 3
			},
			type: {
				default: '销售发货出库'
			},
			isEdit: {
				default: true
			}
		},
		data() {
			return {
				outRules: {
					verifyDeptName: {
						required: true,
						message: '请选择领料部门',
						trigger: ['blur', 'change']
					},
					fromUser: {
						required: true,
						message: '请选择领料人',
						trigger: ['blur', 'change']
					}
				},
				outputSceneState,
				clientEnvironmentId:
					uni.getStorageSync("userInfo") &&
					uni.getStorageSync("userInfo").clientEnvironmentId,
				pricingWayList: [
					{ id: 1, name: '按数量计价' },
					{ id: 2, name: '按重量计价' },
					{ id: 3, name: '按增重计价' }
				],
				form: {},
				tableField: [{
						label: '名称',
						field: 'productName',
					},
					{
						label: '计价方式',
						field: 'pricingWay',
						formatter: (row) => {
							return this.pricingWayList.find(item => item.id === row.pricingWay)?.name || '';
						}
					},
					{
						label: '编码',
						field: 'productCode',
					},
					{
						label: '类型',
						field: 'productCategoryName',
					},
					{
						label: '客户代号',
						field: 'customerMark',
					},
					{
						label: '单价',
						field: 'singlePrice',
					},
					{
					label: '数量',
					field: 'totalCount',
				},
				{
					label: '合计',
					field: 'totalPrice',
				},
				],
				tableField2: [{
						label: '名称',
						field: 'categoryName',
					},
					{
						label: '编码',
						field: 'categoryCode',
					},
					{
						label: '型号',
						field: 'categoryModel',
					},
					{
						label: '规格',
						field: 'specification',
					},
					{
						label: '牌号',
						field: 'brandNum',
					},
					{
						label: '批次号',
						field: 'batchNo',
					},
					{
						label: '颜色',
						field: 'colorKey',
					},
					{
						label: '计量数量',
						field: 'measureQuantity',
					},
					{
						label: '计量单位',
						field: 'measureUnit',
					},
					{
						label: '重量',
						field: 'weight',
					},
					{
						label: '重量单位',
						field: 'weightUnit',
					},
					{
						label: '单价',
						field: 'price',
					},
					{
						label: '金额',
						field: 'totalMoney',
					},
					{
						label: '仓库',
						field: 'warehouseName',
					},
					{
						label: '机型',
						field: 'modelKey',
					},
					{
						label: '供应商',
						field: 'supplierName',
					},
					{
						label: '供应商代号',
						field: 'supplierCode',
					},
				],
				tableField3: [{
						label: '编码',
						field: 'categoryCode',
					},
					{
						label: '名称',
						field: 'categoryName',
					},
					{
						label: '批次号',
						field: 'batchNo',
					},
					{
						label: '发货条码',
						field: 'barcodes',
					},
					{
						label: '包装编码',
						field: 'packageNo',
					},
					{
						label: '包装数量',
						field: 'packingQuantity',
					},
					{
						label: '包装单位',
						field: 'packingUnit',
					},
					{
						label: '计量数量',
						field: 'measureQuantity',
					},
					{
						label: '计量单位',
						field: 'measureUnit',
					},
					{
						label: '物料代号',
						field: 'materielDesignation',
					},
					{
						label: '客户代号',
						field: 'clientCode',
					},
					{
						label: '刻码',
						field: 'engrave',
					},
					{
						label: '重量',
						field: 'weight',
					},
					{
						label: '重量单位',
						field: 'weightUnit',
					},
					{
						label: '机型',
						field: 'modelKey',
					},
					{
						label: '颜色',
						field: 'colorKey',
					},
					{
						label: '质检结果',
						field: 'result',
						formatter: (row) => {
							return this.qualityResults[row.result] || '-';
						}
					},
					{
						label: '质检状态',
						field: 'status',
						formatter: (row) => {
							return this.qualityStatus[row.status] || '-';
						}
					},
					{
						label: '生产日期',
						field: 'productionDate',
					},
					{
						label: '采购日期',
						field: 'purchaseDate',
					},
					{
						label: '供应商',
						field: 'supplierName',
					},
					{
						label: '供应商代号',
						field: 'supplierCode',
					},
				],
				qualityResults: { 1: '合格', 2: '不合格' },
				qualityStatus: { 1: '未质检', 2: '已质检' },
				dimension: '3',
				curNow: 0,
				isPrice: 1,
				departmentOption: [],
				userOption: [],
				userInfo: {},
				formData: {
					storageTime: '',
					extInfo: {
						assetType: [], //物品类型id
						assetTypeName: '', //物品类型名称
						deptCode: '', //部门code
						deptName: '', //部门名称
						verifyDeptCode: '', //审核部门编码
						verifyDeptName: '', //审核部门名称
						deliveryName: '', //送货人名称
						fromUserPhone: '', //送货人电话
						sourceBizNo: '', //销售订单
						urgent: '', //紧急状态
						supplierId: '', //供应商ID
						supplierName: '', //供应商名称
						createUserName: '', //创建人名字
						contentImage: [] //图片数组
					},
					fromId: '', //领料人
					fromUser: '', //送货人
					bizType: '', //物品类型
					verifyId: '', //审核人Id
					verifyName: '', //审核人名称
					createUserId: '',
					remark: '',
					type: 2
				},
				productList: [],
				packingList: [],
				showPackingList: [],
				newColumns: [],
				goodsLists: [],
			}
		},
		computed: {
			list() {
				if(this.taskDefinitionKey == 'storemanApprove') {
					return ['发货信息', '物品清单', '出库信息', '出库清单', '包装清单']
				} else {
					return ['发货信息', '物品清单']
				}
			},
			columns() {
				const columns = [
					{
						columnKey: 'index',
						label: '序号',
						type: 'index',
						width: 55,
						align: 'center',
						showOverflowTooltip: true,
						fixed: 'left'
					},
					{
						label: '编码',
						prop: 'categoryCode',
						align: 'center',
						width: 150,
						showOverflowTooltip: true
					},
					{
						label: '名称',
						prop: 'categoryName',
						align: 'center',
						width: 150,
						showOverflowTooltip: true
					}
				];
				
				// 级别 - 仅 clientEnvironmentId == 4 时显示
				if (this.clientEnvironmentId == 4) {
					columns.push({
						label: '级别',
						prop: 'level',
						align: 'center'
					});
				}
				
				// 型号、规格、牌号
				columns.push(
					{
						label: '型号',
						prop: 'categoryModel',
						align: 'center',
						showOverflowTooltip: true
					},
					{
						label: '规格',
						prop: 'specification',
						align: 'center',
						showOverflowTooltip: true
					},
					{
						label: '牌号',
						prop: 'brandNum',
						align: 'center',
						showOverflowTooltip: true
					}
				);
				
				// 动态列
				this.newColumns.forEach(item => {
					columns.push({
						label: item.label,
						prop: item.prop,
						width: 120,
						align: item.align,
						showOverflowTooltip: item.showOverflowTooltip
					});
				});
				
				// 批次号
				columns.push({
					label: '批次号',
					prop: 'batchNo',
					align: 'center',
					showOverflowTooltip: true
				});
				
				// 包装数量、单位
				columns.push(
					{
						label: '包装数量',
						prop: 'packingQuantity',
						width: 80
					},
					{
						label: '单位',
						prop: 'packingUnit'
					}
				);
				
				// 计量数量、计量单位
				columns.push(
					{
						label: '计量数量',
						prop: 'measureQuantity',
						showOverflowTooltip: true
					},
					{
						label: '计量单位',
						prop: 'measureUnit'
					}
				);
				
				// 重量、重量单位
				columns.push(
					{
						label: '重量',
						prop: 'weight',
						align: 'center',
						showOverflowTooltip: true
					},
					{
						label: '重量单位',
						prop: 'weightUnit',
						align: 'center',
						showOverflowTooltip: true
					}
				);
				
				// 机型、颜色、锁定数量、库存
				columns.push(
					{
						label: '机型',
						prop: 'modelKey',
						width: 150
					},
					{
						label: '颜色',
						prop: 'colorKey',
						width: 150
					},
					{
						label: '锁定数量',
						prop: 'lockQuantity',
						width: 100
					},
					{
						label: '库存',
						prop: 'stockNum',
						align: 'center',
						showOverflowTooltip: true
					}
				);
				
				// 单价 - 条件显示
				if (this.isPrice == 1) {
					columns.push({
						label: '单价',
						prop: 'price',
						align: 'center',
						slot: 'price'
					});
				}
				
				// 金额 - 条件显示
				if (this.isPrice == 1) {
					columns.push({
						label: '金额',
						prop: 'totalMoney',
						align: 'center',
						showOverflowTooltip: true,
						slot: 'totalMoney'
					});
				}
				
				// 采购原因 - 仅 clientEnvironmentId == 4 时显示
				if (this.clientEnvironmentId == 4) {
					columns.push({
						label: '采购原因',
						prop: 'purpose',
						align: 'center',
						showOverflowTooltip: true
					});
				}
				
				// 仓库、供应商、供应商代号
				columns.push(
					{
						label: '仓库',
						prop: 'warehouseName',
						width: 150,
						showOverflowTooltip: true
					},
					{
						label: '供应商',
						prop: 'supplierName',
						minWidth: 150,
						showOverflowTooltip: true
					},
					{
						label: '供应商代号',
						prop: 'supplierCode',
						minWidth: 150,
						showOverflowTooltip: true
					}
				);
				
				// 操作列 - 仅在可编辑时显示
				if (this.isEdit) {
					columns.push({
						label: '操作',
						width: 120,
						align: 'center',
						slot: 'action',
						fixed: 'right'
					});
				}
				
				return columns;
			}
		},
		beforeDestroy() {
			uni.$off('setSelectList')
			uni.removeStorageSync('productList')
		},
		created() {
			uni.$on('setSelectList', async (data, dimension) => {
				uni.removeStorageSync('productList')
				console.log('setSelectList~~~', data, dimension)
				if (data?.length) {
					this.detailData(data, dimension)
				}
			})
		},
		async mounted() {
			this.userInfo = uni.getStorageSync('userInfo')
			this.$nextTick(() => {
				this.$refs.outForm?.setRules(this.outRules)
			})
			await this.getListItems()
			//仓库出入库是否显示金额（0：不显示 1：显示）
			parameterGetByCode({
				code: 'wms_price'
			}).then((res) => {
				this.isPrice = res.value;
			});
			await this.initDeptData();
			await this.getDetailData(this.businessId);
		},
		methods: {
			// 打开领料部门选择器
			openDepartmentPicker() {
				this.$refs.departmentPicker._show()
			},
			departmentConfirm(data, name, allList) {
				this.formData.extInfo.verifyDeptCode = data[0]
				this.formData.extInfo.verifyDeptName = name
				this.formData.fromId = ''
				this.formData.fromUser = ''
				this.getStaffList(data[0])
			},
			// 打开领料人选择器
			openUserPicker() {
				this.$refs.userPicker._show()
			},
			userConfirm(data, name) {
				this.formData.fromId = data[0]
				this.formData.fromUser = name
			},
			changeStorageTime(e) {
				console.log(e, 'changeStorageTime');
			},
			// 获取物品列表
			async getListItems() {
				const res = await getProduceTreeByPid({});
				this.goodsLists = res;
			},
			getFieldModel() {
				fieldModel({ fieldModel: 't_main_category' }).then((res) => {
					let newRes = res.map((m) => {
						return {
						prop: 'extField.' + m.prop,
						label: m.label,
						align: 'center',
						showOverflowTooltip: true
						};
					});
					this.newColumns = [...newRes];
				});
			},
			// 获取当前时间 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}`;
			},
			initFormData() {
				console.log('initFormData~~~', this.outputSceneState)
				// 出库类型
        		this.formData.bizType = this.bizType;
				this.formData.storageTime = this.getCurrentTime();
				this.formData.bizTypeStr = this.outputSceneState.find(item => item.code == this.bizType)?.label || ''
				this.formData.extInfo.assetType = Array.from(
					new Set(this.form.topCategoryIds?.split(','))
				);
				this.formData.extInfo.assetTypeName = this.formData.extInfo.assetType.map(id => {
					const item = this.goodsLists.find(g => g.id == id);
					return item?.name || id;
				}).join(',');
				console.log('formData.extInfo.assetTypeName:', this.formData.extInfo.assetTypeName);
				// 添加单据来源
				this.formData.sourceBizNo = this.form?.docNo;
				// 入库登记人
				this.formData.extInfo.createUserId = this.userInfo.userId;
				this.formData.extInfo.createUserName = this.userInfo.name;
				this.formData.createUserId = this.userInfo.userId;
				if (this.form.makerId) {
					getUserById(this.form.makerId).then((res) => {
						console.log(res, 'makerId');
						this.$set(this.formData.extInfo, 'verifyDeptCode', res.groupId);
						this.$set(this.formData.extInfo, 'verifyDeptName', res.groupName);
					});
				}

				// 销售相关逻辑
				if (this.form.productList?.length > 0) {
					this.formData.clientName = this.form.contactName;
					this.formData.clientCode = this.form.contactCode;
					// 获取领料人列表
					this.getStaffList(this.form.deptId).then(() => {
						// 获取领料人和领料部门
						this.formData.fromId = this.form.makerId;
						this.formData.fromUser = this.form.makerName;
						this.formData.extInfo.verifyDeptCode = this.form.deptId;
						this.formData.extInfo.verifyDeptName = this.form.deptName;
					});
					console.log(this.form.productList, 'this.saleProductList11111');
					let pData = {
						type: '1',
						deliveryNo: this.formData.sourceBizNo,
						builders: this.form.productList.map((item) => {
						return {
							categoryId: item.productId || item.categoryId,
							num: item.totalCount,
							// warehouseId: this.bizType == 3 ? item.warehouseId : ''
							batchNo: item.batchNo || '',
						};
						})
					};
					console.log('111~~~~~~~~', pData)
					getHierarchyFifo(pData)
						.then((data) => {
							this.detailData(data, this.dimension);
						})
						.catch((err) => {
							console.log(err);
						});
				}

				console.log('formData~~~', this.formData)
			},
			detailData(data, dimension) {
				console.log('detailData~~~', data, dimension)
				this.dimension = dimension;

				const mergedData = [...(this.formData.outInDetailList || []), ...data];
				this.formData.outInDetailList = mergedData;

				this.productList = data.map((productItem) => {
					return {
						...productItem,
						suspendBatchNo: productItem.batchNo || '',
						outInDetailRecordRequestList:
						productItem.outInDetailRecordRequestList.map((packingItem) => {
							return {
							...packingItem,
							workOrderId:
								this.type === '自选领用出库'
								? this.form.detailList[0].workOrderId
								: '',
							pickOrderId:
								this.type === '自选领用出库'
								? this.form.detailList[0].pickOrderId
								: '',
							taskId:
								this.type === '自选领用出库'
								? this.form.detailList[0].taskId
								: '',
							categoryName: productItem.categoryName,
							categoryCode: productItem.categoryCode,
							supplierCode: productItem.supplierCode,
							supplierName: productItem.supplierName,
							materialDetailList: packingItem.materialDetailList.map(
								(materialItem) => {
								return {
									...materialItem,
									categoryName: productItem.categoryName,
									categoryCode: productItem.categoryCode,
									supplierCode: productItem.supplierCode,
									supplierName: productItem.supplierName
								};
								}
							)
							};
						})
					};
				});

				const newProducts = mergedData.map((productItem) => ({
					...productItem,
					suspendBatchNo: productItem.batchNo || '',
					outInDetailRecordRequestList:
						productItem.outInDetailRecordRequestList.map((packingItem) => ({
						...packingItem,
						categoryName: productItem.categoryName,
						categoryCode: productItem.categoryCode,
						supplierCode: productItem.supplierCode,
						supplierName: productItem.supplierName,
						workOrderId:
							this.type === '自选领用出库'
							? this.form.detailList[0].workOrderId
							: '',
						pickOrderId:
							this.type === '自选领用出库'
							? this.form.detailList[0].pickOrderId
							: '',
						taskId:
							this.type === '自选领用出库'
							? this.form.detailList[0].taskId
							: '',
						materialDetailList: packingItem.materialDetailList.map(
							(materialItem) => ({
								...materialItem,
								categoryName: productItem.categoryName,
								categoryCode: productItem.categoryCode,
								supplierCode: productItem.supplierCode,
								supplierName: productItem.supplierName
							})
						)
						}))
					}));

				// 去重合并产品列表和新产品列表
				const uniqueProducts = [
				...new Map(
					[...this.productList, ...newProducts].map((item) => [item.id, item])
				).values()
				];
				this.productList = uniqueProducts;
				console.log('111111111111111');
				console.log(this.productList);
				// 排序
				this.productList.sort((a, b) => a.categoryCode - b.categoryCode);

				// 获取包装维度数据
				const arr = [];
				for (const key in this.productList) {
				for (const k in this.productList[key].outInDetailRecordRequestList) {
					arr.push({
					...this.productList[key].outInDetailRecordRequestList[k]
					});
				}
				}
				this.packingList = arr;

				const newPacking = [];
				newProducts.forEach((item) => {
				newPacking.push(...item.outInDetailRecordRequestList);
				});
				//去重
				const newPackingList = [
				...new Map(
					[...this.packingList, ...newPacking].map((item) => [item.id, item])
				).values()
				];
				this.packingList = newPackingList;

				this.packingList.sort((a, b) => a.categoryCode - b.categoryCode);

				// 获取物料维度数据
				// let iArr = [];
				// arr.forEach((item) => {
				// 	item.materialDetailList.forEach((ele) => {
				// 		iArr.push({ ...ele });
				// 	});
				// });
				// this.materialList = iArr;

				// const newMaterial = [];
				// newPacking.forEach((item) => {
				// 	newMaterial.push(...item.materialDetailList);
				// });
				// this.materialList = [...this.materialList, ...newMaterial];
				// 触发分页更新
				// this.pickingPageNum = 1;
				// this.materielPageNum = 1;
				// this.pickingFetchData();
				// this.materielFetchData();

				this.formData.outInDetailList = this.productList;

				console.log(this.productList, 'this.productList');
				console.log(this.packingList, 'this.packingList');
			},
			// 部门列表
			async initDeptData() {
				let deptTreeList = await listOrganizations()
				this.departmentOption = toTreeData({
					data: deptTreeList,
					idField: 'id',
					parentIdField: 'parentId'
				})
			},
			async getStaffList(id) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let res = await getUserPage({
					groupId: id,
					size: 9999,
					page: 1
				})
				uni.hideLoading()
				this.userOption = res.list
			},
			sectionChange(index) {
				this.curNow = index;
			},
			addStock() {
				console.log(this.formData.extInfo.assetType);
				if (
					!(
						this.formData.extInfo.assetType &&
						this.formData.extInfo.assetType.length > 0
					)
				)
				return uni.$u.toast('请选择出库产品类型')
				if (!this.formData.bizType && this.formData.bizType !== 0)
				return uni.$u.toast('请选择出库场景');
				uni.setStorageSync('productList', this.productList)
				uni.navigateTo({
					url: '/pages/warehouse/outHouse/selectOutType?assetType=' + this.formData.extInfo.assetType
				})

			},
			// 删除产品
			deleteProductList(row, index) {
				uni.showModal({
					title: '提示',
					content: '确定删除该产品吗？',
					success: (res) => {
						if (res.confirm) {
							this.productList.splice(index, 1);
						}
					}
				});
			},
			async getDetailData(id) {
				const data = await getByIdOnlyReplaceAPI(id);
				data.repliedStr = data.replied === 1 ? '是' : '否';
				this.form = data;
				console.log('form~~~', this.form)
				this.initFormData();
			},
			async getReturnStorage() {
				try {
					const valid = await this.$refs.outForm.validate();
					console.log('valid~~~', valid);
					if (!this.productList?.length) {
						return uni.$u.toast('请添加出库明细！');
					}
					let obj = JSON.parse(JSON.stringify({ ...this.formData, type: 2 }));

					obj.extInfo.sourceBizNo = obj.sourceBizNo;
					obj.fromType = obj.type;
					// 处理物品类型assetType
					obj.extInfo.assetType = obj.extInfo?.assetType.join(',');
					// 处理仓库id
					let warehouseId = [];
					let warehouseName = [];
					let warehouseIds = this.productList
						.map((item) => item.warehouseId)
						.flat();
					let warehouseNames = this.productList
						.map((item) => item.warehouseName)
						.flat();
					warehouseIds.forEach((item, index) => {
						if (!warehouseId.includes(item)) {
							warehouseId.push(item);
							warehouseName.push(warehouseNames[index]);
						}
					});
					obj.warehouseIds = warehouseId;
					obj.warehouseNames = warehouseName;
					console.log('2222', obj);
					let isPass = false;
					// 1按数量计费 2按重量计费
					if (this.form.pricingWay == 2) {
						// 判断包装重量是否全部大于0
						isPass = this.packingList.every((item) => item.weight > 0);
					} else {
						isPass = true;
					}
					if (isPass) {
						return obj;
					} else {
						uni.$u.toast('委外发货重量不能为空');
					}
				} catch (e) {
					console.log('验证失败', e);
					return null;
				}
			},
			//
			getTableValue() {
				return new Promise(async (resolve, reject) => {
					try {
						// await this.$refs.uForm[0].validate()
						// await this.$refs.outForm[0].validate()
						resolve({
							form: this.form,
							returnStorageData: await this.getReturnStorage()
						})
					} catch {
						reject(null)
					}


				})
			},
		}
	}
</script>
<style scoped>
/* .task-form-container { */
	/* padding-top: 20rpx; */
/* } */
.tab-content {
	padding-top: 20rpx;
}
.u-subsection--subsection {
	background-color: #fff;
}
.assetType_box {
	padding: 12rpx 18rpx;
	width: 100%;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	font-size: 30rpx;
}
.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;
}
</style>