<template>
	<selectAgent v-if="active == 'agent'"  @changeActive="changeActive"/>
	<view class="lists" v-else>
		<view class="status_bar" :style="navHeight"></view>
		<view class="header-bg">
			<image class="header-bg-img" src="@/static/image/nav_bg@3x.png" mode="scaleToFill"></image>
		</view>
		<view class="main" :class="{'source-main':isWine}" :style="mainHeight">
			<list ref="list" class="scroll-area view" loadmoreoffset='100' @loadmore="scrolltolower"
				:show-scrollbar='false'>
				<refresh @refresh="refresh" :display="refreshing ? 'show' : 'hide'">
				</refresh>
				<cell v-for="(item,index) in lists" :key="item.plan_number">
					<view class="scroll-item">
						<view class="checkBox" v-if="isWine">
							<checkbox-group @change="handleCheck(index,item)">
								<label>
									<checkbox :disabled='item.disabled' value="cb" :checked="item.checked" />
								</label>
							</checkbox-group>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">年度</text>
							<text class="item-block-value">{{item.annual}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">计划类型</text>
							<text class="item-block-value">{{item.zZFLD00002QTextView}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">制票类型</text>
							<text class="item-block-value">{{item.infTypeTextView}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">营销单元</text>
							<text class="item-block-value">{{item.zzfld000001TextView}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">发票号</text>
							<text class="item-block-value">{{item.invoId}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">产品</text>
							<text class="item-pro-value">{{item.productDesc}}</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">开票总量</text>
							<text class="item-block-value">{{item.invoiceQty}}件</text>
						</view>
						<view class="item-block item-block-code" v-if="isWine">
							<text class="item-block-label">开票总量</text>
							<text class="item-block-value">{{item.useBot}}瓶</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">已发数量</text>
							<text class="item-block-value">{{item.deliveryQty}}件</text>
						</view>
						<view class="item-block item-block-code" v-if="isWine">
							<text class="item-block-label">已发数量</text>
							<text class="item-block-value">{{item.deliverBot}}瓶</text>
						</view>
						<view class="item-block item-block-code">
							<text class="item-block-label">剩余数量</text>
							<text class="item-block-value">{{handleNum(item)}}</text>
						</view>
						<view class="bottom" v-if="!isWine">
							<view class="bottom-btn">
								<button class="btn btn-l" type="default" @tap="purchaseBtn(item)">
									<text class="btn-text btn-text-l">立即要货</text>
								</button>
							</view>
						</view>
					</view>
				</cell>
				<cell>
					<view class="loading-more" v-if='lists.length>2'>
						<text class="loading-more-text">{{loadingText}}</text>
					</view>
				</cell>
				<cell v-if='lists.length===0'>
					<view class="empty-block" v-if='lists.length===0'>
						<image class="icon-empty" src="@/static/image/no_data@3x.png" mode=""></image>
						<text class="empty-text">暂无数据</text>
					</view>
				</cell>
			</list>
			<view class="bottom-box" v-if="isWine">
				<button class="btn" type="default" @tap="nextStep">
					<text class="btn-text">立即要货</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'


	import {
		apiPurchaseList,
		apiGetUnFinishedInvByPromote
	} from '@/servers/purchaseList.js'

	import timeFormat from '@/uview-ui/libs/function/timeFormat.js'
	import selectAgent from '../select-agent/select-agent'
	export default {
		components: {
			selectAgent
		},
		data() {
			return {
				cb:'',
				scrollTop: 0,
				isOpened: 'none',
				loadingText: '加载中...',
				refreshing: false,
				page: {
					"page": "1",
					"pagesize": "10",
				},
				loadParams: {
					total: 0,
					totalPage: 1,
					isDone: false,
					isRefresh: false
				},
				selectedSalePlan: {},
				typesIndex: 0,
				lists: [],
				sourceType: 'wine',
				checkedArr: [],
				active: 'agent',
				row: {}
			}
		},
		computed: {
			...mapState(['sysinfo', 'userInfo','isChildCustomer']),
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			mainHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height - 44 - 30 }px`,
				}
			},
			scrollHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height - 44 - 156 }px`
				}
			},
			isWine(){
				return this.sourceType ==='wine' || this.sourceType ==='wineTerminal'
			}
		},
		onShow() {
		},
		created() {
			// this.sourceType = this.$route.query.type
			// this.getSalesPlanTypes(true)
			console.log(this.isChildCustomer,'isChildCustomer')
		},
		onLoad(option) {
			this.sourceType = option.type
			this.active = this.isChildCustomer ? 'agent' : 'query'
			this.lists = []
			if(this.isWine){
				this.active == 'query' && this.getWineList()
				this.reset()
				return
			}
			this.reset()
			this.active == 'query' && this.getSalesPlan()
			this.active == 'agent' && uni.setNavigationBarTitle({
			  title: '选择经销商'
			})
		},
		methods: {
			changeActive(type, row) {
			  this.active = type
			  this.row = row
			  console.log(this.row,'this.row')
			  if(this.isWine){
			  	this.getWineList()
			  	return
			  }
			  this.getSalesPlan()
			 //  if(type=='query'){
				// this.agentInfo = row
				// return
			 //  }
			},
			nextStep(){
				if(this.checkedArr.length === 0){
					uni.showToast({
						title: '请先选择要货单',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				// 两条数据件数瓶数累加除去箱装盒数大于1才能下一步
				let qtyNum = 0
				let botNum = 0
				this.checkedArr.forEach((ele,index) => {
				  qtyNum += ele.availableQty - 0
				  botNum += ele.availableBot - 0
				});
				qtyNum = qtyNum + parseInt(botNum/Number(this.checkedArr[0].xzhs))
				botNum = botNum%Number(this.checkedArr[0].xzhs)
				const row = {
				  ...this.checkedArr[0],
				  availableQty: qtyNum,
				  availableBot: botNum,
				  // invoInfoid: this.checkedArr[0].invoId,
				}
				if(row.availableQty - 0 === 0){
					uni.showToast({
						title: '选择的酒不够一件',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				const params = {
					...row,
					demandType: this.sourceType ==='wine' ? '1' : '2'
				}
				uni.navigateTo({
					url: `/pages/purchase/purchase-apply?order=${JSON.stringify(params)}&sourceType=purchase`
				})
			},
			handleCheck(idx,row){
				// this.$set(this.lists,idx,{...this.lists[idx],checked : !this.lists[idx].checked})
				this.lists[idx].checked = !this.lists[idx].checked
				this.checkedArr = []
				this.lists.forEach((ele,index) => {
					if(idx !== index){
						if(ele.productCode !== this.lists[idx].productCode || ele.zzfld000001 !== this.lists[idx].zzfld000001 ||ele.invoId !== this.lists[idx].invoId){
							ele.disabled = true
						}else{
							ele.disabled = false
						}
					}
					if(ele.checked){
						this.checkedArr.push(ele)
					}
					// if(ele.checked){
					// 	if(ele.productCode === row.productCode && ele.zzfld000001 === row.zzfld000001 && ele.invoId === row.invoId && ele.zZFLD00002Q === row.zZFLD00002Q && ele.availableBot === row.availableBot && ele.availableQty === row.availableQty ){
					// 		this.checkedArr.push(row)
					// 	}
					// }
				})
				
				this.lists.forEach((ele,index) => {
					if(this.checkedArr.length === 0){
						ele.disabled = false
					}
				})
			},
			handleNum(row){
				const qty = row.availableQty ? row.availableQty + '件' : ''
				const bot = row.availableBot ? row.availableBot + '瓶' : ''
				return qty + bot
			},
			purchaseBtn(item) {
				const params = {
					...item,
					demandType: this.sourceType ==='common' ? '1' : '2'
				}
				uni.navigateTo({
					url: `/pages/purchase/purchase-apply?order=${JSON.stringify(params)}&sourceType=purchase`
				})
			},
			async getSalesPlan(isRefresh) {
				// const params = {
				// 	...this.page,
				// }
				const demandType = this.sourceType ==='common' ? '1' : '2'
				const params = `?page=${this.page.page}&pagesize=${this.page.pagesize}&demandType=${demandType}&childLinkCustomer=${this.row?.customerCode || ''}`
				uni.showLoading({
					title: '加载中'
				});
				setTimeout(function() {
					uni.hideLoading();
				}, 2000);
				const res = await apiPurchaseList(params)
				uni.hideLoading();

				const {
					data,
				} = res
				this.page.page = data.page * 1
				// this.page.pagesize = 20 * 1
				this.loadParams.total = data.Total * 1
				this.loadParams.totalPage = Math.ceil(data.Total * 1 / this.page.pagesize * 1)
				const dataMap = data && data.Rows.length>0 && data.Rows.map((item) => {
					item.checked = false
					item.disabled = false
					return item
				}) || []

				if (isRefresh) {
					this.lists = dataMap
					this.loadParams.isDone = false
				} else {
					this.lists = this.lists.concat(dataMap)
				}

				setTimeout(() => {
					this.refreshing = false;
				}, 300)

			},
			async getWineList(isRefresh){
				const demandType = this.sourceType ==='wine' ? '1' : '2'
				const params = `?page=${this.page.page}&pagesize=${this.page.pagesize}&demandType=${demandType}&childLinkCustomer=${this.row?.customerCode || ''}`
				uni.showLoading({
					title: '加载中'
				});
				setTimeout(function() {
					uni.hideLoading();
				}, 2000);
				const res = await apiGetUnFinishedInvByPromote(params)
				uni.hideLoading();
				
				const {
					data,
				} = res
				this.page.page = data.page * 1
				// this.page.pagesize = 20 * 1
				this.loadParams.total = data.Total * 1
				this.loadParams.totalPage = Math.ceil(data.Total * 1 / this.page.pagesize * 1)
				const dataMap = data && data.Rows.length>0 && data.Rows.map((item) => {
					item.checked = false
					item.disabled = false
					return item
				}) || []
				this.checkedArr = []
				if (isRefresh) {
					this.lists = dataMap
					this.loadParams.isDone = false
				} else {
					this.lists = this.lists.concat(dataMap)
				}
				
				setTimeout(() => {
					this.refreshing = false;
				}, 300)
			},
			refresh(e) {
				this.refreshing = true;
				this.reset()
				this.getSalesPlanTypes(true)
				// this.getSalesPlan(true)
				// #ifdef APP-NVUE
				try {
					// console.log('-------', this.$refs.list)
					this.$refs.list.resetLoadmore();
				} catch (e) {
					console.log('onrefresh', e)
				}
				// #endif

			},
			scrolltolower() {
				console.log('onReachBottom');
				if (this.page.page < this.loadParams.totalPage) {
					this.page.page++
					this.getSalesPlanTypes()
					// this.getSalesPlan()
				} else {
					this.loadParams.isDone = true
					this.loadingText = '-- 到底了 --'
				}
			},
			reset() {
				this.loadParams = {
					total: 0,
					totalPage: 1,
					isDone: false,
					isRefresh: false
				}
				this.page.page = 1
				this.lists = []
				this.loadingText = '加载中'
			},
			getSalesPlanTypes(type=null) {
				if(this.isWine){
					this.getWineList(type)
					return
				}
				this.getSalesPlan(type)
			},
		}
	}
</script>

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

	.header-bg {
		height: 284rpx;
		opacity: 0.72;
		margin-top: -88rpx;
	}

	.header-bg-img {
		width: 750rpx;
	}

	.lists {
		position: relative;
		flex-direction: column;
		background: #f0f4f5;
		flex: 1;
	}

	.main {
		position: relative;
		flex-direction: column;
		margin-top: -164rpx;
		padding: 0 16rpx;
	}

	.scroll-area {
		overflow-y: scroll;
	}

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

	.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;
		overflow: hidden;
		text-overflow: ellipsis;
		color: #888;
	}

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

	.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;
	}

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

	.planout-block-item {
		margin-bottom: 32rpx;
	}

	.scroll-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-bottom: 32rpx;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 40rpx 48rpx;
	}

	.planout-block-item__last {
		height: 40px;
	}

	.item-block {
		overflow: hidden;
	}

	.item-block-label {
		font-size: 24rpx;
		color: #999;
		flex: 3;
		line-height: 56rpx;
	}
	
	.item-block-value {
		align-items: center;
		flex: 5.5;
		font-size: 24rpx;
		color: $text-base-color;
		line-height: 56rpx;
	}
	.item-pro-value{
		color: $text-base-color;
		font-size: 24rpx;
		width: 200%;
		flex: 5.5;
		text-align: left;
	}
	.item-block-code {
	}
	
	.item-block-label-des {
		flex: 1;
		text-align: left;
		font-size: 28rpx;
		color: #333;
	}

	.detal-item-label {
		color: #999;
		font-size: 24rpx;
	}

	.detal-item-value {
		color: #333;
		font-size: 28rpx;
	}

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

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

	.loading-more {
		flex: 1;
		align-items: center;
		justify-content: center;
		padding-top: 14px;
		padding-bottom: 14px;
		text-align: center;
	}

	.loading-more-text {
		font-size: 12px;
		color: #999;
	}
	.bottom {
		margin-top: 36rpx;
		flex: 1;
		justify-content: center;
	}
	.bottom-box {
		position: fixed;
		display: flex;
		bottom: 0;
		left: 0;
		z-index: 10;
		width: 750rpx;
		height: 140rpx;
		justify-content: space-around;
		align-items: center;
		background: #fff;
	}
	.bottom-btn{
		width: 328rpx;
		height: 92rpx;
		border-radius: 50%;
		justify-content: space-between;
		align-items: center;
	}
	
	.btn {
		flex: 1;
		background: $wly-primary-color;
	}

	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}
	.empty-block {
		width: 750rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.icon-empty {
		width: 150rpx;
		height: 150rpx;
		margin-top: 300rpx;
	}

	.empty-text {
		color: #999;
		margin-top: 56rpx;
		font-size: 28rpx;
	}
	.checkBox{
		display: flex;
		justify-content: flex-end;
		float: right;
		text-align: right;
	}
	.source-main{
		padding-bottom: 100rpx;
	}
</style>
