<template>
	<view class="apply-history view" :style="winHeight">
		<view class="status_bar" :style="navHeight"></view>
		<view class="apply-history-wrapper view">
			<component :style="componentHeight" :sourceType='sourceType' :orderItem='detail' :channelTypeArr='channelTypeArr' :releaseNum='releaseNum' :is="currentTabComponent" @click="changeComponent" @submit="submit" ></component>
		</view>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	import { initAppWantGoods, getChannelType, findById, generateUUID, queryDirectStore,queryPledgeQuantity } from '@/servers/purchaseList.js'

	import purchaseMain from '../purchase-main/purchase-main'
	import purchaseReceive from '../purchase-receive/purchase-receive'
	
	// #ifdef APP-PLUS
	const dom = weex.requireModule('dom');
	// #endif

	export default {
		components: {
			purchaseMain,
			purchaseReceive,
		},
		data() {
			return {
				releaseNum: 0,
				terminalRobotArrs: [],
				demandType: '1',
				sourceType: '',
				channelTypeArr: [],
				currentTabComponent: 'purchaseMain',
				topHeight: '',
				detail: {},
				orderItem: {
					ticketTypeVal: '',
					deliveryPlanCode: '',
					deliveryPlanName: ' ',
					channelTypeCode: '',
					channelTypeName: ' ',
					marketPlaceCode: '',
					marketPlaceName: ' ',
					quantity: '',
					shuntTypeCode: '',
					shuntTypeName: ' ',
					shuntCode: '',
					shuntName: ' ',
					receiveUnitName: ' ',
					contactNumber: '',
					contacPerson: '',
					receiveAddress: '',
					shuntingCustomer: '',
					shuntingCustomerAdress: ''
				},
			}
		},
		computed: {
			componentHeight(){
				// console.log('componentHeight',`${this.sysinfo.safeArea.height - 44 - this.topHeight}px`,this.sysinfo);
				return {
					'height':`${this.sysinfo.safeArea.height - 44 - this.topHeight}px`
				}
			},
			winHeight(){
				return {
					'height':`${this.sysinfo.safeArea.height}px`
				}
			},
			navHeight(){
				return {
					'height':`${this.sysinfo.safeArea.top + 44}px`
				}
			},
			...mapState(['sysinfo'])
		},
		onReady() {
			// this.winHeight = `height:${this.sysinfo.safeArea.height}px`;
			// this.navHeight = `height:${this.sysinfo.safeArea.top + 44}px`;
			// #ifdef APP-NVUE
			let queryTabSize = uni.createSelectorQuery().in(this);
			// queryTabSize.select('#top').boundingClientRect();
			queryTabSize.exec(rects => {
				console.log('rects',rects);
				rects.forEach((rect) => {
					this.topHeight = rect.height;
				})
			});
			// #endif
			
			// #ifdef H5
			// uni.createSelectorQuery().in(this).select('#top').boundingClientRect( (res) => {
			// 	this.topHeight = res.height;
			// }).exec();
			// #endif
		},
		onBackPress(event) {
			console.log('event--quota', event, this.currentTabComponent)
			// uni.navigateBack({
			// 	delta: 1
			// })
			if (this.currentTabComponent === 'purchaseReceive') {
				uni.navigateTo({
					url: `/pages/purchase/purchase-apply`
				});
				this.currentTabComponent = 'purchaseMain'
				return false
			} else {
				uni.switchTab({
					url: "pages/purchase/purchase"
				})
			}
			return false
		},
		onLoad(option) {
			this.sourceType = option.sourceType
			if(option.sourceType === 'myPurchase'){
				this.findById(option.id)
			}else{
				this.orderItem = {
					// ...this.orderItem,
					...JSON.parse(option.order)
				}
				this.demandType = this.orderItem.demandType
			}
		},
		created() {
			this.sourceType === 'purchase' && this.getDetail()
		},
		methods: {
			// changeUUid(res){
			// 	if(res.data.length > 0){
			// 		this.detail.fileBizId = res.data[0].bizId
			// 	}else{
			// 		this.generateUUID()
			// 	}
			// },
			// 获取生成文件id
			async generateUUID(){
				const res = await generateUUID()
				this.detail.fileBizId = res.data
			},
			async findById(id){
				const res = await findById(id)
				this.detail = {
					procInstId: null,
					procUnitId: "APPLY",
					processAction: "save",
					processDefinitionKey: "wantGoods",
					'shuntTypeName': ' ',
					'shuntName': ' ',
					'channelTypeName': '',
					 isPcjName: res.data.isPcj - 0 ===0 ? '否': '是',
					 shuntTypeName: res.data.shuntChannelsTypeTextView,
					...res.data,
					 shuntDealerName: res.data.shuntDealer,
					 fileBizId: res.data.id,
					 bizCode: 'wantGoods',
					 demandTypeTextView: res.data.demandType == 'ZDZG' ? '终端直配' : '',
				}
				this.getChannelType()
				// res.data.demandType == 'ZDZG' && this.getTerminalRobot()
			},
			async getPledgeQuantity(){
			      const { billCustCode, billCustomer,wantGoodsDetailList } = this.detail
			      const params = {
			        customerCode: billCustCode,
			        customerName: billCustomer,
			        productCode: wantGoodsDetailList[0].productCode,
			        productName: wantGoodsDetailList[0].productDesc,
			      }
			      try {
			        const {data} = await queryPledgeQuantity(params)
			        this.releaseNum = data.quantity || 0
			      } catch (error) {
			        
			      }
			},
			async getChannelType(){
				const params = {
					salePlan: this.detail.planType,
					productCode: this.detail.wantGoodsDetailList?.[0]?.productCode || this.orderItem.productCode,
					customerCode: this.detail.customerCode
				}
				
				// 只有终端要货时才添加isTerminal参数
				if (this.demandType == 2) {
					params.isTerminal = true
				}
				
				const res = await getChannelType(params)
				this.channelTypeArr = res.data
				// if (this.detail.acceptUnitType =='V013'|| this .detail.acceptUnitType =='V015'){
				// 	this.channelTypeArr = [{ value: 'T', name: '团购渠道' }]
				// }
				if (this.detail.acceptUnitType =='v014'){
					this.channelTypeArr = [{ value: 'Z', name: '终端团购渠道' }]
					this.detail.channelsType =  this.channelTypeArr[0].value
					this.detail.channelTypeName =  this.channelTypeArr[0].name
				}
				if (!this.channelTypeArr.length) {
					this.channelTypeArr = [{ value: 'S', name: '社会化渠道' }]
					this.detail.channelsType =  this.channelTypeArr[0].value
					this.detail.channelTypeName =  this.channelTypeArr[0].name
				  }
			},
			async getDetail(){
				const res = await initAppWantGoods(this.orderItem)
				for(let k in res.data){res.data[k] = res.data[k]===null?'':res.data[k]}
				// sourceType区分货权转移
				this.detail = {
					'shuntTypeName': ' ',
					'shuntName': ' ',
					'channelTypeName': '',
					...res.data,
					 isPcj:0, 
					 isPcjName:'否',
					 significance: 'normal',
					 significanceTextView: '正常',
					 sourceType:1,
					 billStatus: "E001",
					 status: 0,
					 isShunt: '0',
					 fileBizId: null,
					 bizCode: 'wantGoods',
					 demandType: this.demandType ==1 ? '' : 'ZDZG',
					 demandTypeTextView: this.demandType ==1 ? '' : '终端直配',
					 terminalId: '',
					 terminalName: '',
					 terminalIdTextView: '',
					 receiveUnitName: res.data.demandType == 'ZDZG' ? '' : res.data.receiveUnitName,
				}
				this.getChannelType()
				this.getPledgeQuantity()
				this.sourceType === 'purchase' && this.generateUUID()
				// this.demandType == 2 && this.getTerminalRobot()
			},
			// 绑定终端
			getTerminalRobot(){
			  const params = {
				dealerId: this.detail.customerCode,
				inventoryCode: this.detail.brand,
				channelType: this.detail.channelsType, // 添加渠道类型参数
				page: {
					current: 1,
					size: 5000
				}
			  }
			  
			  queryDirectStore(params).then(res => {
				this.terminalRobotArrs = res.data.data.records
			  })
			},
			changeComponent(com) {
				this.currentTabComponent = com;
			},
			submit() {
				console.log('submit')
			}
		}

	}
