<template>
	<view class="detail-view">
		<u-form label-width="160" :model="add_form" ref="uForm">
			<view class="form-model-view">
				<u-form-item required label="所属仓库" prop="warehouseName">
					<u-input @click="goPage('/pagesT/werahouse/selWerahouse')" class="dis-input" disabled v-model="add_form.warehouseName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item required label="盘点日期" prop="buyerName">
					<picker mode="date" @change="bindDateChange">
						<view style="width: 510rpx;text-align: right;margin-right: 10rpx;display: inline-block;">
							<text v-if="add_form.stocktakingTime">{{ $u.timeFormat(add_form.stocktakingTime, 'yyyy-mm-dd') }}</text>
							<text style="color:#B8C0C8;" v-else>请选择</text>
						</view>
						<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
					</picker>
				</u-form-item>
			</view>
			<view class="form-model-view">
				<u-form-item required label="商品清单">
					<view @click="selGoodsPage" class="form-value add-btn-go">
						<u-icon name="plus" size="24"></u-icon>
						<text>选择商品</text>
					</view>
				</u-form-item>
				<view class="goods-ul" v-if="goods_list.length">
					<block v-for="(item, index) in goods_list" :key="index">
						<view class="goods-li clearfix">
							<view class="goods-img float_left" @click="delGoods(item, index)"><u-icon size="40" name="minus-circle-fill" color="#fa3534"></u-icon></view>
							<view class="float_left info">
								<view class="goods-name ellipsis">{{ item.materielName }}</view>
								<view class="goods-code">{{ item.materielCode }}</view>
								<view class="goods-num clearfix">
									<view class="float_left">{{ item.unitName }};{{ item.skuName }}</view>
									<view class="float_right">账目库存: {{ $utils.formatNub(item.documentInventoryNum) }}</view>
								</view>
								<view class="num-ul">
									<view class="num-li">
										<view class="label">实盘库存</view>
										<input @blur="editNumChange(index)" type="digit" placeholder="请输入" v-model="item.currentInventoryNum" />
									</view>
									<view class="num-li" v-if="item.isEq === 5">
										<view class="label">其他单位</view>
										<input type="digit" placeholder="请输入" v-model="item.otherNum" />
									</view>
									<view class="num-li">
										<view class="label">盈亏数量</view>
										<input type="digit" class="input-dis" disabled :value="item.diffNum > 0 ? `+${item.diffNum}` : item.diffNum" />
									</view>
									<view class="num-li" v-if="enableLocationManagement === 5">
										<view class="label">库区库位</view>
										<input
											@click="openLocation(index, item)"
											disabled
											type="text"
											placeholder="请选择"
											:value="item.storageLocationName ? item.areaName + '-' + item.storageLocationName : ''"
										/>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>
			</view>
			<view class="form-model-view">
				<u-form-item label="备注" label-position="top"><u-input type="textarea" v-model="add_form.remark" /></u-form-item>
			</view>
		</u-form>
		<view class="detail-bottom"><u-button class="handel-btn" @click="submit" :loading="sub_load" :ripple="true" type="primary">提交</u-button></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			sub_load: false,
			rules: {
				warehouseName: [
					{
						required: true,
						message: '请选择仓库',
						trigger: ['change', 'blur']
					}
				]
			},
			goods_id: [],
			werahouseData: '',
			warehouseGoods: '',
			goods_num: '',
			add_form: {
				warehouseId: '',
				warehouseName: '',
				operatorName: '',
				remark: '',
				stocktakingTime: '',
				details: []
			},
			goods_list: [],
			del_goods_id: [],
			goods_index: 0,
			areaBysku: ''
		};
	},
	computed: {
		userName() {
			return this.$store.state.userInfo.name;
		},
		enableLocationManagement() {
			return parseInt(this.$store.state.basicSet.enableLocationManagement);
		}
	},
	watch: {
		werahouseData(val) {
			if (val) {
				this.add_form.warehouseId = val.id;
				this.add_form.warehouseName = val.warehouseName;
			}
		},
		// 选择商品资料页面返回
		warehouseGoods(list) {
			if (list) {
				this.selGoods(list);
			}
		},
		areaBysku(val) {
			if (val) {
				const target = this.$u.deepClone(this.goods_list);
				target[this.goods_index] = {
					...target[this.goods_index],
					areaId: val.areaId,
					areaName: val.areaName,
					areaCode: val.areaCode,
					storageLocationId: val.storageLocationId,
					storageLocationName: val.storageLocationName,
					storageLocationCode: val.storageLocationCode
				};
				this.goods_list = target;
			}
		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	onLoad(options) {
		if (options.id) {
			this.invenrory_id = options.id;
			uni.setNavigationBarTitle({
				title: '编辑盘点单'
			});
			this.getStocktakingInfo();
		} else {
			this.add_form.stocktakingTime = parseInt(new Date().getTime() / 1000);
		}
	},
	methods: {
		// 去选择库区库位页面
		openLocation(index, row) {
			this.goods_index = index;
			this.goPage(`/pagesT/stock/WarehouseRegionBySku?basicGoodsId=${row.materielId}&skuId=${row.skuId}&warehouseId=${this.add_form.warehouseId}`);
		},
		delGoods(row, index) {
			if (row.id) {
				this.del_goods_id.push(row.id);
			}
			this.goods_list.splice(index, 1);
		},
		selGoodsPage() {
			if (!this.add_form.warehouseId) {
				this.$u.toast('请选择仓库');
				return;
			}
			uni.setStorageSync('warehouseGoods', this.goods_list);
			this.goPage('/pagesT/goods/GoodsbyWarehouse?id=' + this.add_form.warehouseId);
		},
		// 详情
		getStocktakingInfo() {
			this.$u.api.getStocktakingInfo(this.invenrory_id).then(({ data }) => {
				this.add_form = {
					warehouseId: data.warehouseId,
					warehouseName: data.warehouseName,
					operatorName: data.operatorName,
					remark: data.remark,
					stocktakingTime: data.stocktakingTime,
					details: data.details
				};
				// 商品
				this.goods_list = data.details.map(item => {
					return {
						id: item.id,
						buyNum: 1,
						materielId: item.materielId,
						materielName: item.materielName,
						materielCode: item.materielCode,
						skuId: item.skuId,
						skuName: item.skuName,
						unitName: item.unitName,
						diffNum: item.differenceStatus === 4 ? 0 - item.differenceNum : item.differenceNum - 0,
						remark: item.remark,
						costUnitPrice: item.costUnitPrice || 0,
						documentInventoryNum: Number(item.documentInventoryNum), // 账面库存
						currentInventoryNum: Number(item.currentInventoryNum), // 实盘库存
						otherNum: Number(item.otherNum), // 其他单位
						areaId: item.areaId,
						areaName: item.areaName,
						areaCode: item.areaCode,
						storageLocationName: item.storageLocationName,
						storageLocationId: item.storageLocationId,
						storageLocationCode: item.storageLocationCode
					};
				});
			});
		},
		bindDateChange(e) {
			this.add_form.stocktakingTime = this.$utils.timeByTimestamp(e.detail.value + ' 00:00:00');
		},
		// 改变数量
		editNumChange(index) {
			let target = this.$u.deepClone(this.goods_list);
			target[index].diffNum = this.$NP.minus(target[index].currentInventoryNum, target[index].documentInventoryNum);
			this.goods_list = target;
		},
		// 多选商品确定
		selGoods(list) {
			this.goods_list = list.map(item => {
				return {
					isEq: item.isEq,
					otherNum: Number(item.otherNum) || '',
					materielId: item.materielId,
					materielCode: item.materielCode,
					materielName: item.materielName,
					warehouseName: this.add_form.warehouseName,
					skuName: item.skuName,
					skuId: item.skuId,
					unitName: item.unitName,
					currentInventoryNum: Number(item.inventoryNum), // 实盘库存
					costUnitPrice: Number(item.costPrice),
					diffNum: 0,
					remark: '',
					buyNum: 1,
					documentInventoryNum: item.allNum, // 账面库存
					areaId: '',
					areaName: '',
					areaCode: '',
					storageLocationName: '',
					storageLocationId: '',
					storageLocationCode: ''
				};
			});
		},
		submit() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					if (!this.goods_list.length) {
						this.$u.toast('请选择商品');
						return;
					}
					const details = this.$u.deepClone(this.goods_list).map(item => {
						delete item.diffNum;
						delete item.buyerNum;
						return item;
					});
					const params = {
						...this.add_form,
						operatorName: this.userName,
						details: details
					};
					this.sub_load = true;
					if (this.invenrory_id) {
						this.$u.api
							.updateStocktaking(this.invenrory_id, {
								...params,
								deleteArray: this.del_goods_id
							})
							.then(res => {
								this.sub_load = false;
								this.$u.toast('修改成功');
								setTimeout(() => {
									uni.navigateBack();
								}, 2000);
							})
							.catch(err => {
								this.sub_load = false;
							});
					} else {
						this.$u.api
							.addStocktaking(params)
							.then(res => {
								this.sub_load = false;
								this.$u.toast('新建成功');
								setTimeout(() => {
									uni.navigateBack();
								}, 2000);
							})
							.catch(err => {
								this.sub_load = false;
							});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.goods-ul {
	padding-bottom: 20rpx;
	.more-goods {
		line-height: 80rpx;
		border-top: 1px solid #eeeeee;
		text-align: center;
		font-size: 24rpx;
	}

	.goods-title {
		margin-bottom: 20rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		border-bottom: 1px solid #eeeeee;

		.float_right {
			color: $uni-color-primary;
		}
	}

	.goods-li {
		line-height: 32rpx;
		margin-top: 20rpx;

		.goods-img {
			margin-right: 20rpx;
			image {
				width: 150rpx;
				height: 150rpx;
				border-radius: 8rpx;
				display: block;
			}
		}

		.info {
			width: 640rpx;
			.num-ul {
				display: flex;
				padding-top: 20rpx;
				.num-li {
					font-size: 24rpx;
					line-height: 36rpx;
					flex: 3;
					text-align: center;
					position: relative;
					font-weight: bold;
					padding: 0 16rpx;
					.label {
						font-weight: 400;
						color: #999999;
					}
					input {
						text-align: center;
						border-bottom: 1px solid $uni-color-primary;
						&.input-dis {
							border-bottom: 1px solid #eeeeee;
						}
					}
					&::after {
						display: block;
						content: '';
						position: absolute;
						width: 1px;
						height: 60rpx;
						top: 50%;
						transform: translateY(-50%);
						right: 0;
						background-color: #eeeeee;
					}
					&:last-child {
						&::after {
							display: block;
							content: '';
							position: absolute;
							width: 1px;
							height: 50rpx;
							top: 50%;
							transform: translateY(-50%);
							right: 0;
							background-color: transparent;
						}
					}
				}
			}
			.goods-name {
				width: 640rpx;
				height: 34rpx;
				line-height: 34rpx;
			}

			.goods-code {
				font-size: 24rpx;
				padding-top: 10rpx;
			}

			.goods-num {
				padding-top: 10rpx;
				font-size: 24rpx;

				.price {
					font-size: 28rpx;
					font-weight: bold;
					color: $uni-color-error;
				}
			}
		}
	}
}
</style>
