<template>
  <view class="main-content">
    <view class="content-box">
      <view class="tabs-container">
        <Tabs :list="list1" @change="handlTabs" ref="tabRef" />
      </view>

      <!-- 瀑布流 -->
      <view v-if="userType == '1'">
        <up-waterfall v-model="flowList" v-if="pages.total >0">
          <template #left>
            <view class="demo-warter" v-for="(item, index) in leftList" :key="index" @click="goToDetail(item)">
              <up-lazy-load threshold="-450" border-radius="10" :image="item.volunteerPicture"
                :index="index"></up-lazy-load>
              <view class="demo-title-container">
                <view class="demo-title">
                  {{ item.businessTierName }}
                </view>
              </view>
              <view class="demo-skillDescribe">
                {{item.skillDescribe}}
              </view>
              <view class="demo-PriceDome">
                <view class="demo-price">
                  <image :src="item.volunteerPicture" class="name-image"></image>
                  <text class="name-text">{{ item.name }}</text>
                </view>
                <view class="demo-price">
                  <image src="/static/img/1x.png" class="image-1x"></image>
                  <text class="name-textNumber">1w</text>
                </view>
              </view>
            </view>
          </template>
          <template #right>
            <view class="demo-warter" v-for="(item, index) in rightList" :key="index" @click="goToDetail(item)">
              <up-lazy-load threshold="-450" border-radius="10" :image="item.volunteerPicture"
                :index="index"></up-lazy-load>
              <view class="demo-title-container">
                <view class="demo-title">
                  {{ item.businessTierName }}
                </view>
              </view>
              <view class="demo-skillDescribe">
                {{item.skillDescribe}}
              </view>
              <view class="demo-PriceDome">
                <view class="demo-price">
                  <image :src="item.volunteerPicture" class="name-image"></image>
                  <text class="name-text">{{ item.name }}</text>
                </view>
                <view class="demo-price">
                  <image src="/static/img/1x.png" class="image-1x"></image>
                  <text class="name-textNumber">1w</text>
                </view>
              </view>
            </view>
          </template>
        </up-waterfall>
        <view v-else>
          <NoneView />
        </view>
      </view>
      <up-loadmore style="margin-top: 40rpx;" :status="loadmoreInfo.status" :loadmoreText="loadmoreInfo.loadingText"
        :loadingText="loadmoreInfo.loadmoreText" :nomoreText="loadmoreInfo.nomoreText" @loadmore="handleLoadmore"
        v-if="userType == 1 && pages.total >0" />
    </view>
  </view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
	} from 'vue';
	import {
		onLoad,
		onReachBottom
	} from "@dcloudio/uni-app";

	import {
		volunteerinfolist
	} from "@/api/volunteerDetailsApi/details.js"
	import store from '@/store'
	import Tabs from "@/pages_home/components/tabs/index.vue"
	import NoneView from '@/components/NoneView/index.vue'

	const list1 = ref([])
	const list2 = ref([])
	const flowList = ref([]); //list数据
	const rightList = ref([])
	const currentTabs2 = ref(0)
	const serviceCategory = ref('')
	const leftList = ref([])
	const showDropdown = ref(false)
	const tabRef = ref(null)
	const businessManagementId = ref(null)
	const data = reactive({
		address: store.state.user.addressInfo,
	})

	const userType = uni.getStorageSync('userType') //读取本地存储

	function handlTabs(record) {
		clearList();
		serviceCategory.value = record.parentId;
		businessManagementId.value = record.id;
		// 重置分页状态
		pages.value.current = 1;
		pages.value.total = 0;
		loadmoreInfo.value.status = 'loadmore';
		getList();
	}

	const goToDetail = async (item) => {
		const params = {
			volunteerId: item.volunteerId, // 获取 volunteerId
			serviceCategory: item.serviceCategory, // 获取 serviceCategory
			businessManagementId: item.businessManagementId, //获取 businessManagementId
		};
		uni.navigateTo({
			url: `/pages_home/pages/Volunteerside/goodsDetails?params=${JSON.stringify(params)}`
		});
	}



	onLoad((options) => {
		const dataList = JSON.parse(decodeURIComponent(options.dataList));

		serviceCategory.value = options.serviceCategory
		list1.value = dataList
		list2.value = dataList[0].children

		// 新增：动态设置顶部标题
		if (options.title) {
			uni.setNavigationBarTitle({ title: decodeURIComponent(options.title) });
		}
	})

	// 分页
	const pages = ref({
		current: 1,
		pageSize: 10,
		total: 0
	})



	const loadmoreInfo = ref({
		status: 'loadmore',
		loadingText: '努力加载中...',
		loadmoreText: '点击加载更多~',
		nomoreText: '已经到底啦～'
	})


	// 加载更多
	async function handleLoadmore(e) {
		if (pages.value.current < Math.ceil(pages.value.total / pages.value.pageSize)) {
			pages.value.current += 1;
			loadmoreInfo.value.status = 'loading';
			await getList();
		} else {
			loadmoreInfo.value.status = 'nomore';
		}
	}



	const getList = async () => {
		try {
			loadmoreInfo.value.status = 'loading';

			// 检查 businessManagementId 是否存在
			if (!businessManagementId.value) {
				console.log('No businessManagementId selected');
				return;
			}
			const { address } = data
			const { cityCode, latitude, longitude } = address
			console.log('volunteerinfolist ==>',address);
			// 请求时传递分页参数
			const res = await volunteerinfolist({
				pageNum: pages.value.current, // 当前页码
				pageSize: pages.value.pageSize, // 每页大小
				businessManagementId: businessManagementId.value,
				provinceName: cityCode.data[0], // 省
				provinceCode: cityCode.code[0],
				cityName: cityCode.data[1], // 市
				cityCode: cityCode.code[1],
				districtName: cityCode.data[2],
				districtCode: cityCode.code[2],
				latitude,
				longitude,
			});

			if (!res || !res.rows) {
				return;
			}

			// 如果是第一页，先清空
			if (pages.value.current === 1) {
				leftList.value = [];
				rightList.value = [];
			}

			// 将数据分成左右两列
			res.rows.forEach((item, index) => {
				index % 2 !== 0 ? rightList.value.push(item) : leftList.value.push(item);
			});
			pages.value.total = res.total;

			// 判断是否已经到了最后一页
			if (pages.value.current >= Math.ceil(res.total / pages.value.pageSize)) {
				loadmoreInfo.value.status = 'nomore';
			} else {
				loadmoreInfo.value.status = 'loadmore';
			}
		} catch (error) {
			clearList();
			console.error('Error fetching data:', error);
		}
	};

	const clearList = () => {
		leftList.value = [];
		rightList.value = [];
		loadmoreInfo.value.status = 'loadmore';
		pages.value.total = 0;
	}

	onReachBottom(() => {
		if (pages.value.current < Math.ceil(pages.value.total / pages.value.pageSize)) {
			pages.value.current += 1;
			loadmoreInfo.value.status = 'loading';
			
			getList();
		}
	})



	onMounted(() => {
		// 如果有默认选中的 tab，则初始化数据
		if (list1.value.length > 0) {
			const defaultTab = list1.value[0];
			businessManagementId.value = defaultTab.id;

			getList();
		}
	})
