<template>
	<view class="container">
		<!-- 内容区域 -->
		<view class="content">
			<!-- 收货地址 -->
			<view class="address-section" @click="selectAddress">
				<view class="address-left">
					<image class="location-icon" :src="$baseUrl + 'homepage/Q3Res/settlementCenter_addressIcon.png'"
						mode="aspectFit"></image>
					<view class="address-info">
						<text class="address-text" v-if="hasAddress">{{ fullAddress }}</text>
						<text class="address-text no-address" v-else>请选择收货地址</text>
						<view class="recipient-info" v-if="hasAddress">
							<text class="recipient-name">{{ recipientName }}</text>
							<text class="recipient-phone">{{ recipientPhone }}</text>
						</view>
					</view>
				</view>
				<view class="arrow-icon">></view>
			</view>

			<!-- 订单信息模块 -->
			<view class="order-info-section">
				<!-- 商品信息 -->
				<view class="product-section">
					<view class="store-info">
						<image class="store-icon" :src="$baseUrl + 'homepage/Q3Res/settlementCenter_shopIcon.png'"
							mode="aspectFit"></image>
						<text class="store-name">飞鹤星妈会</text>
					</view>
					<view class="product-detail">
						<view class="product-image">
							<text class="image-placeholder">优惠券</text>
						</view>
						<view class="product-info">
							<text class="product-name">优惠券名称占位优惠券名称占位优惠券名称占位</text>
							<text class="product-spec">净含量 750g</text>
							<view class="price-quantity-row">
								<text class="product-price">12000积分</text>
								<text class="product-quantity">x1</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 配送方式 -->
				<view class="delivery-section">
					<text class="delivery-label">配送方式</text>
					<text class="delivery-method">快递邮寄</text>
				</view>

				<!-- 订单备注 -->
				<view class="notes-section">
					<text class="notes-label">订单备注</text>
					<text class="notes-hint">选填:对本次交易的说明(最多40字)</text>
					<input class="notes-input" placeholder="请输入订单备注" maxlength="40" v-model="orderNotes" />
				</view>

				<!-- 订单汇总 -->
				<view class="summary-section">
					<text class="summary-label">共1件</text>
					<text class="summary-price">小计:12000积分</text>
				</view>
			</view>
		</view>

		<!-- 客服按钮 -->
		<view class="service-btn">
			<image class="service-icon" :src="$baseUrl + 'homepage/Q3Res/settlementCenter_serviceBtn.png'"
				mode="aspectFit"></image>
		</view>

		<!-- 底部提交栏 -->
		<view class="bottom-bar">
			<view class="total-info">
				<text class="total-label">商品积分</text>
				<text class="total-price">12000积分</text>
			</view>
			<button class="submit-btn" @click="submitOrder">提交订单</button>
		</view>
	</view>
</template>

<script>
import { fetchTradeCredits } from '@/api/goods.js';
import { getAddressList } from '@/api/address.js';

