<template>
  <view>
    <!-- 首页顶部定位区域 -->
    <view class="home-banner" :class="{ 'home-banner-with-bg': showAddressBg }">
      <view class="home-banner-left" @click="cityClick">
        <img src="@/static/uview/common/map-pin-fill@1x.png" alt="" class="map-pin-fill">
        <text class="address-text">{{ data.address.name }}</text>
      </view>
    </view>

    <view class="home-main">
      <view class="custom-swiper" v-if="list3.length > 0">
        <up-swiper :list="list3" indicator indicatorMode="line" circular :height="'554rpx'"></up-swiper>
      </view>
    </view>

    <view class="home-Wrapper">
      <view class="home-grid">
        <Client />
      </view>

      <view class="home-swiper" v-if="userType == 1">
        <view v-if="ValueZone.length > 0">
          <up-swiper :list="ValueZone" :indicator="false" indicatorMode="line" circular></up-swiper>
        </view>
      </view>



      <view class="home-ranking" :class="{ 'no-margin': userType === 2 }">
        <ServIces :leftList="leftList" :rightList="rightList" :ValueZoneSwiper="ValueZoneSwiper" v-if="userType == 1">
        </ServIces>
        <RankingList v-if="userType === 2" />
      </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" />
    </view>

    <custom-tab-bar page="home" class="customTabBar" />

    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onShow, onReachBottom, onUnload, onPageScroll } from '@dcloudio/uni-app'
import RankingList from '@/pages/common/rankingList/index.vue'
import ServIces from '@/components/Services/services.vue'
import { Client } from '@/components/Client/new_file.vue'
import { volunteerinfolist } from '@/api/volunteerDetailsApi/details.js'
import { slideshow, settingHomeAddress } from '@/api/home.js'
import { chooseLocationInit, locateTheCurrentAddress } from '@/utils/adress'
import CustomTabBar from '@/components/CustomTabBar/index.vue'
import { regionAddresstree } from '@/api/home.js'
import { getToken } from '@/utils/auth'
import store from '@/store'

const rightList = ref([])
const leftList = ref([])
const list3 = ref(['']) // Initialize with at least one empty item
const ValueZone = ref(['']) // Initialize with at least one empty item
const hotList = ref([])
const ValueZoneSwiper = ref([''])
const userType = uni.getStorageSync('userType'); //读取本地存储

const globalData = ref({
  statusBarHeight: 47,
  navBarHeight: 91,
})
const data = reactive({
  address: store.state.user.addressInfo,
  queryValue: '',
})
console.log('--------index--------',data.address);

// 分页
const pages = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  serviceCategory: '',
  // appStatus:"2",
})

const cityClick = async () => {
  const { latitude, longitude } = data.address
  const address = await chooseLocationInit(
    { latitude, longitude },
    addresstree.value
  )
  console.log('TCL: cityClick -> address', address)
  data.address = { ...data.address, ...address }
  store.dispatch('handlerAddress',data.address)
  settingAddress();
  console.log('address', address)
}

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'


    const { address } = data
    const { cityCode, latitude, longitude } = address
    const params = {
      pageNum: pages.value.current,
      pageSize: pages.value.pageSize,
      serviceCategory: pages.value.serviceCategory || '',
      businessManagementId: 0,

      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,
    }
    console.log('volunteerinfolist ==>',params);
    
    const res = await volunteerinfolist(params)

    if (!res || !res.rows) {
      return
    }
    console.log(
      '判断是否已经到了最后一页',
      pages.value.current >= Math.ceil(res.total / pages.value.pageSize)
    )

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

    // 每次都追加新数据
    res.rows.forEach((item, index) => {
      index % 2 !== 0 ? rightList.value.push(item) : leftList.value.push(item)
    })
    console.log('home', leftList.value, rightList.value);

    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) {
    leftList.value = []
    rightList.value = []
    loadmoreInfo.value.status = 'loadmore'
    pages.value.total = 0
    console.error('Error fetching data:', error)
  }
}

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

