<template>
	<view class="orderDetail-digitalShel flex flex_column">
		<view class="contHead" :style="{background:state!= 'error'&&state!= 'AUDIT_REJECT'&&state!='CANCEL'&&state!='WAIT_PAY' ? '#066cff':(state=='WAIT_PAY'?'#f45c03':'#e61100'),color:'#fff'}">
			<view class="statusH">
				<view class="flex flex_column align_center">
					<view class="status-row">
						<u-icon :name="statusIcon" size="42" color="#fff"> 
						</u-icon>
						<text>{{statusText}}</text>
					</view>
					<view v-if="info.billStatus=='WAIT_PAY'" class="messageText">
						请尽快支付，
						<u-count-down separator="zh" :separator-size="24" bg-color="none" color="#ffff7f" separator-color="#ffff7f" :timestamp="info.timestamp" :show-days="false" :show-hours="false" @end="countDownEnd()"></u-count-down>
						后订单将自动取消。
					</view>
					<view v-else class="messageText"><text>{{statusMessage}}</text></view>
				</view>
			</view>
		</view>
		<view class="order-body">
			<view class="info partList" v-if="partList.length" style="max-height: 50vh;overflow: auto;">
				<view class="infoList">
					<view class="title">
						产品列表
					</view>
					<view v-if="info">
						共<text class="cText">{{info.totalCategory}}</text>款
					</view>
				</view>
				<view v-for="(item,dix) in partList" :key="item.id" class="item-list-box">
					<view class="item-list flex">
						<view style="height: 160rpx;width: 160rpx;">
							<u-image :src="item.product.images ? item.product.images+'?x-oss-process=image/resize,p_50':'/static/def_imgs.png'" border-radius="16" width="160" height="160" bg-color="#EBEBEB" ></u-image>
						</view>
						<view>
							<view class="item-name">
							  <text>{{item.product.productName}}</text>
							</view>
							<view class="item-nums" v-if="item.product&&item.product.code">
								<text>{{item.product.code}}</text>
							</view>
							<view class="item-nums" v-if="item.product&&item.product.origCode">
								<text style="color: #00aaff;">{{item.product.origCode}}</text>
							</view>
							<view class="item-head">
								<view class="flex align_center">
									<view class="price-txt">￥<text>{{item.priceStr[0]}}</text>.{{item.priceStr[1]}}</view>
									<view class="flex align_center rebate-tag" v-if="item.promoProductType=='TICKET_PRODUCT'">
										返<text>{{item.resultValue}}</text>元
									</view>
									<view class="flex align_center rebate-tag" v-if="item.promoProductType=='REGULAR_PRODUCT'">
										买{{item.conditionValue}}赠{{item.resultValue}}
									</view>
									<view class="flex align_center tejia-tag" v-if="item.promoProductType=='SPECIAL_PRODUCT'">
										特价<text>￥{{item.priceOrig}}</text>
									</view>
								</view>
								<view>
									X <text class="cText">{{item.qty}}</text>{{item.product&&item.product.unit||''}}
								</view>
							</view>
						</view>
					</view>
					<!-- 赠品 -->
					<view class="item-list flex gift-box" v-if="item.giftObj">
						<view style="height: 120rpx;width: 120rpx;margin-left: 40rpx;">
							<u-image :src="item.giftObj.product.images ? item.giftObj.product.images+'?x-oss-process=image/resize,p_50':'/static/def_imgs.png'" border-radius="16" width="120" height="120" bg-color="#EBEBEB" ></u-image>
						</view>
						<view>
							<view class="item-name flex align_center">
							  <view class="flex align_center rebate-tag">
							  	赠品
							  </view>
							  <text class="ellipsis-one">{{item.giftObj.product.productName}}</text>
							</view>
							<view class="item-nums ellipsis-one" v-if="item.giftObj.product&&item.giftObj.product.code">
								<text>{{item.giftObj.product.code}}</text>
							</view>
							<view class="item-nums ellipsis-one" v-if="item.giftObj.product&&item.giftObj.product.origCode">
								<text style="color: #666;">{{item.giftObj.product.origCode}}</text>
							</view>
							<view class="item-head">
								<view class="flex align_center"></view>
								<view>
									X <text class="cText">{{item.giftObj.qty}}</text>{{item.giftObj.product&&item.giftObj.product.unit||''}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 分页 -->
				<view class="product-pages" v-if="totalPages>1">
					<uni-pages-nav :totalPages="totalPages" :showShadow="false" :currentPage="pageNo" @pagechanged="getRow"></uni-pages-nav>
				</view>
			</view>
			<view class="info" v-if="info">
				<view class="infoList">
					<text>总金额</text>
					<view class="price-txt">￥<text>{{Number(info.totalAmount).toFixed(2)}}</text></view>
				</view>
				<view class="infoList gray-text" v-if="info.totalSpecialGiveAmount">
					<text>总优惠</text>
					<text class="cText">￥{{Number(info.totalSpecialGiveAmount).toFixed(2)}}</text>
				</view>
				<view class="infoList gray-text" v-if="info.totalTicketGiveAmount">
					<text>代金券</text>
					<text class="cText">￥{{Number(info.totalTicketGiveAmount).toFixed(2)}}</text>
				</view>
			</view>
			<view class="info" v-if="!hasPay && info">
				<view class="infoList">
					<view class="title">订单信息</view>
					<view class="statu"></view>
				</view>
				<view class="infoList dju">
					<text>订单编号</text>
					<text>{{info.purchaseNo||'--'}}</text>
				</view>
				<view class="infoList">
					<text>下单时间</text>
					<text>{{info.purchaseDate||'--'}}</text>
				</view>
				<view class="infoList">
					<text>下单人员</text>
					<text>{{info.purchaserName || '--'}}</text>
				</view>
			</view>
			<!-- 线上支付 显示 -->
			<view class="info" v-if="hasPay && info">
				<u-read-more ref="uReadMore" :text-indent="0" toggle close-text="更多信息" :show-height="460">
					<view class="infoList">
						<view class="title">订单信息</view>
						<view class="statu"></view>
					</view>
					<view class="infoList dju">
						<text>订单编号</text>
						<text>{{info.purchaseNo||'--'}}</text>
					</view>
					<view class="infoList">
						<text>下单时间</text>
						<text>{{info.purchaseDate||'--'}}</text>
					</view>
					<view class="infoList">
						<text>下单人员</text>
						<text>{{info.purchaserName || '--'}}</text>
					</view>
					<view class="infoList" v-if="info&&info.billStatus != 'WAIT_AUDIT'&&info.billStatus != 'WAIT_PAY'&&info.billStatus != 'CANCEL'">
						<text>审核时间</text>
						<text>{{info.auditDate||'--'}}</text>
					</view>
					<view class="infoList" v-if="isPayOk">
						<text>支付方式</text>
						<text>{{info.payInfo.payWay=='WXPAY_ONLINE_XCX'?'微信支付':'--'}}</text>
					</view>
					<view class="infoList" v-if="isPayOk">
						<text>支付时间</text>
						<text>{{info.payInfo.payDate||'--'}}</text>
					</view>
					<view class="infoList" v-if="info&&info.billStatus == 'CANCEL'">
						<text>取消时间</text>
						<text>{{info.cancelDate ||'--'}}</text>
					</view>
					<view class="infoList" v-if="info&&(info.billStatus == 'CANCEL'||info.billStatus == 'AUDIT_REJECT')&&isPayOk">
						<text>退款方式</text>
						<text>原支付返回</text>
					</view>
					<view class="infoList" v-if="info&&(info.billStatus == 'CANCEL'||info.billStatus == 'AUDIT_REJECT')&&isPayOk">
						<text>退款时间</text>
						<text>{{info.payInfo.refundDate ||'--'}}</text>
					</view>
					<view class="infoList" v-if="info&&(info.billStatus == 'CANCEL'||info.billStatus == 'AUDIT_REJECT')&&isPayOk">
						<text>退款状态</text>
						<text>{{info.payInfo.refundState=='FINISH'?'已退款':(info.payInfo.refundState=='WAIT'?'退款中':'退款失败')}}</text>
					</view>
					<view class="infoList" v-if="shelfInfo">
						<text>配送汽配商</text>
						<text>{{shelfInfo.dealerName}}</text>
					</view>
				</u-read-more>
			</view>
		</view>
		<view v-if="info&&info.billStatus == 'WAIT_AUDIT'||info.billStatus == 'WAIT_PAY'||info.billStatus == 'WAIT_RECEIVE'" style="background-color: #fff;">
			<view class="footer flex align_center justify_center">
				<u-button style="margin-left: 10px;" v-if="info.billStatus == 'WAIT_AUDIT'||info.billStatus == 'WAIT_PAY'" size="medium" shape="round" type="default" plain @click="cancelOrder(info)">取消订单</u-button>
				<u-button style="margin-left: 10px;" v-if="info.billStatus == 'WAIT_PAY'" size="medium" shape="round" type="error" plain @click="payOrder(info)">立即支付</u-button>
				<!-- <u-button style="margin-left: 10px;" v-if="info.billStatus == 'FINISH'" size="medium" shape="round" type="error" plain @click="buyAgain(info)">再次购买</u-button> -->
				<u-button style="margin-left: 10px;" v-if="info.billStatus == 'WAIT_RECEIVE'" size="medium" shape="round" type="error" plain @click="receiveOrder(info)">确认收货</u-button>
			</view>
			<view :style="{height:safeAreaBottom+'px'}"></view>
		</view>
		<!-- 付款弹框 -->
		<payModal :showPopu="showPopu" :payInfo="info" :payData="payData" @close="showPopu=false" @payComplete="payComplete"></payModal> 
	</view>
</template>

<script>
	import payModal from '../components/payModal.vue'
	import { purchaseQueryDetailPage,purchaseQueryPage,purchaseCancel,purchaseReceive,purchasePay } from '@/api/purchase.js'
	import moment from 'moment'
	export default {
	   name: 'procureDetailOrder',
	   components:{
	   	payModal
	   },
	   data() {
		   return {
			   loading: false,
			   info: null,
			   statusText: '',
			   statusIcon: '', // 结算状态icon
			   statusMessage: '请耐心等待汽配经销商进行配送',
			   partList: [], // 配件列表
			   state: 'success',
			   pageNo:1,
			   pageSize: 30,
			   total: 0,
			   purchaseSn: null,
			   showPopu: false,
			   safeAreaBottom: 0, // 底部安全区域高度
			   payData: null
		   }
	   },
	   onLoad(option) { 
		   this.safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
		   uni.setNavigationBarTitle({
		   	title: '采购订单详情'
		   })
		   // 查明细
		   this.purchaseSn = option.purchaseSn
		   this.getDetail()
		   // 获取明细列表
		   this.getDetailList()
	   },
	   onUnload() {
			this.$store.state.vuex_tempOrderData = null
	   },
	   computed: {
		   totalPages(){
			   return Math.ceil(this.total / this.pageSize)
		   },
		   // 货架经销商信息
		   shelfInfo(){
				return this.$store.state.vuex_storeShelf
		   },
		   //是否有支付信息
		   hasPay(){
				return this.info&&this.info.payOnlineFlag==1&&this.info.payInfo
		   },
		   //是否已付款
		   isPayOk(){
			   return this.hasPay && this.info.payInfo.payState=='FINISH'
		   },
	   },
	   methods: {
		 pageInit(data){
			 // 计算待付款剩余倒计时
			 if(data.billStatus== 'WAIT_PAY'){
			 	data.timestamp = (new Date(data.createDate.replace(/-/g,'/')).getTime() + 1800000 - new Date().getTime())/1000
			 }
			 data.payOk = data.payOnlineFlag==1&&data.payInfo&&data.payInfo.payState=='FINISH'
			 this.info = data
			 this.state = data.billStatus
			 const stateText = {'WAIT_AUDIT':'待审核','WAIT_PAY':'待付款','AUDIT_REJECT':'审核不通过','WAIT_OUT_WAREHOUSE':'待收货','WAIT_RECEIVE':'待收货','FINISH':'已完结','CANCEL':'已取消'}
			 this.statusText = stateText[this.state]
			 this.statusIcon = this.state == 'FINISH' ? 'checkmark-circle' : ((this.state == 'AUDIT_REJECT'||this.state == 'CANCEL')?'close-circle':'hourglass')
			 this.statusMessage = this.state == 'WAIT_OUT_WAREHOUSE'||this.state == 'WAIT_RECEIVE' ? '请耐心等待汽配经销商进行配送' : ''
			 // 更改标题栏背景色
			 uni.setNavigationBarColor({
			 	frontColor: '#ffffff',
			 	backgroundColor: this.state!= 'error'&&this.state!= 'AUDIT_REJECT'&&this.state!= 'CANCEL'&&this.state!= 'WAIT_PAY' ? '#066cff':(this.state=='WAIT_PAY'?'#f45c03':'#e61100'),
			 })
		 },
		 // 实时查询详情
		 getDetail(){
			purchaseQueryPage({pageNo:1,pageSize:1,purchaseSn: this.purchaseSn}).then(res => {
				const data = res.data ? res.data.list[0] : null
				if(data){
					data.billStatus = data.billStatus == 'WAIT_AUDIT'&&data.payOnlineFlag==1&&data.payInfo&&data.payInfo.payState=='WAIT'?'WAIT_PAY':data.billStatus
					this.pageInit(data)
				}
			}) 
		 },
		 // 下一页
		 getRow(pageNo){
			this.pageNo = pageNo
			this.getDetailList()
		 },
		 getDetailList(){
		   uni.showLoading({
		   	title: '加载中'
		   })
		   purchaseQueryDetailPage({purchaseSn: this.purchaseSn,pageNo:this.pageNo,pageSize:this.pageSize}).then(res => {
			    uni.hideLoading()
				if(res.status == 200){
					this.partList = res.data ? res.data.list : []
					// 是否有赠品
					const giftList = this.partList.filter(item => item.promoProductType == 'GIFT_PRODUCT')
					// 正品
					this.partList = this.partList.filter(item => item.promoProductType !== 'GIFT_PRODUCT')
					this.partList.map(item=>{
					  // 关联赠品
					  item.giftObj = giftList.find(gift => gift.purchaseDetailParentSn  == item.purchaseDetailSn)
					  item.priceStr = Number(item.price).toFixed(2).toString().split('.')
					})
					this.total = res.data ? res.data.count : 0
				}
		   }) 
		 },
		 message(title){
		 	uni.showToast({
		 		icon:'none',
		 		title: title,
				duration: 3000
		 	})
		 },
		 // 取消订单
		 cancelOrder(item){
		 	let _this = this
		 	uni.showModal({
		 		title: '提示',
		 		content: !item.payOk ? '确定取消订单吗？':'取消后订单金额将于1-3个工作日到账（原路返回）？',
		 		success: function (res) {
		 			if (res.confirm) {
		 				purchaseCancel({purchaseSn:_this.purchaseSn}).then(res => {
		 					if (res.status == 200) {
		 						_this.message('取消成功')
								item.payInfo = null
								uni.$emit('refreshPurcaOrder',item,'CANCEL')
								setTimeout(()=>{
									uni.navigateBack()
								},3000)
		 					} else {
		 						_this.message(res.message)
		 					}
		 				})
		 			}
		 		}
		 	});
		 },
		 // 倒计时结束，取消订单刷新页面
		 countDownEnd(){
			 this.showPopu = false
			 const _this = this
			 uni.showModal({
			 	title: '提示',
			 	content: '订单超过30分钟已自动取消',
				showCancel:false,
				confirmText:'知道了',
			 	success: function (res) {
			 		_this.state = 'CANCEL'
			 		_this.info.billStatus = 'CANCEL'
					_this.info.payInfo = null
			 		_this.statusText = '已取消'
			 		_this.statusIcon = 'close-circle'
			 		_this.statusMessage = '订单超过30分钟已自动取消'
			 		_this.info.cancelDate = moment().format('YYYY-MM-DD hh:mm:ss')
					uni.$emit('refreshPurcaOrder',_this.info,'CANCEL')
			 		// 更改标题栏背景色
			 		uni.setNavigationBarColor({
			 			frontColor: '#ffffff',
			 			backgroundColor: '#e61100',
			 		}) 
			 	}
			 });
		 },
		 // 立即支付
		 payOrder(item){
			uni.showLoading({
				title: '加载中...'
			})
			purchasePay({
				bizSn:item.purchaseSn,
				bizNo:item.purchaseNo,
				bizType:'PURCHASE',
				payUserOpenId: this.$store.state.vuex_openid || uni.getStorageSync('openid')
			}).then(res=>{
				this.showPopu = true
				this.payData = res.data?res.data.payRequestRest:null
				uni.hideLoading()
			})
		 },
		 // 付款成功,isOk: false 取消支付或支付失败，true 支付完成
		 payComplete(item,isOk){
		 	this.showPopu = false
		 	if(isOk){
				this.message('支付成功')
		 		uni.$emit('refreshPurcaOrder',item,'WAIT_AUDIT')
				setTimeout(()=>{
					uni.navigateBack()
				},3000)
		 	}
		 },
		 // 再次购买
		 buyAgain(item){
		 },
		 // 确认收货
		 receiveOrder(item){
		 	let _this = this
		 	uni.showModal({
		 		title: '提示',
		 		content: '确定收货吗？',
		 		success: function (res) {
		 			if (res.confirm) {
		 				purchaseReceive({purchaseSn:_this.purchaseSn}).then(res => {
		 					if (res.status == 200) {
		 						_this.message('收货成功')
								uni.$emit('refreshPurcaOrder',item,'FINISH')
		 						setTimeout(()=>{
									uni.navigateBack()
								},3000)
		 					} else {
		 						_this.message(res.message)
		 					}
		 				})
		 			}
		 		}
		 	});
		 },
	   }
	}
</script>

<style lang="less">
	page{
		height: 100%;
	}
	.orderDetail-digitalShel{
		height: 100%;
		.redText{
			color: #FB1E1E;
			margin: 0 10rpx;
		}
		.cText{
			color: #666;
			margin: 0 6rpx;
			font-size: 14px;
		}
		.gray-text{
			text{
				font-size: 14px;
				color: #999;
			}
		}
		.order-body{
			flex-grow: 1;
			overflow: auto;
			.partList{
				margin-top: 20rpx;
			}
		}
		.contHead {
			.statusH{
				> view{
					padding: 10upx 12%;
					font-size: 34upx;
				}
				.status-row{
					font-size: 42upx;
					text{
						margin-left: 10rpx;
					}
				}
				.messageText{
					font-size: 28upx;
					text-align: center;
					text{
						color: #f3e781;
					}
					padding: 20rpx 0;
				}
			}
		}
		.price-txt{
			color: red;
			display: flex;
			align-items: baseline;
			font-size: 12px;
			text{
				font-size: 32rpx;
			}
		}
		.info{
			background-color: #FFFFFF;
			padding: 10rpx 30upx;
			font-size: 32rpx;
			margin-bottom: 20rpx;
			.infoList{
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 2rpx solid #f2f2f2;
				&:last-child{
					border: none;
				}
				.title{
					font-weight: bold;
					> text{
						color: #ff9808;
						font-size: 24upx;
					}
				}
				> text{
					&:first-child{
						color: #666E75;
					}
				}
			}
			.item-list-box{
				border-bottom: 2rpx solid #f2f2f2;
				&:last-child{
					border: none;
				}
			}
			.item-list{
				padding: 20rpx 0;
				> view{
					&:first-child{
						margin-right: 20rpx;
						position: relative;
						overflow: hidden;
						width: 160rpx;
						height: 160rpx;
						border-radius: 6px;
						border: 1px solid #eee;
					}
					&:last-child{
						flex-grow: 1;
						width: 60%;
					}
				}
				.item-name{
					word-wrap: break-word;
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
				}
				.item-nums{
					text{
						font-size: 28rpx;
						color: #666;
					}
				}
				.item-head{
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: #666;
					margin-top: 5px;
					> view:last-child{
						font-size: 24rpx;
						text{
							margin: 0 10rpx;
							font-size: 28rpx;
						}
					}
				}
				.rebate-tag{
					background: #ffe7df;
					color: #E91E63;
					padding: 2px 5px;
					font-size: 10px;
					border-radius: 3px;
					margin-left: 6px;
				}
				.tejia-tag{
					color: #E91E63;
					margin-left: 6px;
					font-size: 12px;
					text{
						font-size: 12px;
						color: #999;
						margin-left: 5px;
						text-decoration: line-through;
					}
				}
			}
		}
		.gift-box.item-list{
			.item-name{
				color: #666;
				font-size: 12px;
				font-weight: normal;
			}
			.item-nums{
				text{
					color: #666;
					font-size: 12px;
				}
			}
			.rebate-tag{
				margin-left: 0;
				margin-right: 5px;
			}
			.ellipsis-one{
				flex-grow: 1;
				width:80%;
			}
		}
		.footer{
			padding: 20upx;
			background: #FFFFFF;
		}
	}
	
</style>