export default {
	data() {
		return {
			orderNotes: '',
			// 订单参数
			orderParams: {},
			priceData: null,
			// 地址信息
			selectedAddress: null,
			hasAddress: false,
			fullAddress: '',
			recipientName: '',
			recipientPhone: '',
			// 商品信息
			goodsInfo: {
				name: '',
				spec: '',
				points: 0,
				quantity: 1
			}
		}
	},
	onLoad(options) {
		console.log('结算页面参数:', options);
		
		// 解析页面参数
		this.parsePageParams(options);
		
		// 检查收货地址
		this.checkAddress();
	},
	
	onShow() {
		// 页面显示时重新检查地址（从地址编辑页面返回时）
		this.checkAddress();
	},
	methods: {
		// 解析页面参数
		parsePageParams(options) {
			this.orderParams = {
				gid: options.gid || '',
				skuld: options.skuld || '',
				buy_num: parseInt(options.buy_num) || 1,
				phone: options.phone || '',
				amount: options.amount || '',
				couponId: options.couponId || '',
				remark: options.remark || '',
				addressId: options.addressId || '',
				storeId: options.storeId || '',
				projectId: options.projectId || ''
			};

			// 解析价格数据
			if (options.priceData) {
				try {
					this.priceData = JSON.parse(decodeURIComponent(options.priceData));
				} catch (error) {
					console.error('解析价格数据失败:', error);
				}
			}

			// 设置商品信息
			this.goodsInfo = {
				name: options.goodsName || '商品名称',
				spec: options.spec || '750g',
				points: parseInt(options.points) || 0,
				quantity: parseInt(options.buy_num) || 1
			};
		},

		// 检查收货地址
		async checkAddress() {
			try {
				const response = await getAddressList();
				console.log('地址列表:', response);
				
				if (response.ok && response.success && response.data && response.data.length > 0) {
					// 查找默认地址
					const defaultAddress = response.data.find(addr => addr.current);
					if (defaultAddress) {
						this.selectedAddress = defaultAddress;
						this.hasAddress = true;
						this.orderParams.addressId = defaultAddress.id;
						this.updateAddressDisplay();
					} else {
						// 没有默认地址，使用第一个地址
						this.selectedAddress = response.data[0];
						this.hasAddress = true;
						this.orderParams.addressId = response.data[0].id;
						this.updateAddressDisplay();
					}
				} else {
					// 没有地址，需要添加
					this.hasAddress = false;
					this.selectedAddress = null;
					this.showAddAddressModal();
				}
			} catch (error) {
				console.error('获取地址列表失败:', error);
				this.hasAddress = false;
				this.selectedAddress = null;
			}
		},

		// 更新地址显示
		updateAddressDisplay() {
			if (this.selectedAddress) {
				// 构建完整地址字符串
				const addressParts = [];
				if (this.selectedAddress.province) addressParts.push(this.selectedAddress.province);
				if (this.selectedAddress.city) addressParts.push(this.selectedAddress.city);
				if (this.selectedAddress.area) addressParts.push(this.selectedAddress.area);
				if (this.selectedAddress.detail) addressParts.push(this.selectedAddress.detail);
				
				this.fullAddress = addressParts.join('');
				this.recipientName = this.selectedAddress.name || '';
				this.recipientPhone = this.selectedAddress.mobile || '';
			}
		},

		// 显示添加地址弹窗
		showAddAddressModal() {
			uni.showModal({
				title: '提示',
				content: '您还没有收货地址，是否添加地址？',
				confirmText: '添加地址',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						this.navigateToAddAddress();
					} else {
						// 用户取消，返回上一页
						uni.navigateBack();
					}
				}
			});
		},

		// 跳转到添加地址页面
		navigateToAddAddress() {
			uni.navigateTo({
				url: '/v3/addressList/addressEdit'
			});
		},

		// 选择地址
		selectAddress() {
			if (!this.hasAddress) {
				// 没有地址，跳转到添加地址页面
				this.navigateToAddAddress();
			} else {
				// 有地址，跳转到地址列表页面
				uni.navigateTo({
					url: '/v3/addressList/addressList'
				});
			}
		},

		// 提交订单
		async submitOrder() {
			try {
				// 检查是否有收货地址
				if (!this.hasAddress || !this.selectedAddress) {
					uni.showModal({
						title: '提示',
						content: '请先选择收货地址',
						confirmText: '去选择',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.selectAddress();
							}
						}
					});
					return;
				}

				// 显示确认兑换弹窗
				this.showConfirmModal();
			} catch (error) {
				console.error('提交订单失败:', error);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			}
		},

		// 显示确认兑换弹窗
		showConfirmModal() {
			uni.showModal({
				title: '兑换确认',
				content: `本次兑换需要消耗${this.goodsInfo.points}积分，确定要兑换吗？`,
				confirmText: '确定',
				cancelText: '取消',
				success: async (res) => {
					if (res.confirm) {
						await this.createOrder();
					}
				}
			});
		},

		// 创建订单
		async createOrder() {
			try {
				uni.showLoading({
					title: '下单中...'
				});

				console.log('下单参数:', this.orderParams);
				const response = await fetchTradeCredits(this.orderParams);
				console.log('下单结果:', response);

				uni.hideLoading();

				if (response.ok && response.success) {
					// 下单成功，跳转到支付结果页面
					this.navigateToPayResult(true, response.data);
				} else {
					// 下单失败
					this.navigateToPayResult(false, null, response.msg);
				}
			} catch (error) {
				console.error('下单失败:', error);
				uni.hideLoading();
				this.navigateToPayResult(false, null, error.message);
			}
		},

		// 跳转到支付结果页面
		navigateToPayResult(isSuccess, orderData = null, errorMsg = '') {
			const resultParams = {
				success: isSuccess,
				orderId: orderData ? orderData.orderId : '',
				points: this.goodsInfo.points,
				goodsName: this.goodsInfo.name
			};

			if (!isSuccess) {
				resultParams.failureReason = errorMsg || '兑换失败，请重试';
			}

			uni.navigateTo({
				url: `/v3/payResultPage/payResultPage?${this.buildQueryString(resultParams)}`
			});
		},

		// 构建查询字符串
		buildQueryString(params) {
			return Object.keys(params)
				.map(key => `${key}=${encodeURIComponent(params[key])}`)
				.join('&');
		}
	}
}
</script>