</script>

<style scoped lang="scss">
.main-content {
	width: 100%;
	height: 100vh;
	background: #fff;
}

.content-box {
	width: 100%;
	height: 100%;
	padding-bottom: 40rpx;
}

	.Wrapper {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.Wrapper-img {
		width: 50rpx;
		height: 50rpx;
		margin-left: 10rpx;
	}


	.Wrapper-content {
		color: rgba(16, 16, 16, 1);
		font-size: 25rpx;
		font-family: PingFangSC-regular;
		line-height: 20rpx;
	}

	/* 外层容器 */
	.tabs-container {
		width: 100%;
		background: #fff;
		padding: 10px 0;
	}

	/* Flex 布局容器 */
	.tabs-wrapper {
		display: flex;
		align-items: center;
		position: relative;
	}

	/* 可横向滚动的 scroll-view */
	.tabs-scroll {
		flex: 1;
		/* 占据剩余空间 */
		overflow-x: auto;
		/* 允许横向滚动 */
		white-space: nowrap;
		/* 禁止换行 */
		-webkit-overflow-scrolling: touch;
		/* iOS 平滑滚动 */
	}

	/* 隐藏滚动条（可选） */
	.tabs-scroll::-webkit-scrollbar {
		display: none;
	}

	/* 固定图标（始终显示在右侧） */
	.fixed-icon {
		width: 30px;
		height: 30px;
		margin-left: 10px;
		/* 与 tabs 的间距 */
		flex-shrink: 0;
		/* 禁止压缩 */
	}

.demo-warter {
  border-radius: 8px;
  margin: 5px;
  background-color: #ffffff;
}

.u-close {
  position: absolute;
  top: 32rpx;
  right: 32rpx;
}

.demo-image {
  width: 100%;
  border-radius: 4px;
}

.demo-title-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 4rpx 12rpx;
  /* z-index: 0; */
  margin-top: 10rpx;
  border-radius: 10rpx;
  box-sizing: border-box;
  border: 1rpx solid rgba(237, 93, 49, 0.8);
}

.demo-title {

  font-size: 22rpx;
  color: #ED5D31;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

.demo-skillDescribe {
  width: 298rpx;

  font-family: PingFang SC;
  font-size: 26rpx;
  font-weight: 500;
  line-height: 36rpx;
  letter-spacing: normal;
  color: #141414;
  margin-top: 5px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

.demo-img {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;

}
.demo-PriceDome {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 15rpx;
}

.demo-price {
  display: flex;
  align-items: center;
  overflow: hidden;
  /* 防止内容溢出 */
}

.image-1x {
  width: 20rpx;
  height: 20rpx;
  z-index: 0;
}

.name-textNumber {
  font-size: 22rpx;
  font-weight: normal;
  line-height: 24rpx;
  text-align: right;
  letter-spacing: -0.04em;
  color: #FF6E51;
}


.name-text {
  width: 117rpx;
  height: 34rpx;
  font-family: PingFang SC;
  font-size: 24rpx;
  font-weight: normal;
  line-height: 34rpx;
  letter-spacing: -0.04em;
  color: rgba(0, 0, 0, 0.8);
}

.name-image {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
  border-radius: 50%;
}


.name-text {
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 超出部分隐藏 */
  text-overflow: ellipsis;
  /* 显示省略号 */
  max-width: 120rpx;
  /* 6个中文字符大约占120rpx */
}
</style>