<template>
	<view class="flexTop">
		<view class="content">
			<view v-for="(item,index) in goodList" :key="index">
				<view class="box">
					<view class="flex">
						<text class="text1">订单编号：{{item.id}}</text>
						<text
							class="text2">{{item.status=='SUBMITTED'?'等待付款':item.status=='PAID'?'等待发货':item.status=='DELIVERED'?'等待收货':item.status=='FINISHED'?'交易成功':item.status=='CANCELED'||item.status=='CLOSED'?'交易关闭':item.status=='WAITING_FOR_REFUND'?'审核中':item.status=='REFUNDING'?'退款处理中':item.status=='REFUND_REJECTED'?'驳回':item.status=='REFUND_FINISHED'?'退款完成':''}}</text>
					</view>
					<view class="flex-column" v-for="(item1,index1) in item.items" :key="index1"
						@click="gotoStatu(item)">
						<view>
							<image :src="item1.colorPic" class="img"></image>
						</view>
						<view class="flex-d1">
							<view class="flex-w">
								<text class="text1">{{item1.silkName}}</text>
								<text class="text2">x{{item1.length}}米</text>
							</view>
							<text class="text3">{{item1.pricePreMeter}}元/米</text>
							<text class="text3">¥{{item1.price}}</text>
						</view>
					</view>
					<view class="flex1">
						<text class="text1">{{status==1?'应付金额：':'实付金额：'}}¥{{item.actual}}</text>
						<view class="view1">
							<view style="margin: 0 5rpx;"
								v-if="item.status=='PAID'||item.status=='DELIVERED'||item.status=='FINISHED'">
								<up-button size="small" :plain="true" :hairline="true"
									@click="afterSale(item)" color="#909399">售后</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='PAID'||item.status=='DELIVERED'">
								<up-button size="small" :plain="true" :hairline="true"
									@click="receiveGoods(item)" color="#909399">确认收货</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='SUBMITTED'">
								<up-button size="small" :plain="true" :hairline="true"
									@click="cancelOrder(item)" color="#909399">取消订单</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='SUBMITTED'">
								<up-button type="error" size="small" :plain="true" :hairline="true"
									@click="gotoPuy(item)" color="#909399">立即付款</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='CANCELED'||item.status=='CLOSED'">
								<up-button size="small" :plain="true" :hairline="true"
									@click="delectOrder(item)" color="#f56c6c">删除订单</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='WAITING_FOR_REFUND'||item.status=='REFUNDING'||item.status=='REFUND_REJECTED'||item.status=='REFUND_FINISHED'">
								<up-button size="small" :plain="true" :hairline="true" @click="gotocustm()" color="#909399">联系客服</up-button>
							</view>
							<view style="margin: 0 5rpx;" v-if="item.status=='WAITING_FOR_REFUND'">
								<up-button size="small" type="error" :plain="true" :hairline="true" @click="cancelSale(item)" color="#909399">取消售后</up-button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	<!-- 申请售后弹窗 -->
	<view>
		<up-popup :show="popupShow" mode="bottom" :round="10" @close="popupShow=false" @open="open" closeable>
			<view class="cont">
				<view style="margin-top: 20rpx;text-align: center;font-size: 32rpx;">
					<text>选择面料</text>
				</view>
				<view class="flexpopup">
					<view class="content">
						<view v-for="(item,index) in afterSaleItem.items" :key="index">
							<view>
								<checkbox-group @change="handleChange(item)">
									<label class="flex-column">
										<view>
											<image :src="item.colorPic" class="img"></image>
										</view>
										<view class="flex-d">
											<view class="flex-w">
												<text class="text1">{{item.silkName}}</text>
											</view>
											<text class="text3">{{item.color}} {{item.length}}米</text>
											<text class="text3">实付价格:¥{{item.price}}</text>
										</view>
										<checkbox :checked="item.checked" />
									</label>
								</checkbox-group>
							</view>
						</view>
					</view>
					<view style="margin-top: 30rpx;" @click="gotoAfterSale">
						<up-button shape="circle" color="linear-gradient(to right,#13b267,#258010)">下一步</up-button>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { onShow } from '@dcloudio/uni-app';
	import { deleteAction, getAction, postAction } from '../http';

	const emit = defineEmits(['statueNow', 'cancelOrder', 'reset'])
	const status = ref(0)
	const popupShow = ref(false)
	const afterSaleItem = ref({})
	const goodList = ref([])//全部数据
	// const dataList=ref([])//展示
	onShow(() => {

	})
	const cancelOrder = (item : any) => {
		emit('cancelOrder', item)
	}
	const gotoPuy = (item : any) => {
		postAction('/order/pay', { orderId: item.id }, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }).then((res : any) => {
			if (res.code === 200) {
				let { nonceStr, prepayId, timeStamp, signature } = res.data
				prepayId = JSON.parse(prepayId).prepay_id
				let package1 = 'prepay_id=' + prepayId
				uni.requestPayment({
					provider: 'wxpay',// 支付类型微信支付wxpay/支付宝支付alipay
					orderInfo: {
						"appid": "wxc385500b1df207b8",  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
						"noncestr": nonceStr, // 随机字符串
						"package": package1,        // 固定值
						"partnerid": "1680435317",      // 微信支付商户号
						"prepayid": prepayId, // 统一下单订单号 
						"timestamp": timeStamp,        // 时间戳（单位：秒）
						"sign": signature // 签名，这里用的 MD5/RSA 签名
					},
					timeStamp: timeStamp,        // 时间戳（单位：秒）
					nonceStr: nonceStr, // 随机字符串
					package: package1,        // 固定值
					signType: "RSA", // 签名，这里用的 MD5/RSA 签名
					paySign: signature,
					success: (res) => {
						console.log('支付成功', res)
						uni.showToast({
							title: '支付成功'
						})
						getAction('/order/getOrderById', { orderId: item.id }).then((res : any) => {
							if (res.code === 200) {
								uni.setStorageSync('orderGoods', JSON.stringify(res.data))
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/orderFlow/Order/orderDetails'
									})
								}, 100)
							} else {
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}, 100)
							}
						})
					},
					fail: (result) => {
						uni.showToast({
							title: '支付失败',
							icon: 'error'
						})
					}
				})
			}
		})
	}
	const gotoStatu = (item : any) => {
		if(item.status=='WAITING_FOR_REFUND'||item.status=='REFUNDING'||item.status=='REFUND_REJECTED'||item.status=='REFUND_FINISHED'){
			uni.setStorageSync('orderGoods', JSON.stringify(item))
			uni.navigateTo({
				url: '/pages/orderFlow/afterSale/afterSale'
			})
		}else if (item.status == 'SUBMITTED') {
			uni.setStorageSync('orderGoods', JSON.stringify(item))
			uni.navigateTo({
				url: '/pages/orderFlow/Order/orderDetails?type=' + 1
			})
		} else {
			uni.setStorageSync('orderGoods', JSON.stringify(item))
			uni.navigateTo({
				url: '/pages/orderFlow/Order/orderDetails'
			})
		}
	}
	const changeStuta = (data : any, list : any) => {
		status.value = data
		setTimeout(() => {
			emit('statueNow', data)
			goodList.value = list
		}, 300)
	}
	defineExpose({
		changeStuta
	})
	const delectOrder = (item : any) => {
		uni.showModal({
			content: '是否删除该订单？',
			success: function (res) {
				if (res.confirm) {
				deleteAction(`/order/delete${item.id}`).then((res:any)=>{
					if(res.code===200){
						uni.showToast({
							icon:'success',
							title:'删除成功！'
						})
						goodList.value=goodList.value.filter(l=>l.id!=item.id)
					}else{
						uni.showToast({
							icon:'error',
							title:'删除失败！'
						})
					}
				})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	}
	const receiveGoods = (item : any) => {
		uni.showModal({
			content: '是否确认收货？',
			success: function (res) {
				if (res.confirm) {
					//拉起确认收货组件
					  wx.openBusinessView({
					    businessType: 'weappOrderConfirm',
					    extraData: {
					      merchant_id: '1680435317',
					      merchant_trade_no: item.id,
					      transaction_id: item.wechatPayBill
					    },
					    success() {
					     postAction('/order/received', { orderId: item.id }, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }).then((res : any) => {
					     	if (res.code === 200) {
					     		uni.showToast({
					     			title: '收货完成！',
					     			icon: 'success',
					     		})
					     		emit('reset', 1)
					     	}
					     })
					    },
					    fail(err) {
							console.log(err);
					      uni.showToast({
					      	title:'确认失败！',
							icon:'none',
					      })
					    },
					    complete() {
					      //dosomething
					    }
					  });
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	}
	const afterSale = (item : any) => {
		item.items.forEach((l : any) => {
			l.checked = false
		})
		afterSaleItem.value = item
		popupShow.value = true
	}
	const open = () => {
		popupShow.value = true
	}
	const handleChange = (item : any) => {
		item.checked = !item.checked
	}
	const gotoAfterSale = () => {
		let arr = afterSaleItem.value.items.filter(l => l.checked);
		if (arr.length) {
			popupShow.value=false
			uni.navigateTo({
				url: '/pages/orderFlow/applicationRefund/applicationRefund?item=' + JSON.stringify(arr)+'&orderId='+ afterSaleItem.value.id
			})
		} else {
			uni.showToast({
				title: '请选择退款订单!',
				icon: 'none'
			})
		}
	}
	const gotocustm=()=>{
		uni.reLaunch({
			url:'/pages/minPackage/customerService'
		})
	}
	const cancelSale=(item:any)=>{
		uni.showModal({
			content: '是否确认取消？',
			success: function (res) {
				if (res.confirm) {
					postAction('/refund/cancelByOrderId',{orderId:item.id}, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }).then((res:any)=>{
						if(res.code===200){
							uni.showToast({
								title:'取消成功！',
								icon:'success'
							})
							emit('reset', 1)
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	}
</script>

<style lang="scss" scoped>
	.flex1 {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		border-top: 1rpx solid #eeeeee;
		border-bottom: 1rpx solid #eeeeee;

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

		.text1 {
			color: #999999;
		}
	}

	.flex {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		border-bottom: 1rpx solid #eeeeee;
		margin-bottom: 20rpx;

		.text1 {
			color: #999999;
		}

		.text2 {
			color: red;
		}
	}

	.box {
		padding: 10rpx 0;
	}

	.flex-column {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 20rpx;
	}

	.flex-d {
		width: calc(100% - 280rpx);
		height: 170rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.text3 {
			color: #999999;
		}
	}
	.flex-d1 {
		width: calc(100% - 220rpx);
		height: 170rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	
		.text3 {
			color: #999999;
		}
	}

	.flex-w {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-left: 1%;

		.text1 {
			font-size: 36rpx;
			padding: 2rpx 0;
		}

		.text2 {
			font-size: 34rpx;
			color: #1abc9c;
			padding: 2rpx 0;
		}
	}

	.img {
		width: 190rpx;
		height: 190rpx;
		border-radius: 20rpx;
	}

	.flexTop {
		display: flex;
		flex-direction: column;
		height: 93vh;
		overflow: hidden;
	}

	.flexpopup {
		display: flex;
		flex-direction: column;
		max-height: 70vh;
		overflow: hidden;
	}

	.content {
		flex: 1;
		overflow-y: scroll;
	}

	.cont {
		padding: 10rpx 20rpx;
	}
</style>