<template>
  <FlexCol :gap="20" :padding="30" :innerStyle="{
    marginTop: '-130px',
    backgroundImage: 'url(https://xy.wenlvti.net/app_static/images/home/BannerHome.png)',
    backgroundSize: '100% auto',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'top center',
    backgroundColor: themeContext.resolveThemeColor('background.primary'),
  }">
    <FlexCol position="absolute" :left="0" :top="0">
      <StatusBarSpace />
      <Button 
        @click="showCityPopup = true"
        icon="https://xy.wenlvti.net/app_static/images/home/IconSwitch.png"
        :text="currentCity"
        type="custom"
        color="transparent"
      />
    </FlexCol>
    <Height height="200px" />
    <FlexCol :gap="20" align="center">
      <SearchBar v-model="searchKeywords" placeholder="搜索" :innerStyle="{
        backgroundColor: 'white',
        borderRadius: '20rpx',
        borderWidth: '1px',
        borderStyle: 'solid',
        borderColor: themeContext.resolveThemeColor('primary'),
        width: '650rpx',
      }" />
      <Image 
        src="https://xy.wenlvti.net/app_static/images/home/BannerIndex.png" 
        width="700rpx" 
        height="200px"
        mode="aspectFill" 
        :innerStyle="{
          borderRadius: '20rpx',
          clipPath: 'ellipse(100% 90% at 50% 0%)'
        }"
      />
    </FlexCol>

    <LightMap
      small
      :limitCity="currentCity"
      :startLonlat="currentLonlat"
      @changedCity="handleChangedCity"
      @selectVillage="goDetails"
    >
      <NoticeBar 
        v-if="currentNoticeContent"
        :content="currentNoticeContent"
        :innerStyle="{
          position: 'absolute',
          top: '20rpx',
          left: '20rpx',
          right: '20rpx',
          zIndex: 100,
          borderRadius: '30rpx',
        }"
        :textStyle="{
          fontSize: '26rpx',
        }"
        icon="https://xy.wenlvti.net/app_static/images/home/IconLightActive.png"
        :iconProps="{
          size: 34,
        }"
        textColor="#C9211F"
        backgroundColor="#D9492E10"
    />
    </LightMap>

    <FlexRow justify="space-between" :padding="[10, 16]" gap="gap.md">
      <Button 
        icon="https://xy.wenlvti.net/app_static/images/home/IconSwitch.png" 
        radius="radius.lg" 
        :padding="[10, 30]"
        @click="showCityPopup = true"
      >
        切换城市
      </Button>
      <Button 
        icon="https://xy.wenlvti.net/app_static/images/home/IconFollow.png" 
        radius="radius.lg" :padding="[10, 30]" 
        @click="showMyFollowPopup = true"
      >
        我的关注
      </Button>
      <Button 
        icon="https://xy.wenlvti.net/app_static/images/home/IconLight.png" 
        radius="radius.lg" :padding="[10, 30]" 
        @click="navTo('/pages/home/light/submit-map', { code: currentCityCode })"
      >
        点亮村社
      </Button>
    </FlexRow>

    <HomeTitle title="乡村排名" showMore />
    <VillageRankList />

    <HomeTitle title="志愿者排名" showMore :lightCount="3" />
    <VillageUserRankList />

    <HomeTitle title="精选记忆" showMore />
    <MasonryGrid>
      <MasonryGridItem
        v-for="(item, i) in recommendLoader.content.value"
        :key="i"
        :width="340"
      >
        <IndexCommonImageItem
          :image="item.image"
          :title="item.title"
          :desc="item.desc"
          :userName="item.userName"
          :likes="item.likes"
          :isLike="item.isLike"
        />
      </MasonryGridItem>
    </MasonryGrid>

    <Loadmore status="nomore" />
    <Height :height="150" />

    <Popup 
      v-model:show="showCityPopup" 
      closeable
      position="top"
      size="80vh"
    >
      <CitySelect @selectCity="handleSelectCity" />
    </Popup>

    <Popup 
      v-model:show="showMyFollowPopup" 
      closeable
      position="bottom"
      round
      size="80vh"
    >
      <VillageMyFollow @goDetails="goDetails" />
    </Popup>
  </FlexCol>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useTheme } from '@/components/theme/ThemeDefine';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useStorageVar } from '@/components/composeabe/StorageVar';
