<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="summary upload salescenter top-radius">
			<text class="mustIcon">*</text>
			<text class="top-date">营销中心</text>
			<view class="top-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>
		<view class="summary upload salescenter">
			<text class="top-date">业务员</text>
			<text class="top-date-des">{{HEADINFO.ZZFLD000004_DSCR}}</text>
		</view>
		<!-- <view class="top-bot-border"></view> -->
		<view class="summary upload salescenter">
			<text class="top-date">备注</text>
		</view>
		<view class="remark bot-radius">
			<textarea class="remark-text" v-model="HEADINFO.ZZFLD000028" />
		</view>
		<scroll-view class="scroll-area view" :scroll-top="scrollTop" scroll-y="true" style="min-height: 1700rpx;">
			<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" v-if="item.isBigSingleProduct === 'TRUE'"
								@click="selectPlanOrder(item,index)">
								<view class="middle-date">
									<text class="mustPosIcon">*</text>
									<text class="middle-date">计划编号</text>
								</view>
								<!-- <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.ZZFLD00002Q_TEXT}}</text>
										</view>
									</view>
									<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit">
									</image>
								</view>
							</view>
							<view class="text-block" @click="selectProduct(index,'inner')">
								<view class="middle-date">
									<text class="mustPosIcon">*</text>
									<text class="middle-date">产品</text>
								</view>
								<!-- <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">
								<view class="middle-date">
									<text class="mustPosIcon">*</text>
									<text class="middle-date">数量（件）</text>
								</view>
								<!-- <text class="middle-date">数量（件）</text> -->
								<input class="middle-date-des" type="number" :value="item.quantity"
									@input="calcInnerTotal($event,item,index)"
									@blur="updateQuotaData(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 {
		apiUpdateGroupData
	} from '@/servers/groupOrder.js'

	import {
		mapMutations,
		mapState
	} from 'vuex'

	export default {
		data() {
			return {
				Marketing: '',
				scrollTop: 0,
				mode: 'inner',
				selectedSalesCenter: {},
				salesCenterIndex: -1,
				planinnerLists: [{
					checked: false,
					'ZZFLD00002Q_TEXT': '',
					"DESCRIPTION": "",
					'NET_PRICE': 0,
					'NET_VALUE': 0,
					'quantity': 0,
					'total': 0,
					'product_info': {},
					'isBigSingleProduct': 'FALSE'
				}],
				HEADINFO: {},
				productInitInfo: {},
			}
		},
		props: {
			isKeepData: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			...mapState(['groupOrder']),
			intotalComputed() {
				let money = 0
				this.planinnerLists.forEach((item) => {
					money += item.NET_VALUE * 1
				})
				return money.toFixed(2)
			},
			selectedSalesCenterArr() {
				return this.groupOrder.baseinfo.YXDY
			}
		},
		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.updateQuotaData(fromIndex, data.mode, product);

			})

			uni.$on('selectedGroupPlan', function(data) {
				console.log('监听到事件来自 selectedGroupPlan ，携带参数 msg 为：', data);
				const fromIndex = data.index * 1
				let selectedSalePlan = data.selectedSalePlan
				let selectedProductSalePlan = {}
				_this.planinnerLists = _this.planinnerLists.map((item, i) => {
					if (i === fromIndex) {
						item.salesplan_info = {
							...selectedSalePlan
						}
						item.ZZFLD00002Q = selectedSalePlan.PLAN_TYPE
						item.ZZFLD00002Q_TEXT = selectedSalePlan.PLAN_TYPE_DESC
						selectedProductSalePlan = {
							...item
						}
					}
					return item
				})

				// _this.updateQuotaData(fromIndex, 'inner', selectedProductSalePlan);
			})
		},
		onUnload() {
			console.log('onUnload')
			uni.$off('selectedProduct')
			uni.$off('selectedGroupPlan')
		},
		beforeDestroy() {
			console.log('onUnload2')
			uni.$off('selectedProduct')
			uni.$off('selectedGroupPlan')
		},
		created() {
			console.log(this.isKeepData,'this.isKeepData',this.groupOrder)
			const {
				INFO,
				ITEM,
				baseinfo
			} = this.groupOrder
			this.HEADINFO = INFO
			// this.planinnerLists[0] = {
			// 	...this.planinnerLists[0],
			// 	...ITEM[0]
			// }
			this.planinnerLists = [ ...ITEM ] 
			this.productInitInfo = ITEM[0]
			if(baseinfo && baseinfo.YXDY.length === 1){
				this.salesCenterIndex = 0
				this.Marketing = this.selectedSalesCenterArr[0].VALUE
			}
			// 回显营销
			if(this.isKeepData){
				this.selectedSalesCenterArr.forEach((ele,idx) => {
					if(ele.KEY === this.groupOrder.INFO.ZZFLD000001){
						this.salesCenterIndex = idx
						this.selectedSalesCenter = this.selectedSalesCenterArr[this.salesCenterIndex]
						this.HEADINFO.ZZFLD000001 = this.selectedSalesCenter.KEY
					}				
				});
				this.planinnerLists = [...this.groupOrder.ITEM]
			}
		},
		methods: {
			async updateQuotaData(productIndex, mode, product) {
				console.log('updateQuotaData---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 apiUpdateGroupData(params)
				console.log('updateQuotaData', res)
				const {
					ITEM,
					INFO
				} = res.DATA

				// let groupOrder = {
				// 	...this.groupOrder,
				// 	'INFO': INFO,
				// }
				// this.$uStore({
				// 	name: 'groupOrder',
				// 	value: groupOrder
				// });
				this.HEADINFO = {
					...this.HEADINFO,
					...INFO
				}
				if (mode === 'inner') {
					this.planinnerLists = this.planinnerLists.map((item, i) => {
						if (i === productIndex) {
							item = {
								...item,
								...product,
								...ITEM[0],
								isBigSingleProduct: res.DISPLAY // 是否为大单品产品
							}
						}
						return item
					})

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

			},
			// 更新选中的产品
			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)
				}
			},
			// 选择计划类型
			selectPlanOrder(product, index, mode = 'inner') {
				if (product.isBigSingleProduct === 'TRUE') {
					uni.navigateTo({
						url: `/pages/select-group-plan/select-group-plan?from=quotaOrder&product=${JSON.stringify((product))}&head=${JSON.stringify(this.HEADINFO)}`
					});
				} else {
					uni.showToast({
						title: '请先选择大单品产品',
						duration: 2000,
						icon: 'none'
					});
				}
			},
			selectProduct(index, mode = 'inner') {
				this.mode = mode
				if (this.salesCenterIndex !== -1) {
					uni.navigateTo({
						url: `/pages/select-product/select-product?from=groupOrder&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": "",
					'ZZFLD00002Q_TEXT': '',
					"DESCRIPTION": "",
					"SHORT_TEXT": "",
					'NET_PRICE': 0,
					'NET_VALUE': 0,
					'quantity': 0,
					'total': 0,
					'product_info': {},
					'isBigSingleProduct': 'FALSE'
				}
				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
				this.Marketing = this.selectedSalesCenter.VALUE
			},
			nextStep() {
				if (this.planinnerLists.some((item) => {
						return item.isBigSingleProduct === 'TRUE' && item.ZZFLD00002Q === ''
					})) {
					uni.showToast({
						title: '计划编号不能为空',
						duration: 2000,
						icon: 'none'
					});
					return
				}

				let groupOrder = {
					"baseinfo": this.groupOrder.baseinfo,
					'ITEM': this.planinnerLists,
					'ATTACHMENT': [],
					'INFO':{ ...this.HEADINFO,Marketing:this.Marketing},
				}
				this.$uStore({
					name: 'groupOrder',
					value: groupOrder
				});
				console.log('groupBaseInfo', groupOrder)

				this.$emit('click', 'orderUpload')
			},
			preStep() {
				let groupOrder = {
					"baseinfo": this.groupOrder.baseinfo,
					'ITEM': this.planinnerLists,
					'ATTACHMENT': [],
					'INFO':{ ...this.HEADINFO,Marketing:this.Marketing},
				}
				this.$uStore({
					name: 'groupOrder',
					value: groupOrder
				});
				this.$emit('click', 'groupBaseinfo', true)
			},
			...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: 3;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #333;
		margin-bottom: 8rpx;
		margin-left: 4rpx;
	}

	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		// line-height: 96rpx;
		height: 96rpx;
		color: #888;
		margin-top: 10rpx;
	}
	.middle-date-pro {
		flex: 3;
		font-size: 28rpx;
		// margin-top: 10rpx;
		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: 10rpx;
		height: 100rpx;
		padding: 0 48rpx 0 24rpx;
		justify-content: space-between;
		background: #fff;
	}

	.salescenter {
		height: 80rpx;
		margin-bottom: 0;
	}

	.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: #ff0f00;
		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;
		justify-content: 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;
	}
	.remark-text {
		flex: 1;
		height: 120rpx;
		background: #f5f6f7;
		border-radius: 4px;
		padding: 12rpx 18rpx;
		margin-bottom: 40rpx;
		font-size: 28rpx;
	}
	.remark{
		background: #fff;
		padding: 0 10px;
	}
	.top-bot-border{
		border-bottom: 1px solid #f4f5f6;
		margin: 0 24px 0 12px;
	}
	.top-date {
		flex: 2;
		font-size: 28rpx;
		line-height: 80rpx;
		color: #333;
		margin-bottom: 8rpx;
		margin-left: 4rpx;
	}
	
	.top-date-des {
		flex: 3;
		font-size: 28rpx;
		line-height: 80rpx;
		height: 80rpx;
		color: #888;
	}
	.bot-radius{
		border-bottom-left-radius: 10px;
		border-bottom-right-radius: 10px;
	}
	
	.top-radius{
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
	}
	.mustIcon {
		width: 16rpx;
		height: 40rpx;
		color: #FF1D32;
	}
	.mustPosIcon{
		color: #FF1D32;
		position: relative;
		top: 30rpx;
	}
</style>
