<template>
	<view class="lists">
		<view class="middle upload summary">
			<view class="summary-block">
				<image class="icon_plan" src="@/static/image/icon_plan@3x.png" mode=""></image>
				<text class="upload-text">合计金额</text>
			</view>
			<view>
				<text class="summary-num">{{intotalComputed}}</text>
			</view>
		</view>

		<view class="middle summary upload salescenter">
			<text class="middle-date">营销中心</text>
			<view class="middle-date-des uni-list picker-year">
				<view class="uni-list-cell">
					<view class="uni-list-cell-db">
						<picker class="picker-block" @change="bindPickerSalesCenterChange" mode="selector"
							:value="salesCenterIndex" range-key='VALUE' :range="selectedSalesCenterArr">
							<view class="uni-input">
								<text
									class="uni-input-text">{{selectedSalesCenterArr[salesCenterIndex] && selectedSalesCenterArr[salesCenterIndex].VALUE || '请选择'}}</text>
							</view>
						</picker>
					</view>
				</view>
				<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
			</view>
		</view>

		<scroll-view class="scroll-area view" :scroll-top="scrollTop" scroll-y="true">
			<view class="view">
				<view class="planout-block">
					<text class="planout-block-title">订购产品</text>
					<image class="planout-block-icon" src="@/static/image/order_more@3x.png" @click="addPlanout()"
						mode="aspectFit"></image>
				</view>
				<uni-swipe-action class="planout-block-lists">
					<uni-swipe-action-item v-for="(item,index) in planinnerLists" :key='index'>
						<view class="middle view planout-block-item">
							<view class="text-block title-first">
								<text class="middle-date title-first__text">{{index+1}}</text>
							</view>
							<view class="text-block" @click="selectProduct(index,'inner')">
								<text class="middle-date">产品</text>
								<view class="middle-date-des uni-list picker-year">
									<view class="uni-list-cell">
										<view class="uni-list-cell-db">
											<text class="middle-date-des">{{item.DESCRIPTION}}</text>
										</view>
									</view>
									<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit">
									</image>
								</view>
							</view>
							<view class="text-block">
								<text class="middle-date">数量（件）</text>
								<input class="middle-date-des" type="number" :value="item.quantity"
									@input="calcInnerTotal($event,item,index)"
									@blur="updateNoQuotaData(index,'inner',item)" placeholder="请填写" />
							</view>
							<view class="text-block">
								<text class="middle-date">单价</text>
								<text class="middle-date-des">{{item.NET_PRICE}}</text>
							</view>
							<view class="text-block text-block-last">
								<text class="middle-date">小计</text>
								<text class="middle-date-des">{{item.NET_VALUE}}</text>
							</view>
						</view>
						<template v-slot:right>
							<view class="swipe-right-block" @click="handleDel(index,'inner')">
								<text class="swipe-right-block__text">删除</text>
							</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>

			</view>

			<view class="bottom-area"></view>

			<view class="bottom">
				<button class="btn btn-l" type="default" @tap="preStep">
					<text class="btn-text btn-text-l">上一步</text>
				</button>
				<button class="btn" type="default" @tap="nextStep">
					<text class="btn-text">下一步</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		apiInitNoQuotaData,
		apiUpdateNoQuotaData
	} from '@/servers/noQuotaOrder.js'

	import {
		mapMutations,
		mapState
	} from 'vuex'

	export default {
		data() {
			return {
				scrollTop: 0,
				mode: 'inner',
				selectedSalesCenterArr: [{
					KEY: -1,
					VALUE: ''
				}],
				selectedSalesCenter: {},
				salesCenterIndex: -1,
				planinnerLists: [{
					checked: false,
					'quantity': 0,
					'total': 0,
					NET_VALUE: 0,
					'product_info': {},
				}],
				HEADINFO: {},
				productInitInfo: {}
			}
		},
		computed: {
			...mapState(['noQuotaOrder', 'userInfo']),
			intotalComputed() {
				let money = 0
				this.planinnerLists.forEach((item) => {
					money += item.NET_VALUE
				})
				return money
			}
		},
		created() {
			this.initNoQuotaData()
		},
		mounted() {
			console.log('监听到事件来自 onShow');
			let _this = this

			uni.$on('selectedProduct', function(data) {
				console.log('监听到事件来自 selectedProduct ，携带参数 msg 为：', data);
				const fromIndex = data.index * 1
				const selectedProduct = data.selectedProduct
				_this.mode = data.mode

				let product = {}
				_this.planinnerLists = _this.planinnerLists.map((item, i) => {
					if (i === fromIndex) {
						item.product_info = {
							...selectedProduct
						}
						product = {
							...item
						}
					}
					return item
				})

				_this.updateNoQuotaData(fromIndex, data.mode, product);

			})
		},
		onUnload() {
			console.log('onUnload')
			uni.$off('selectedProduct')
		},
		beforeDestroy() {
			console.log('onUnload2')
			uni.$off('selectedProduct')
		},
		methods: {
			// 初始化订单数据
			async initNoQuotaData() {
				const params = {
					'PARTNER': this.userInfo.code
				}
				const res = await apiInitNoQuotaData(params)
				const {
					HEAD,
					YXDY,
					ITEM
				} = res
				this.selectedSalesCenterArr = YXDY
				this.planinnerLists[0] = {
					...this.planinnerLists[0],
					...ITEM[0]
				}
				this.HEADINFO = HEAD
				this.productInitInfo = ITEM[0]
			},
			async updateNoQuotaData(productIndex, mode, product) {
				console.log('updateNoQuotaData---entry', productIndex, mode, product)
				let item_inner = []

				let productAfterInit = this.updateProductByInit(productIndex, mode, product)

				console.log('productAfterInit', productAfterInit)

				// 产品编号和件数 都有才请求
				if (!(productAfterInit?.product_info?.PRODUCT_ID &&
						productAfterInit?.ZZFLD000009)) {
					return
				}

				if (mode === 'inner') {
					item_inner = [productAfterInit]
				}

				const params = {
					"INFO": this.HEADINFO,
					"ITEM": item_inner,
				}
				const res = await apiUpdateNoQuotaData(params)
				console.log('updateNoQuotaData', res)
				const {
					ITEM,
					INFO,
				} = res.DATA

				this.HEADINFO = {
					...this.HEADINFO,
					...INFO
				}
				if (mode === 'inner') {
					this.planinnerLists = this.planinnerLists.map((item, i) => {
						if (i === productIndex) {
							item = {
								...item,
								...product,
								...ITEM[0]
							}
							// item.product_info = ITEM[0]
						}
						return item
					})

					console.log('planinnerLists', this.planinnerLists)
				}

			},
			// 更新选中的产品
			updateProductByInit(productIndex, mode, product) {
				const {
					PRODUCT_ID,
					SHORT_TEXT
				} = product.product_info
				let obj = {}
				if (mode === 'inner') {
					this.planinnerLists = this.planinnerLists.map((item, i) => {
						if (i === productIndex) {
							item.ORDERED_PROD = PRODUCT_ID
							item.DESCRIPTION = SHORT_TEXT
							item.ZZFLD000009 = item.quantity
							obj = item
						}
						return item
					})
				}
				return obj
			},
			calcInnerTotal(e, item, i) {
				console.log('sss', item, e)

				let value = 0
				if (e.target.value) {
					value = e.target.value
					e.target.value = value * 1
				} else {
					value = e.detail.value
					e.detail.value = value * 1
				}

				this.planinnerLists.forEach((product, index) => {
					if (i === index) {
						product.quantity = value * 1
						product.total = value * item.NET_VALUE * 1 || 0
					}
				})
				// value = `${value}`.replace(/[^0-9]/g, '') // 正则判断只能输入数字
			},
			handleDel(index, mode = 'inner') {
				if (mode === 'inner') {
					this.planinnerLists.splice(index, 1)
				}
			},
			selectProduct(index, mode = 'inner') {
				this.mode = mode
				if (this.salesCenterIndex !== -1) {
					uni.navigateTo({
						url: `/pages/select-product/select-product?from=noQuotaOrder&mode=${mode}&index=${index*1}&head=${JSON.stringify(this.HEADINFO)}`
					});
				} else {
					uni.showToast({
						title: '请先选择营销中心',
						duration: 2000,
						icon: 'none'
					});
				}

			},
			addPlanout() {
				let product = {
					checked: false,
					"PRODUCT_ID": "",
					"ORDERED_PROD": "",
					"DESCRIPTION": "",
					"SHORT_TEXT": "",
					'NET_PRICE': '',
					'NET_VALUE': '',
					'quantity': 0,
					'total': 0,
					NET_VALUE: 0,
					'product_info': {}
				}
				this.planinnerLists.unshift(product)
			},
			// 选择营销中心
			bindPickerSalesCenterChange(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.salesCenterIndex = e.detail.value
				this.selectedSalesCenter = this.selectedSalesCenterArr[this.salesCenterIndex]
				this.HEADINFO.ZZFLD000001 = this.selectedSalesCenter.KEY
			},
			nextStep() {
				let noQuotaOrder = {
					'ITEM': this.planinnerLists,
					'item_d': [],
					'ATTACHMENT': [],
					'INFO': this.HEADINFO,
				}
				this.$uStore({
					name: 'noQuotaOrder',
					value: noQuotaOrder
				});
				console.log('noQuotaOrder', noQuotaOrder)
				this.$emit('click', 'orderUpload')
			},
			preStep() {
				uni.switchTab({
					url: `/pages/go-order/go-order`
				})
			},
			...mapMutations(["$uStore"]),
		}
	}