import { useVillageStore } from '@/store/village';
import { navTo } from '@/components/utils/PageAction';
import Image from '@/components/basic/Image.vue';
import Loadmore from '@/components/display/loading/Loadmore.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Height from '@/components/layout/space/Height.vue';
import SearchBar from '@/components/form/SearchBar.vue';
import Button from '@/components/basic/Button.vue';
import HomeTitle from '@/common/components/parts/HomeTitle.vue';
import VillageRankList from './components/VillageRankList.vue';
import VillageUserRankList from './components/VillageUserRankList.vue';
import VillageInfoApi from '@/api/inhert/VillageInfoApi';
import MasonryGrid from '@/components/layout/masonry/MasonryGrid.vue';
import MasonryGridItem from '@/components/layout/masonry/MasonryGridItem.vue';
import IndexCommonImageItem from '@/common/components/parts/IndexCommonImageItem.vue';
import Popup from '@/components/dialog/Popup.vue';
import CitySelect from './components/CitySelect.vue';
import VillageMyFollow from './components/VillageMyFollow.vue';
import type { CityItem } from '@/api/map/MapApi';
import MapApi from '@/api/map/MapApi';
import LightMap from './components/LightMap.vue';
import NoticeBar from '@/components/display/NoticeBar.vue';
import StatusBarSpace from '@/components/layout/space/StatusBarSpace.vue';
import type { VillageListItem } from '@/api/inhert/VillageApi';
import FollowVillageApi from '@/api/light/FollowVillageApi';

const emit = defineEmits(['goVillage']);

const villageStore = useVillageStore();
const themeContext = useTheme();
const searchKeywords = ref('');
const showCityPopup = ref(false);
const showMyFollowPopup = ref(false);
const currentLonlat = ref<{ longitude: number, latitude: number }>();

const { value: currentCity } = useStorageVar('currentCityName', '厦门市');
const currentCityCode = ref('');

watch(currentCity, async (newVal) => {
  currentCityCode.value = await MapApi.simpleGetRegionCode(newVal);
}, { immediate: true });

const currentNoticeContent = ref('目前厦门市已被点亮一个社区，刚刚小亮贡献了10个光源，让湖里区点亮了一个社区');

const recommendLoader = useSimpleDataLoader(async () => {
   const res = (await VillageInfoApi.getListForDiscover(
    1, 20, 
    '', 
  ));
  return res.list.concat(res.list,res.list, res.list, res.list).sort(() => Math.random() - 0.5).map((item) => ({
    ...item,
    isLike: Math.random() > 0.5,
    likes: Math.floor(Math.random() * 1000),
    userName: '用户' + Math.floor(Math.random() * 1000000),
    badge: item.villageName || '',
  }))
});

function goDetails(item: VillageListItem) {
  showMyFollowPopup.value = false;
  villageStore.setCurrentVillage(item);
  emit('goVillage')
}
async function handleChangedCity(city: string) {
  currentCity.value = city;
  const res = await MapApi.searchPoi(city);
  if (res.length > 0) {
    currentLonlat.value = {
      longitude: res[0].location[0],
      latitude: res[0].location[1],
    };
  }
}
function handleSelectCity(city: CityItem) {
  currentCity.value = city.name;
  showCityPopup.value = false;
  handleChangedCity(city.name);
}

onMounted(async () => {
  const res = await FollowVillageApi.getFollowVillageList({ page: 1, pageSize: 200 });
  villageStore.setMyFollowVillages(res.list);
  if (res.list.length > 0)
    villageStore.setCurrentVillage(res.list[0]);
});
</script>