const getBanners = async () => {
  try {
    const res = await slideshow(21)
    if (res.code === 200 && res.data.picture) {
      list3.value = res.data.picture.split(',')
    }

    const value_res = await slideshow(20)
    if (value_res.code === 200 && value_res.data.picture) {
      ValueZone.value = value_res.data.picture.split(',')
    }

    const hot_res = await slideshow(11)
    if (hot_res.code === 200 && hot_res.data.picture) {
      hotList.value = hot_res.data.picture.split(',')
    }
    const hot_node = await slideshow(22)
    if (hot_node.code === 200 && hot_node.data.picture) {
      ValueZoneSwiper.value = hot_node.data.picture.split(',')
    }
  } catch (error) {
    console.log('error', error)
  }
}

const settingAddress = async () => {
  try {
    console.log('data', data)

    const { address } = data
    const { cityCode, latitude, longitude } = address
    const parmas = {
      provinceName: cityCode.data[0], // 省
      provinceCode: cityCode.code[0],
      provinceInd: cityCode.index[0],
      cityName: cityCode.data[1], // 市
      cityCode: cityCode.code[1],
      cityInd: cityCode.index[1],
      districtName: cityCode.data[2],
      districtCode: cityCode.code[2],
      districtInd: cityCode.index[2],
      address: address.name,
      latitude,
      longitude,
    }
    console.log("TCL: settingAddress -> parmas", parmas);
    const res = await settingHomeAddress(parmas)
    leftList.value = [];
    rightList.value = [];
    userType === 1 && getList()
  } catch (error) {
    console.log('设置地址失败', error)
  }
}

onShow(() => {
  getBanners()

  // 在 App.vue  中初始化
  uni.getSystemInfo({
    success: (res) => {
      const statusBarHeight = res.statusBarHeight

      const navBarHeight =
        res.platform === 'android' ? 48 : 44 + res.statusBarHeight
      globalData.value = { statusBarHeight, navBarHeight }
    },
  })
})

const addresstree = ref([])

const showAddressBg = ref(false)

// Handle page scroll event
onPageScroll(e => {
  // Show background when scrolled past threshold (middle of carousel, around 200px)
  showAddressBg.value = e.scrollTop > 180
})

onMounted(async () => {

  const token = getToken();
  // console.log("TCL: token", token || 'null')
  if (token) {
    const res_dara = await regionAddresstree()
    addresstree.value = res_dara.data
    locateTheCurrentAddress(res_dara.data)
      .then((res) => {
        console.log('locateTheCurrentAddress', res)
        data.address = res
        settingAddress()
      })
      .catch((error) => {
        console.log('获取地址失败!', error)
        getList()
      })
  } else {
    //设置默认角色
    uni.setStorageSync('userType', 1);
    getList();
  }
})

onUnload(() => { })
</script>

<style scoped lang="scss">
// 首页顶部区域-轮播图
.home-banner {
  position: fixed;
  z-index: 130;
  // top: v-bind('globalData.statusBarHeight + 10 + "px"');
  left: 0;
  height: 90px;
  width: 100%;
  padding: 10rpx 0;
  transition: background-color 0.3s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;

  &.home-banner-with-bg {
    // background-color: rgba(255, 255, 255, 0.9);
    // box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    background: #FAFBF0;
    height: 90px;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .home-banner-left {
    display: flex;
    align-items: center;
    padding-left: 10rpx;
    box-sizing: border-box;
    margin-top: 80rpx;

    .map-pin-fill {
      width: 34rpx;
      height: 34rpx;
    }

    .address-text {
      width: 178rpx;
      height: 42rpx;
      font-family: PingFang SC;
      font-size: 28rpx;
      font-weight: normal;
      line-height: 40rpx;
      letter-spacing: normal;
      color: #000000;
      max-width: 120rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

// 分类下轮播图
.home-swiper {
  margin-top: 40rpx;
  margin-right: 23rpx;
  margin-left: 23rpx;
  width: 704rpx;
  height: 180rpx;
  border-radius: 16rpx;
  background: linear-gradient(180deg, #FEF9ED 0%, #FFF9F3 100%);
}

// 瀑布流
.home-ranking {
  margin-top: 93rpx;
  margin-left: 11rpx;
  margin-right: 17rpx;
  margin-bottom: 120rpx;
  
  &.no-margin {
    margin-top: 0;
  }
}

// 轮播图下的圆角样式
.home-Wrapper{
  position: absolute;
  top: 542rpx;
  width: 100%;
  border-radius: 20rpx 20rpx 0rpx 0rpx;
  overflow: hidden;
  background: #FFF9F3;
}

/* 底部安全区域 */
.safe-area-bottom {
  height: 150rpx;
  width: 100%;
}
</style>
