<template>
	<view class="container safe-area">
		<!-- 顶部banner -->
		<banner-swiper 
			:banner-list="bannerList" 
			height="400rpx" 
			video-id-prefix="home-video"
			@image-click="onBannerImageClick"
		></banner-swiper>
		<view class="content">
			<!-- 回收流程 -->
			<view class="process-section">
				<view class="section-header">
					<text class="title">回收流程</text>
				</view>
				<view class="process-grid">
					<view class="process-item" v-for="(item, index) in processes" :key="index">
						<image :src="item.icon" mode="aspectFit" class="process-icon"></image>
						<text class="process-text">{{item.text}}</text>
						<!-- <text class="process-number">{{index + 1}}</text> -->
					</view>
				</view>
				<button class="submit-btn" hover-class="submit-btn-hover" @click="getPickupto">
					<text class="submit-btn-hearder">快速免费上门</text>
					<text class="btn-desc">点击开始预约</text>
					<image src="/static/home/1745478917401 3.png" mode="aspectFit" class="arrow-icon"></image>
					<image src="/static/home/1745478917401 4.png" mode="aspectFit" class="arrow-icon-left"></image>
				</button>
			</view>

			<uv-divider :dashed="true"></uv-divider>
			<!-- 服务城市 -->
			<view class="city-section" @click="goCity">
				<view class="city-header">
					<text>已开通包邮服务城市有哪些？</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
				<text class="city-list">{{ cityListStr }}</text>
			</view>


			<view class="Xiadan-section">
				<image :src="addressCion" alt="" class="process-icon" />
				<text class="left-text">不会下单？联系客服了解回收流程。</text>
				<view class="right" @click="goService">
					<image src="/static/home/联系客服.png" mode=""></image>
					<text>联系客服</text>
				</view>
			</view>



			<!-- 关于我们 -->
			<view class="about-section">
				<view class="section-header">
					<text class="title">关于我们</text>
				</view>
				<view class="about-footer" @click="goAbout">
					<view class="about-header">
						<image :src="sbkCion" mode="aspectFit" class="logo"></image>
						<!-- <text class="about-title">关于我们</text> -->
					</view>
					<view class="about-content">
						<text>免费寄、送件验、秒到账、助环保</text>
						<text class="about-desc">让二手交易更轻松，让地球多一份绿意</text>
					</view>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<!-- 价格概览 -->
			<view class="price-section">
				<view class="section-header" @click="getPickupto">
					<text class="title">价格概览</text>
					<view class="more">
						<uni-icons type="right" size="14" color="#999"></uni-icons>
						<text>查看更多</text>
					</view>
				</view>
				<view class="price-grid">
					<view class="price-item" v-for="(item, index) in priceList" :key="item.id || index"
						@tap="goToRecycleCategory(item.id)">
						<image v-if="item.icon" :src="item.icon" mode="aspectFit" class="item-icon"></image>
						<view v-else class="item-icon placeholder"></view>
						<text class="item-name">{{item.name}}</text>
						<text class="item-price" v-if="!item.maxPrice || item.maxPrice == item.price">¥ {{item.price}}
							<text class="item-price-right">/{{item.unit}}</text>
						</text>
						<text class="item-price" v-else>¥ {{item.price}}-{{item.maxPrice}}
							<text class="item-price-right">/{{item.unit}}</text>
						</text>
					</view>
				</view>
			</view>

			<!-- 最近回收 -->
			<view class="recent-section">
				<view class="section-header">
					<text class="title">最近回收</text>
				</view>
				<view class="records-grid">
					<view class="record-item" v-for="(item, index) in records" :key="index"
						@tap="goToInspectionReport(item)">
						<image :src="item.image" mode="aspectFill"></image>
						<text class="location">{{item.name}}</text>
						<text class="user-id">****{{item.phone ? item.phone.slice(-4) : ''}}</text>
						<text class="user-id-f">成功完成衣物回收已到账</text>
						<text class="amount">+ ¥{{item.price}}</text>
					</view>
				</view>
			</view>

			<!-- 回收去向 -->
			<view class="destination-section">
				<view class="section-header">
					<text class="title">回收去向</text>
				</view>
				<view class="destination-grid">
					<view class="destination-item "
						@click="$utils.navigateTo('/pages/mine/recyclingDestination?id=' + item.id)"
						:class="`destination-item${index + 1}`" v-for="(item, index) in destinations" :key="index">
						<image :src="item.icon" mode="aspectFit" class="dest-icon"></image>
						<view class="dest-info">
							<text class="dest-title">{{item.title}}</text>
							<text class="dest-desc">{{item.description}}</text>
						</view>
					</view>
				</view>
			</view>

		</view>
		<!-- 根据角色显示不同的导航栏 -->
		<tabbar select="home"></tabbar>
		
		<!-- 客服二维码弹窗 -->
		<service-qrcode ref="serviceQrcode" @close="closeQrcodeModal"></service-qrcode>
	</view>
