<template>
	<view class="lists">
		<view class="status_bar" :style="navHeight"></view>
		<view class="middle upload summary">
			<view class="summary-block">
				<text class="upload-text">预约</text>
			</view>
			<switch class="summary-num" color='red' :checked="isChecked" @change="switchChange" />
			<!-- <view class="summary-line summary-line-last">
				<text>材料保证金</text>
				<text>0.00</text>
			</view> -->
		</view>

		<view class="middle upload salescenter">
			<text class="middle-date">包材汇总保证金</text>
			<text class="middle-date-des">{{HEADINFO.huokuan}}</text>
		</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>

		<scroll-view class="scroll-area view" :scroll-top="scrollTop" scroll-y="true" :show-scrollbar='false'>
			<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="text" @blur="updateNoQuotaData(index,'',item)"
								v-model="item.planqty_box" placeholder="请填写" />
						</view>
						<view class="text-block">
							<text class="middle-date">期望交货日期</text>
							<text class="middle-date-des">{{item.pur_date}}</text>
						</view>
						<view class="text-block">
							<text class="middle-date">包材保证金</text>
							<text class="middle-date-des">{{item.huokuan}}</text>
						</view>
						<view class="text-block text-block-last">
							<text class="middle-date">备注</text>
							<input class="middle-date-des" type="text" v-model="item.remark" placeholder="请填写" />
						</view>
					</view>
					<template v-slot:right>
						<view class="swipe-right-block" @click="handleDel(index)">
							<text class="swipe-right-block__text">删除</text>
						</view>
					</template>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</scroll-view>

		<uni-popup ref="popup" background-color="#fff" @change="change" :mask-click='false'>
			<view class="popup-content">
				<view class="popup-content-head">
					<image class="popup-content-head__icon" src="@/static/image/order_success@3x.png" mode=""></image>
				</view>
				<view class="popup-content-content">
					<text class="popup-content-content__title">提交成功</text>
					<!-- <text class="popup-content-content__title2">生产计划编号：{{ orderInfo.OBJECT_ID }}</text> -->
					<text class="popup-content-content__title2">生产计划单号：{{ orderInfo.prodpl_id }}</text>
				</view>
				<view class="popup-content-foot">
					<text class="popup-content-foot__btn" @click="resetData()">继续添加</text>
					<text class="popup-content-foot__btn popup-content-foot__sure"
						@click="fnCheckOrderByNo()">查看计划</text>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	import {
		apiProducePlanInit,
		apiUpdateProducePlanData,
		apiUpdateProduceOrder,
		apiSubmitProduceOrder
	} from '@/servers/produceOrder.js'

	export default {
		data() {
			return {
				isChecked: false,
				scrollTop: 0,
				selectedSalesCenterArr: [{
					KEY: -1,
					VALUE: ''
				}],
				selectedSalesCenter: {},
				salesCenterIndex: -1,
				planinnerLists: [{
					checked: false,
					'planqty_box': 0,
					'total': 0,
					'description': '',
					'product_info': {},
				}],
				HEADINFO: {},
				productInitInfo: {},
				orderInfo: {
					prodpl_id: ''
					
				},
			}
		},
		computed: {
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			...mapState(['sysinfo', 'userInfo'])
		},
		onNavigationBarButtonTap(e) {
			this.submit()
		},
		created() {
			this.initProducePlanData()
		},
		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

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

				// _this.updateNoQuotaData(fromIndex, '', product);

			})
		},
		onUnload() {
			console.log('onUnload')
			uni.$off('selectedProduct')
		},
		beforeDestroy() {
			console.log('onUnload2')
			uni.$off('selectedProduct')
		},
		methods: {
			// 初始化订单数据
			async initProducePlanData() {
				const params = {
					'PARTNER': this.userInfo.code
				}
				const res = await apiProducePlanInit(params)
				const {
					head,
					yxdy,
					item
				} = res.data
				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 productAfterInit = this.updateProductByInit(productIndex, mode, product)
				const {
					PRODUCT_ID,
					SHORT_TEXT
				} = product.product_info
				let productAfterInit = []
				this.planinnerLists.forEach(item => {
					productAfterInit.push({
						...item,
						prod_id: PRODUCT_ID,
						description: SHORT_TEXT
					})
				});
				console.log('productAfterInit', productAfterInit)
				const flag = productAfterInit.every(function(item){
				    return item.prod_id 
				});
				if(!flag){
					return
				}
				const params = {
					"head": this.HEADINFO,
					"item": productAfterInit,
				}
				const res = await apiUpdateProducePlanData(params)
				console.log('updateNoQuotaData', res)
				this.HEADINFO.huokuan = res.data.head.huokuan || 0
				this.planinnerLists = this.planinnerLists.map((item, i) => {
					if (i === productIndex) {
						item = {
							...item,
							...product,
							...res.data.item[i]
						}
					}
					return item
				})

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

			},
			// 更新选中的产品
			updateProductByInit(productIndex, mode, product) {
				const {
					PRODUCT_ID,
					SHORT_TEXT
				} = product.product_info
				this.planinnerLists = this.planinnerLists.forEach(item => {
					item = {
						...item,
						prod_id: PRODUCT_ID,
						description: SHORT_TEXT
					}
				});
				return this.planinnerLists
				// let obj = {}
				// this.planinnerLists = this.planinnerLists.map((item, i) => {
				// 	if (i === productIndex) {
				// 		item.prod_id = PRODUCT_ID
				// 		item.description = SHORT_TEXT
				// 		item.planqty_box = item.planqty_box
				// 		obj = item
				// 	}
				// 	return item
				// })
				// return obj
			},
			selectProduct(index) {
					uni.navigateTo({
						url: `/pages/select-product-pro/select-product-pro?from=produceOrder&mode=&index=${index*1}&head=${JSON.stringify(this.HEADINFO)}`
					});
			},
			addPlanout() {
				let product = {
					checked: false,
					"product_id": "",
					"ordered_prod": "",
					"description": "",
					"short_text": "",
					'net_price': '',
					'net_value': '',
					'product_info': {},
					...this.productInitInfo
				}
				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.SALS_CENTER = this.selectedSalesCenter.VALUE
			},
			handleDel(index, ) {
				this.planinnerLists.splice(index, 1)
			},
			change(e) {
				console.log('当前模式：' + e.type + ',状态：' + e.show);
			},
			fnCheckOrderByNo() {
				this.$refs.popup.close()
				uni.redirectTo({
					url: `/pages/produce-order/produce-order`
				})
			},
			preStep() {
				uni.switchTab({
					url: `/pages/go-order/go-order`
				})
			},
			switchChange(e) {
				console.log('switch1 发生 change 事件，携带值为', e.detail.value)
				this.isChecked = e.detail.value
				this.HEADINFO.preorder = e.detail.value === false ? 0 : 1
			},
			async submit() {
				// const flag = this.planinnerLists.every(function(item){
				// 	console.log(item,'')
				//     return item.description 
				// });
				// console.log(flag,'123321')
				// if(!flag){
				// 	uni.showToast({
				// 		title: '请先选择产品',
				// 		duration: 2000,
				// 		icon: 'none'
				// 	});
				// 	return
				// }
				let res1 = null
				try{
					const params = {
						head: this.HEADINFO,
						item: this.planinnerLists
					}
					res1 = await apiUpdateProduceOrder(params)
					if(res1.msgtype !== 'S'){
						return
					}
				}catch(e){
					//TODO handle the exception
				}
				try{
					const { head, item } = res1.data
					const params2 = {
						ROLE:'WLY001',
						MODE: 'SUBMIT',
						head,
						item
					}
					// this.HEADINFO = HEAD2
					//  this.planinnerLists = ITEM2
					const res2 = await apiSubmitProduceOrder(params2)
					if(res2.msgtype !== 'S'){
						return
					}
					this.orderInfo = {...res1.data.head}
					this.$refs.popup.open('center')
				}catch(e){
					//TODO handle the exception
				}
			},
			resetData() {
				this.$refs.popup.close()
				this.planinnerLists = []
				this.salesCenterIndex = -1
				this.selectedSalesCenter = {}
				this.initProducePlanData()
			}
		}
	}