<style scoped>
.container {
	width: 100%;
	min-height: 100vh;
	background-color: #f5f5f5;
	box-sizing: border-box;
}

/* 内容区域 */
.content {
	padding: 30rpx 30rpx 160rpx;
	box-sizing: border-box;
}

/* 收货地址 */
.address-section {
	background-color: #fff;
	padding: 30rpx;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.address-left {
	display: flex;
	align-items: flex-start;
	flex: 1;
}

.location-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 20rpx;
	margin-top: 5rpx;
}

.address-info {
	flex: 1;
}

.address-text {
	font-size: 28rpx;
	color: #333;
	line-height: 40rpx;
	margin-bottom: 10rpx;
	display: block;
	overflow: hidden;
}

.address-text.no-address {
	color: #999;
	font-style: italic;
}

.recipient-info {
	display: flex;
	gap: 20rpx;
}

.recipient-name,
.recipient-phone {
	font-size: 26rpx;
	color: #666;
}

.arrow-icon {
	font-size: 32rpx;
	color: #999;
}

/* 订单信息模块 */
.order-info-section {
	background-color: #FFFFFF;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

/* 商品信息 */
.product-section {
	background-color: transparent;
	padding: 30rpx;
	border-radius: 0;
	margin-bottom: 0;
}

.store-info {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.store-icon {
	width: 28rpx;
	height: 28rpx;
	margin-right: 10rpx;
}

.store-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.product-detail {
	display: flex;
	align-items: center;
}

.product-image {
	width: 180rpx;
	height: 180rpx;
	background-color: #f0e6d2;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
	position: relative;
	overflow: hidden;
}

.image-placeholder {
	font-size: 20rpx;
	color: #8b7355;
	text-align: center;
	line-height: 1.2;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 12rpx;
	display: block;
	font-weight: 500;
}

.product-spec {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 12rpx;
	display: block;
}

.product-price {
	font-size: 32rpx;
	color: #e6a23c;
	font-weight: bold;
	display: inline-block;
	margin-right: 20rpx;
}

.price-quantity-row {
	display: flex;
	align-items: center;
	margin-top: 8rpx;
}

.product-quantity {
	margin-left: 240rpx;
	font-size: 24rpx;
	color: #999;
}

/* 配送方式 */
.delivery-section {
	background-color: transparent;
	padding: 0 30rpx 30rpx;
	border-radius: 0;
	margin-bottom: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.delivery-label {
	font-size: 28rpx;
	color: #333;
}

.delivery-method {
	font-size: 28rpx;
	color: #666;
}

/* 订单备注 */
.notes-section {
	background-color: transparent;
	padding: 0 30rpx 30rpx;
	border-radius: 0;
	margin-bottom: 0;
}

.notes-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: inline-block;
}

.notes-hint {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 10rpx;
	margin-left: 20rpx;
	display: inline-block;
}

.notes-input {
	width: 100%;
	height: 92rpx;
	border: none;
	border-radius: 10rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
	background-color: #f8f8f8;
}

/* 订单汇总 */
.summary-section {
	background-color: transparent;
	padding: 0 30rpx 30rpx;
	border-radius: 0;
	margin-bottom: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.summary-label {
	font-size: 28rpx;
	color: #333;
}

.summary-price {
	font-size: 28rpx;
	color: #e6a23c;
	font-weight: bold;
}

/* 客服按钮 */
.service-btn {
	position: fixed;
	bottom: 200rpx;
	right: 30rpx;
	width: 120rpx;
	height: 120rpx;
	background-color: #e6a23c;
	border-radius: 50%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 100;
}

.service-icon {
	width: 100%;
	height: 100%;
}

/* 底部提交栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx 30rpx 40rpx;
	box-sizing: border-box;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.total-info {
	display: flex;
	flex-direction: column;
}

.total-label {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 5rpx;
}

.total-price {
	font-size: 32rpx;
	color: #e6a23c;
	font-weight: bold;
}

.submit-btn {
	width: 200rpx;
	height: 80rpx;
	background-color: #e6a23c;
	color: #fff;
	font-size: 28rpx;
	border-radius: 40rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.submit-btn:active {
	background-color: #d4902b;
}
</style>
