<template>
  <view class="main-content">
    <view class="home-banner" :style="`height: ${globalData.navBarHeight}px `">
      <view class="home-banner-left" @click="cityClick">
        <up-icon name="map" color="#fff" size="25"></up-icon>
        <text class="address-text">{{ data.address.name }}</text>
      </view>
      <view class="home-banner-cente">金邻助家</view>
      <view class="home-banner-rigth">
        <!-- <up-icon name="bell" :size="25" color="rgba(46, 46, 46, 1)"></up-icon> -->
      </view>
    </view>
    <view class="home-box" :style="`margin-top: ${globalData.navBarHeight}px `">
      <view class="home-main">
        <view class="custom-swiper" v-if="list3.length > 0">
          <up-swiper
            :list="list3"
            indicator
            indicatorMode="line"
            circular
          ></up-swiper>
        </view>
      </view>

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

      <view class="home-grid hot-box" v-if="userType === 1">
        <view
          v-for="(item, index) in hotList"
          :key="index + 'hot'"
          class="hot-item"
        >
          <img :src="item" alt="" style="width: 100%; height: 160rpx" />
        </view>
       
      </view>
       <view>
          <up-notice-bar :text="text1"></up-notice-bar>
        </view>

      <view class="home-g-bgc">
        <view class="home-grid2">
          <view class="serve-title hot-box-title" v-if="userType === 1"
            >超值专区</view
          >
          <view class="hot-swiper" v-if="ValueZone.length > 0">
            <up-swiper
              :list="ValueZone"
              :indicator="false"
              indicatorMode="line"
              circular
            ></up-swiper>
          </view>
        </view>

        <view class="home-ranking home-grid2">
          <ServIces
            :leftList="leftList"
            :rightList="rightList"
            v-if="userType == 1"
          ></ServIces>
          <RankingList v-if="userType === 2" />
        </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"
      />
    </view>

    <custom-tab-bar page="home" />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { provide } from 'vue'
import { onLoad, onShow, onReachBottom, onUnload } 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 { useDict } from '@/utils/dict.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'

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 userType = uni.getStorageSync('userType') //读取本地存储
const text1 = ref(
  '热烈祝贺：于5月20日上午9:00点钟召开"金邻助家"平台项目的首次发布会！'
)
const globalData = ref({
  statusBarHeight: 47,
  navBarHeight: 91,
})
const data = reactive({
  address: {
    name: '重庆市',
    latitude: 29.333000000000002,
    longitude: 105.94909000000001,
    cityCode: {
      code: [500000, 500100, 500118],
      data: ['重庆市', '重庆市', '永川区'],
      index: [21, 0, 17],
    },
  },
  queryValue: '',
})

// 分页
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 }
  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 params = {
      pageNum: pages.value.current,
      pageSize: pages.value.pageSize,
      serviceCategory: pages.value.serviceCategory || '',
      businessManagementId: 0,
      // appStatus:pages.value.appStatus,
    }
    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 = []
      rightList.value = []
    }

    // 每次都追加新数据
    res.rows.forEach((item, index) => {
      index % 2 !== 0 ? leftList.value.push(item) : rightList.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) {
    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(19)
    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(',')
    }
  } 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,
    }
    const res = await settingHomeAddress(parmas)
    console.log('res', res)
    userType === 1 && getList()
  } catch (error) {
    console.log('设置地址失败', error)
  }
}

onShow(() => {
  getBanners()

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

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

const addresstree = ref([]);

onMounted(async () => {


  const res_dara = await regionAddresstree()
  addresstree.value = res_dara.data;

  const token  = getToken();
  if(token){
    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">
.main-content {
  background: rgba(255, 255, 255, 1);

  .home-banner {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    // background: rgba(255, 255, 255, 1);
    // background-color: #ED806A;
    background-color: rgba(221, 60, 62, 1);
    box-shadow: 0rpx 0rpx 0rpx rgba(0, 0, 0, 0), 0rpx 0rpx 0rpx rgba(0, 0, 0, 0),
      0rpx 2.08rpx 4.17rpx rgba(0, 0, 0, 0.05);
    padding: 20rpx 16rpx;
    color: #fff;
    position: fixed;
    top: 0px;
    left: 0px;
    right: 0;
    z-index: 99;
    bottom: 150rpx;
  }

  .home-box {
    padding-bottom: 150rpx;
  }

  .home-banner-left {
    display: flex;
    align-items: center;
    width: 30%;
  }

  .home-banner-center {
    flex: 1;
    font-size: 38rpx;
  }

  .home-banner-rigth {
    width: 30%;
  }

  .home-main {
    padding: 12px 16px 0;
  }

  .home-ranking {
    padding: 24rpx 16px;
  }
}

.hot-box-title {
  padding: 0 32rpx;
}

.hot-swiper {
  padding: 24rpx 32rpx 0;
}

.hot-box {
  padding: 24rpx 32rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8rpx;

  .hot-item {
    // padding: 32rpx 16rpx;
    // border-radius: 10rpx;
  }
}

.home-grid2 {
  margin-bottom: 32rpx;
  background: #fff;
  padding: 12px 0;
  border-radius: 8px;
}

.home-g-bgc {
  background: #f7f7f7;
  padding: 24rpx;
}

.address-text {
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏溢出内容 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
}
</style>