</script>

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

	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
		background: $background-color-1;
	}

	.status_bar {
		height: var(--status-bar-height);
	}

	/* #endif */

	.lists {
		width: 750rpx;
		position: relative;
		flex-direction: column;
		padding: 32rpx 16rpx 0;
		background: #f0f4f5;
		flex: 1;
	}

	.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;
		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-text {
		flex: 2;
		color: #333;
		font-size: 28rpx;
	}

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

	.salescenter {
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 16px 0 24px;
	}

	.summary-line {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.summary-line-last {
		margin-top: 12rpx;
		padding-right: 8rpx;
	}

	.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;
		text-align: center;
		color: #fff;
		font-size: 34rpx;
		font-weight: 500;
		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;
	}

	/deep/ .uni-popup__wrapper {
		border-radius: 20rpx;
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 580rpx;
		height: 408rpx;
		background: #ffffff;
		border-radius: 24rpx;
	}

	.popup-content-head {
		margin-top: 56rpx;
		margin-bottom: 16rpx;
	}

	.popup-content-head__icon {
		width: 80rpx;
		height: 80rpx;
	}

	.popup-content-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 52rpx;
	}

	.popup-content-content__title {
		font-size: 32rpx;
		color: #444;
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	.popup-content-content__title2 {
		color: #999999;
		font-size: 24rpx;
	}

	.popup-content-foot {}

	.popup-content-foot__btn {
		width: 152rpx;
		height: 60rpx;
		line-height: 60rpx;
		background: #ffedee;
		text-align: center;
		color: #ff0f00;
		font-weight: 500;
		border-radius: 32rpx;
		font-size: 22rpx;
	}

	.popup-content-foot__sure {
		margin-left: 40rpx;
		color: #fff;
		background: #ff1d32;
		border: 1px solid #ff1d32;
	}
	.scroll-area{
		min-height: 2666rpx;
	}
</style>