</template>

<script>
	import pullRefreshMixin from '../mixins/pullRefreshMixin.js'
  import tabbar from '../../compoent/base/tabbar.vue'
  import serviceQrcode from '../../compoent/base/service-qrcode.vue'
  import bannerSwiper from '../../compoent/base/banner-swiper.vue'
export default {
  mixins: [pullRefreshMixin],
  components: {
    tabbar,
    serviceQrcode,
    bannerSwiper
  },
		data() {
			return {
				value: 0,
			processes: [],
			priceList: [],
			records: [],
				destinations: [
					// {
					// 	icon: '/static/home/爱心援乡.png',
					// 	title: '爱心援乡',
					// 	description: '精准帮扶贫困群体'
					// },
					// {
					// 	icon: '/static/home/回塑新源.png',
					// 	title: '回塑新源',
					// 	description: '塑料的第二次成型'
					// },
					// {
					// 	icon: '/static/home/织物出海.png',
					// 	title: '织物出海',
					// 	description: '分拣出最高价值'
					// },
					// {
					// 	icon: '/static/home/碳循再生.png',
					// 	title: '碳循再生',
					// 	description: '减碳从出发生系统'
					// }
				],
				bannerList: [],
				pricePreviewList: [],
				cityList: [],
				addressCion: '',
				sbkCion: '',
				queryParams: {},
			}
		},
		computed: {
			cityListStr() {
				// 提取2级城市（市级），不换行显示，控制显示数量避免超出
				const cityNames = []
				
				// 遍历省级数据，提取市级城市
				this.cityList.forEach(province => {
					if (province.children && Array.isArray(province.children)) {
						province.children.forEach(city => {
							// 只取市级城市名称，去掉"市"字后缀使显示更简洁
							const cityName = city.name.replace(/市$/, '')
							if (cityName && !cityNames.includes(cityName)) {
								cityNames.push(cityName)
							}
						})
					}
				})
				
				// 根据屏幕宽度动态调整显示数量，避免超出容器
				const maxDisplay = 6 // 减少到6个城市，确保不超出
				if (cityNames.length > maxDisplay) {
					return cityNames.slice(0, maxDisplay).join('、') + '...'
				}
				return cityNames.join('、')
			},
			address_cion() {
				console.log(getApp().globalData.configData, 'home-getApp().globalData.configData')
				const item = getApp().globalData.configData.find(i => i.keyName === 'address_cion')
				return item ? item.keyContent : ''
			},
			sbk_cion() {
				const item = getApp().globalData.configData.find(i => i.keyName === 'sbk_cion')
				return item ? item.keyContent : ''
			}
		},
		methods: {
			goAbout() {
				uni.navigateTo({
					url: '/pages/subcomponent/about'
				})
			},
			goCity() {
				uni.navigateTo({
					url: '/pages/baoyou-city/baoyou-city'
				})
			},
			getPickupto() {
				uni.switchTab({
					url: '/pages/component/recycle'
				})
			},
			async onRefresh() {
				await new Promise(resolve => setTimeout(resolve, 1000))
			},
			getAreaList() {
				this.$api('getAreaList', {}, (res) => {
					console.log(res, 'getAreaList');
					if (res.code == 200 && Array.isArray(res.result)) {
						// 按sort升序排序
						const sorted = res.result.slice().sort((a, b) => a.sort - b.sort)
						this.processes = sorted.map(item => ({
							// id: item.id,
							icon: item.image,
							text: item.title
						}))
					}
				})
			},
			goService() {
				uni.navigateTo({
					url: '/pages/subcomponent/admin_faq'
				})
			},
			goToRecycleCategory(id) {
				getApp().globalData.targetRecycleCategoryId = id
				console.log(getApp().globalData.targetRecycleCategoryId, 'getApp().globalData.targetRecycleCategoryId')
				uni.switchTab({
					url: '/pages/component/recycle'
				})
			},
			getPricePreview() {
				const resList = this.pricePreviewList || []
				if (Array.isArray(resList)) {
					// 只取一级分类，按sort升序
					const firstLevel = resList.sort((a, b) => a.sort - b.sort)
					// const firstLevel = resList.filter(item => item.pid == '0').sort((a, b) => a.sort - b.sort)
					// console.log(firstLevel,'firstLevel');
					this.priceList = firstLevel.map(item => {
						// 从静态表中找图片和价格
						// const staticItem = this.priceListStatic.find(s => s.name.replace(/\s/g, '') === item.title.replace(/\s/g, ''))
						// console.log(item,'item');
						return {
							id: item.id, // 保证有id
							icon: item.icon ? item.icon : '',
							name: item.title,
							price: item.priceNo ? item.priceNo : '',
							maxPrice: item.maxPriceNo ? item.maxPriceNo : '',
							unit: item.unit ? item.unit : ''
						}
					})
				}
			},
			getRecentGoods() {
				this.$api('getRecentGoodsList', {}, res => {
					if (res && res.code === 200 && Array.isArray(res.result) && res.result.length > 0) {
						this.records = res.result.map(item => ({
							id: item.id,
							image: item.image,
							name: item.name,
							orderId: item.orderId,
							phone: item.phone,
							price: item.price
						}))
					} else {
						this.records = []
					}
				})
			},
			getRecyclingDestination() {
				this.$api('getRecyclingDestination')
					.then(res => {
						this.destinations = res.result
					})
			},
			goToInspectionReport(item) {
				uni.navigateTo({
					url: `/pages/subcomponent/inspection-report?orderId=${item.orderId}`
				})
			},
			getFreeCityList() {
				this.$api('getFreeCityList', {}, res => {
					if (res && res.code === 200 && Array.isArray(res.result)) {
						// 保持完整的省-市-区三级结构，用于提取2级城市
						this.cityList = res.result.filter(province => 
							province.children && Array.isArray(province.children) && province.children.length > 0
						)
					} else {
						this.cityList = []
					}
				})
			},
			updateCionData() {
				const configData = getApp().globalData.configData || [];
				const address = configData.find(i => i.keyName === 'address_cion');
				const sbk = configData.find(i => i.keyName === 'sbk_cion');
				this.addressCion = address ? address.keyContent : '';
				this.sbkCion = sbk ? sbk.keyContent : '';
			},
			
			// 轮播图图片点击事件
			onBannerImageClick({ item, index }) {
				// 非视频类型的图片点击，显示客服二维码
				if (item.type !== 1) {
					this.showServiceQrcode()
				}
			},
			
			// 显示客服二维码弹窗
			showServiceQrcode() {
				this.$refs.serviceQrcode.open()
			},
			
			// 关闭二维码弹窗
			closeQrcodeModal() {
				// 弹窗关闭后的回调处理
			},
			// 初始化页面数据的方法
			initializePageData() {

				// 先设置数据，再调用处理方法
				this.pricePreviewList = getApp().globalData.pricePreviewList || []
				this.bannerList = getApp().globalData.bannerList || []
				
				this.getAreaList()
				this.getPricePreview()
				this.getRecentGoods()
				this.getFreeCityList()

				// 监听数据更新事件
				uni.$on('pricePreviewListUpdated', () => {
					this.pricePreviewList = getApp().globalData.pricePreviewList || []
					this.getPricePreview()
				})
				uni.$on('bannerListUpdated', () => {
					this.bannerList = getApp().globalData.bannerList || []
				})
			},
		},
		onLoad(query) {
			// 保存query参数
			this.queryParams = query
			if (query.shareId) {
				uni.setStorageSync('shareId', query.shareId)
			}

			// 检查App数据是否已经准备好
			if (!getApp().globalData.isAppDataReady) {
				// 显示加载状态
				uni.showLoading({
					title: '加载中...',
					mask: true
				})

				// 监听App数据准备完成事件
				uni.$on('appDataReady', () => {
					uni.hideLoading()
					this.initializePageData()
				})
			} else {
				// App数据已经准备好，直接初始化页面数据
				this.initializePageData()
			}
		},
		onUnload() {
			uni.$off('pricePreviewListUpdated')
			uni.$off('bannerListUpdated')
			uni.$off('configDataUpdated', this.updateCionData)
		},
		onShow() {
			this.updateCionData();
			// 监听全局数据更新
			uni.$on('configDataUpdated', this.updateCionData);
			this.getPricePreview();
			this.getRecyclingDestination()
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f8f8f8;
		display: flex;
		flex-direction: column;
		padding-bottom: calc(var(--window-bottom) + 70px);
	}

	.safe-area {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}



	.content {
		// flex: 1;
		width: 90%;
		margin: -80rpx auto 0;
		position: relative;
		z-index: 3;
		padding-bottom: 20rpx;
	}

	.Xiadan-section {
		display: flex;
		// justify-content: space-around;
		align-items: center;
		margin-bottom: 20rpx;
		background: linear-gradient(to bottom, #fff3db 0%, #fffefb 50%);

		image {
			width: 80rpx;
			height: 80rpx;
		}

		.left-text {
			font-family: PingFang SC;
			font-weight: 400;
			font-size: 12px;
			line-height: 140%;
			letter-spacing: 0%;
		}

		.right {
			display: flex;
			// flex-direction: row-reverse;
			box-sizing: border-box;
			align-items: center;
			justify-content: center;
			background-color: #fff0d2;
			color: #da7143;
			font-size: 24rpx;
			// flex-grow: 2;
			border: 1px solid #da7143;
			border-radius: 10rpx;
			width: 25%;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.section-header {
		display: flex;
		// justify-content: space-around;
		align-items: center;
		margin-bottom: 20rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.more {
			// justify-content: right;
			display: flex;
			flex-direction: row-reverse;
			align-items: center;
			color: #999;
			font-size: 24rpx;
			flex-grow: 2;
			// width: 100%;
			// margin-right:  0 auto;
		}
	}

	.process-section {
		background: #fff;
		border-radius: 50rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		background: linear-gradient(to bottom, #fff5e1 0%, #fffefb 30%);

		.contact-service {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #666;
			border: 1px solid #da7143;
			background-color: #fff0d2;

			.service-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 8rpx;
			}

		}

		.process-grid {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 20rpx;
			margin: 30rpx 0;
			border: none;
		}


		.process-item {
			position: relative;
			display: flex;
			flex-direction: column;
			align-items: center;
			background-color: #fff8ea;

			// left: 0; right: 0;
			.process-icon {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 10rpx;
			}

			.process-text {
				font-size: 24rpx;
				color: #333;
			}

			.process-number {
				position: absolute;
				top: -10rpx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 24rpx;
				color: #999;
			}
		}

		.submit-btn {
			background: linear-gradient(to right, #ffd01e, #ff8917);
			border-radius: 70rpx;
			padding: 20rpx;
			text-align: center;
			position: relative;
			border: none;
			display: flex;
			flex-direction: column;
			overflow: visible;

			text {
				color: #ffffff;
				font-size: 32rpx;
				font-weight: bold;
				line-height: 40rpx;
				// display: block;
			}

			.btn-desc {
				font-size: 24rpx;
				font-weight: normal;
				// margin-top: 4rpx;
			}

			.arrow-icon {
				position: absolute;
				right: 10rpx;
				top: 10%;
				transform: translateY(-50%);
				width: 40rpx;
				height: 40rpx;
				// z-index: 5;
			}

			.arrow-icon-left {
				position: absolute;
				left: 1rpx;
				top: 90%;
				transform: translateY(-50%);
				width: 40rpx;
				height: 40rpx;
				// z-index: 4;
			}
		}

		.submit-btn::after {
			border: none !important;
		}
	}

	.city-section {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;

		.city-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 10rpx;
		}

		.city-list {
			font-size: 26rpx;
			color: #333;
			font-weight: bold;
			line-height: 1.5;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			word-break: keep-all;
			width: 100%;
			max-width: 100%;
			display: block;
		}
	}

	.price-section {
		background: #f0f9eb;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		background-color: #fffefb;
		background: linear-gradient(to bottom, #fff3db 0%, #fffefb 5%);

		.section-header {
			margin-bottom: 40rpx;
		}

		.price-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20rpx;
		}

		.price-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			background: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			background-color: #fff8ea;

			.item-icon {
				width: 120rpx;
				height: 120rpx;
				margin-bottom: 12rpx;

				&.placeholder {
					width: 120rpx;
					height: 120rpx;
					margin-bottom: 12rpx;
					background: #f5f5f5;
					border-radius: 16rpx;
				}
			}

			.item-name {
				font-size: 30rpx;
				color: #333;
				margin-bottom: 8rpx;
				font-weight: 500;
			}

			.item-price {
				font-family: PingFang SC;
				font-weight: 600;
				font-size: 28rpx;
				line-height: 140%;
				letter-spacing: 0%;
				text-align: center;
				color: #181818;

				.item-price-right {
					text-align: center;
					font-size: 26rpx;
					color: #666;
					line-height: 140%;
					letter-spacing: 0%;
					font-weight: 400;
				}
			}
		}
	}

	.recent-section {
		background: #f0f9eb;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		background-color: #fffefb;
		background: linear-gradient(to bottom, #e8ffe0 0%, #fffefb 15%);

		.records-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
		}

		.record-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			background: linear-gradient(to top, #e8ffe0 0%, #fffefb 100%);
			border-radius: 16rpx;
			padding: 10rpx;
			background-color: #fff8ea;

			image {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
			}

			.location {
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
			}

			.amount {
				font-size: 30rpx;
				color: #13ac47;
				font-weight: bold;
				margin: 6rpx 0;
			}

			.user-id {
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				line-height: 140%;
				letter-spacing: 0%;
				text-align: center;
				color: #183c5c;
			}

			.user-id-f {
				font-family: PingFang SC;
				font-weight: 400;
				font-size: 22rpx;
				line-height: 140%;
				letter-spacing: 0%;
				text-align: center;
				color: #9b9b9b;
			}
		}
	}

	.destination-section {
		// background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		background: linear-gradient(to bottom, #f2f0fc 0%, #fffefb 10%);
		padding-bottom: calc(var(--window-bottom) + 60px);

		.destination-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20rpx;
		}

		.destination-item {
			display: flex;
			align-items: center;
			// background: #fff9f9;
			border-radius: 16rpx;
			padding: 20rpx;

			.dest-icon {
				width: 60rpx;
				height: 60rpx;
				margin-right: 16rpx;
			}

			.dest-info {
				flex: 1;

				.dest-title {
					font-size: 26rpx;
					color: #333;
					margin-bottom: 4rpx;
				}

				.dest-desc {
					font-size: 22rpx;
					color: #999;
				}
			}
		}
	}

	.destination-item1 {
		background: linear-gradient(to top, #ffebeb, #fffefb);
	}

	.destination-item2 {
		background: linear-gradient(to top, #ebf8ff, #fffefb);
	}

	.destination-item3 {
		background: linear-gradient(to top, #ebedff, #fffefb);
	}

	.destination-item4 {
		background: linear-gradient(to top, #ebfff2, #fffefb);
	}

	.about-section {
		background: linear-gradient(to bottom, #fff3db 0%, #fffefb 30%);
		border-radius: 20rpx;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		flex-direction: column;

		.about-footer {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
		}

		.about-header {
			display: flex;
			align-items: center;

			.logo {
				width: 60rpx;
				height: 60rpx;
				margin-right: 16rpx;
			}

			.about-title {
				font-size: 28rpx;
				color: #333;
			}
		}

		.about-content {
			flex: 1;
			margin-left: 20rpx;

			text {
				display: block;
				font-size: 26rpx;
				color: #333;
			}

			.about-desc {
				font-size: 22rpx;
				color: #999;
				margin-top: 4rpx;
			}
		}
	}

	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		border-top: 1rpx solid #f5f5f5;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.tab-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 10rpx 0;
			transition: all 0.3s ease;

			.tab-icon {
				width: 48rpx;
				height: 48rpx;
				margin-bottom: 6rpx;
			}

			text {
				font-size: 22rpx;
				color: #666;
				transition: color 0.3s ease;
			}

			&.active {
				text {
					color: #ff5e00;
				}
			}

			&:active {
				transform: scale(0.95);
			}
		}
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes fadeInScale {
		from {
			opacity: 0;
			transform: scale(0.8);
		}

		to {
			opacity: 1;
			transform: scale(1);
		}
	}


</style>