</script>

<style lang="scss" scoped>
	.view {
		flex-direction: column;
	}

	.lists {
		position: relative;
		flex-direction: column;
		padding: 0 16rpx;
		// overflow-y: scroll;
	}

	.middle {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 40rpx 48rpx;
	}

	.summary-block {
		display: flex;
		align-items: center;
	}


	.text-block {
		overflow: hidden;
		height: 96rpx;
		margin-bottom: 14rpx;
		border-bottom: 1px solid #f4f5f6;
	}

	.text-block-last {
		margin-bottom: 0;
		border-bottom: 0;
	}

	.middle-date {
		flex: 2;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #333;
		margin-bottom: 8rpx;
	}

	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		line-height: 96rpx;
		height: 96rpx;
		color: #888;
	}

	.picker-year {
		position: relative;
		border-radius: 4px;
		align-items: center;
	}

	.title-first {
		border-bottom: 0;
		margin-bottom: 24rpx;
	}

	.title-first__text {
		font-size: 28rpx;
		color: #333333;
		font-weight: 600;
	}


	.uni-list-cell {
		flex: 1;
	}

	.uni-list-cell-db {
		flex: 1;
	}

	.picker-block {
		flex: 1;
	}

	.uni-input-text {
		font-size: 14px;
		color: #888;
	}

	.icon-arrow {
		position: absolute;
		right: 0;
		top: 16px;
		width: 12rpx;
		height: 20rpx;
		z-index: 10;
	}

	.upload {
		padding: 0;
		height: 136rpx;
		padding: 48rpx;
		margin-bottom: 0;
		align-items: center;
	}

	.upload-text {
		flex: 2;
		font-size: 14px;
		color: #999;
	}

	.summary {
		display: flex;
		margin-bottom: 32rpx;
		height: 176rpx;
		padding: 0 48rpx 0 24rpx;
		justify-content: space-between;
	}

	.salescenter {
		height: 100rpx;
	}

	.icon_plan {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}

	.summary-num {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
	}

	.scroll-area {
		padding-bottom: 40rpx;
	}

	.planout-block-lists {
		display: flex;
		flex-direction: column;
	}

	.uni-swipe {
		flex: 1;
		margin-bottom: 26rpx;
	}

	/deep/ .uni-swipe_box {
		flex: 1;
	}

	.swipe-right-block {
		width: 152rpx;
		background: linear-gradient(90deg, #fb4d61, #ff0f00 100%);
		border-radius: 0px 8px 8px 0px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.swipe-right-block__text {
		width: 152rpx;
		display: flex;
		align-items: center;
		color: #fff;
		font-size: 34rpx;
		font-weight: 500;
		text-align: center;
		padding-left: 24rpx;
	}

	.planout-block {
		display: flex;
		justify-content: space-between;
		height: 40rpx;
		margin-top: 48rpx;
		margin-bottom: 32rpx;
		padding: 0 24rpx;
	}

	.planout-block-title {
		font-size: 28rpx;
		color: #333;
		font-weight: 600;
	}

	.planout-block-icon {
		width: 32rpx;
		height: 40rpx;
	}

	.planout-block-item {
		flex: 1;
		width: 750rpx;
	}

	.bottom-area {
		height: 140rpx;
		margin-top: 12rpx;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 10;
		width: 750rpx;
		height: 140rpx;
		padding: 0 32rpx;
		background-color: #fff;
		justify-content: space-between;
		align-items: center;
	}

	.btn {
		flex: 1;
		height: 92rpx;
		background: $wly-primary-color;
		border-radius: 46rpx;
	}

	.btn-l {
		margin-right: 30rpx;
		border: 1px solid $wly-primary-color;
		background-color: transparent;

	}

	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}

	.btn-text-l {
		color: $wly-primary-color;
	}
</style>