</script>

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

	.apply-history {
		width: 750rpx;
		flex: 1;
		background: $background-color-1;
	}

	.apply-history-wrapper {
		margin-top: 18rpx;
	}

	.top {
		position: relative;
		background: $background-color-1;
	}

	.steps {
		flex: 1;
		flex-direction: column;
		margin: 28rpx 0 32rpx;
	}

	.steps__row-text-container {
		align-items: flex-end;
		flex-direction: row;
	}

	.steps__row-text {
		flex: 1;
		flex-direction: column;
	}

	.steps__row-title {
		font-size: 12px;
		line-height: 16px;
		text-align: center;
		color: $text-base-color;
	}

	.steps__row-container {
		margin-bottom: 16rpx;
	}

	.steps__row-line-item {
		flex: 1;
		height: 14px;
		line-height: 14px;
		align-items: center;
		justify-content: center;
	}

	.steps__row-line--before {
		transform: translateX(-1px);
	}

	.steps__row-line {
		flex: 1;
		height: 1px;
		background-color: #999;
	}

	.icon-dot {
		width: 16rpx;
		height: 16rpx;
		background: #E5E5E5;
		border-radius: 50%;
	}

	.icon-dot-active {
		background: #ff1d32;
	}

	.steps__row-line--after {
		transform: translateX(1px);
	}

	.steps__row-line {
		flex: 1;
		height: 1px;
		background-color: #e5e5e5;
	}

	.steps__row-line--active {
		background: #ff3e61;
		border-radius: 1px;
	}

	.steps__row-circle {
		background: #E5E5E5;
	}

	.steps__row-line--hide {
		background-color: transparent;
	}
</style>
