<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="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 :scroll-top="scrollTop" scroll-y="true" class="scroll-Y view">
			<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')">
								<view class="middle-margin-date">
									<text class="mustPosIcon-margin">*</text>
									<text class="middle-margin-date">产品</text>
								</view>
								<!-- <text class="middle-date">产品</text> -->
								<view class="middle-date-margin-des uni-list picker-year">
									<view class="uni-list-cell">
										<view class="uni-list-cell-db">
											<text class="middle-date-margin-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="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 {
		props: {
			isKeepData: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				scrollTop: 0,
				mode: 'inner',
				selectedSalesCenterArr: [],
				selectedSalesCenter: {},
				salesCenterIndex: -1,
				planinnerLists: [{
					checked: false,
					'DESCRIPTION': "",
					'NET_PRICE': 0,
					'quantity': 0,
					'total': 0,
					NET_VALUE: 0,
					'product_info': {},
				}],
				HEADINFO: {},
				productInitInfo: {},
				Marketing: '',
			}
		},
		computed: {
			...mapState(['noQuotaOrder', 'userInfo']),
			intotalComputed() {
				let money = 0
				this.planinnerLists.forEach((item) => {
					money += item.NET_VALUE * 1
				})
				return money.toFixed(2)
			}
		},
		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
				if(YXDY.length === 1){
					this.salesCenterIndex = 0
					this.Marketing = this.selectedSalesCenterArr[0].VALUE
				}
				
				if (this.isKeepData) {
					const {
						INFO,
						ITEM: ITEM2,
					} = this.noQuotaOrder
					this.HEADINFO = {
						...HEAD,
						...INFO
					}
					this.planinnerLists = ITEM2
					this.salesCenterIndex = YXDY.findIndex((item) => {
						return this.HEADINFO.ZZFLD000001 === item.KEY
					})
					this.Marketing = this.selectedSalesCenterArr[this.salesCenterIndex].VALUE
					return
				}

				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': 0,
					'NET_VALUE': 0,
					'quantity': 0,
					'total': 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
				this.Marketing = this.selectedSalesCenter.VALUE
			},
			async updateGroupData() {
				const params = {
					"INFO": this.HEADINFO,
					"ITEM": this.planinnerLists,
				}
				const res = await apiUpdateNoQuotaData(params)
				return res.MSGTYPE === "S"
			},
			async nextStep() {
				if (this.salesCenterIndex === -1) {
					uni.showToast({
						title: '请先选择营销单元',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				const nameFlag = this.planinnerLists.every(function(item){
								return item.DESCRIPTION 
							});
				if (!nameFlag) {
					uni.showToast({
						title: '请先选择产品',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				const quantityFlag = this.planinnerLists.every(function(item){
								return item.quantity 
							});
				if (!quantityFlag) {
					uni.showToast({
						title: '请先填写数量',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				const flag = await this.updateGroupData()
				if(!flag){
					return
				}
				let noQuotaOrder = {
					'ITEM': this.planinnerLists,
					'item_d': [],
					'ATTACHMENT': [],
					'INFO':{ ...this.HEADINFO,Marketing:this.Marketing},
				}
				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;
		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-left: 4rpx;
	}

	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		line-height: 96rpx;
		height: 96rpx;
		color: #888;
	}
	.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: 50rpx;
		color: #333333;
		font-weight: 600;
		font-family: AvenirNext, AvenirNext-BoldItalic;
	}


	.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;
		height: 100rpx;
		margin-bottom: 10rpx;
		padding: 0 48rpx 0 24rpx;
		justify-content: space-between;
	}

	.salescenter {
		height: 80rpx;
		background: #fff;
		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;
	}

	::v-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;
		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: 600rpx;
		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;
	}
	.mustPosIcon-margin{
		color: #FF1D32;
		position: relative;
		top: 20rpx;
	}
	.middle-date-margin-des{
		flex: 3;
		font-size: 28rpx;
		color: #888;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		width: 200%;
		text-align: left;
		justify-content: end;
	}
	.middle-margin-date{
		flex: 2;
		font-size: 28rpx;
		color: #333;
		margin-left: 4rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
	.scroll-Y {
		height: 1000rpx;
	}
</style>
