<template>
  <FlexCol>
    <FlexCol :gap="20" :padding="[30,30,0,30]" :innerStyle="{
      marginTop: '-130px',
      backgroundImage: `url(${appConfiguration?.banners.homeTop})`,
      backgroundSize: '100% auto',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'top center',
      backgroundColor: themeContext.resolveThemeColor('background.primary'),
    }">
      <FlexCol position="absolute" :left="30" :top="0" :right="30">
        <StatusBarSpace />
        <FlexRow justify="space-between" align="center">
          <Button 
            @click="showCityPopup = true"
            icon="https://xy.wenlvti.net/app_static/images/home/IconSwitch.png"
            size="small"
            :text="currentCity"
          />
          <Image
            :src="appConfiguration?.banners.homeTitle"
            :width="140"
            :height="75"
          />
          <Width :width="150" />
        </FlexRow>
      </FlexCol>
      <Height height="150px" />
      <FlexCol :gap="20" align="center">
        <FlexRow justify="space-between" align="center" width="100%">
          <SearchBar v-model="searchKeywords" placeholder="搜索" :innerStyle="{
            backgroundColor: 'white',
            borderRadius: '20rpx',
            borderWidth: '1px',
            borderStyle: 'solid',
            borderColor: themeContext.resolveThemeColor('primary'),
            width: '490rpx',
          }" />
          <Button icon="ai-thinking" @click="handleGoAI" text="问AI" />
        </FlexRow>
        <ImageSwiper 
          :images="appConfiguration?.banners.home"
          :height="460"
          :width="700"
          radius="radius.md"
          :innerStyle="{
            border: '1px solid #fff',
            overflow: 'hidden',
            clipPath: 'ellipse(100% 90% at 50% 0%)'
          }"
        />
      </FlexCol>

      <LightMap
        small
        :city="currentCity"
        :lonlat="currentLocation.currentLonlat.value"
        @getCurrentLonlat="currentLocation.getCurrentExactLocation"
        @selectVillage="goDetails"
        @regionChanged="currentRegion=$event"
      >
        <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="handleLightVillage"
        >
          点亮村社
        </Button>
      </FlexRow>

      <!-- <HomeTitle title="最新动态" />
      <Construction text="测试数据，没有接口！">
        <FlexCol gap="gap.lg">
          <FlexRow 
            v-for="item in activityLoader.content.value" :key="item.id"
            backgroundColor="background.tertiary"
            radius="radius.md"
            :padding="[20, 30]"
            gap="gap.lg"
            align="center"
          > 
            <Avatar 
              :url="item.head"
              :size="80"
              :round="false"
              :radius="10"
            />
            <Text :text="item.content" fontConfig="contentText" :innerStyle="{ flex: 1 }" />
          </FlexRow>
        </FlexCol>
      </Construction> -->

      <HomeTitle title="乡村排名" showMore @moreClicked="navTo('/pages/home/village/rank/village', {
        regionId: currentRegion ?? undefined,
      })" />
      <VillageRankList :list="villageRankListLoader.content.value ?? []" :jumpToSingle="false" @goDetails="goDetails" />

      <HomeTitle title="志愿者排名" showMore :lightCount="3" @moreClicked="navTo('/pages/home/village/rank/volunteer', {
        regionId: currentRegion ?? undefined,
      })" />
      <VillageUserRankList 
        :list="villageUserRankListLoader.content.value ?? []" 
        @goDetails="navTo('/pages/home/village/volunteer/detail', { id: $event.id })"
      />

      <HomeTitle title="精选记忆">
        <template #right>
          <Touchable
            :padding="[15, 20]"
            :innerStyle="{ marginRight: '20rpx' }"
            direction="row"
            center
            gap="gap.md"
            @click="handleGoPublish()"
          >
            <Icon name="https://xy.wenlvti.net/app_static/images/village/IconLargeHistory.png" :size="30" />
            <Text text="AI帮你写" fontConfig="contentText" />
          </Touchable>
        </template>
      </HomeTitle>
    </FlexCol>
    <OfficialAccountPublishWrap
      topic="亮乡源" 
      @publishsuccess="onPublishSuccess"
    />

    <Height :height="200" />

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

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

    <IntroClamTip ref="introClamTipRef" @apply="handleLightVillage" />
  </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 { useGetCurrentLocation } from './composeabe/GetCurrentLocation';
import { useAuthStore } from '@/store/auth';
import { useRequireLogin } from '@/common/composeabe/RequireLogin';
import { useOfficialAccount } from './composeabe/OfficialAccount';
import { useUserTools } from '@/common/composeabe/UserTools';
import { ArrayUtils, waitTimeOut } from '@imengyu/imengyu-utils';
import { toast } from '@/components/utils/DialogAction';
import { navTo } from '@/components/utils/PageAction';
import Image from '@/components/basic/Image.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 Popup from '@/components/dialog/Popup.vue';
import CitySelect from './components/CitySelect.vue';
import VillageMyFollow from './components/VillageMyFollow.vue';
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 LightVillageApi, { VillageListItem } from '@/api/light/LightVillageApi';
import type { CityItem } from '@/api/map/MapApi';
import Width from '@/components/layout/space/Width.vue';
import OfficialAccountPublishWrap from '@/common/components/OfficialAccountPublishWrap.vue';
import IntroClamTip from './village/dialogs/IntroClamTip.vue';
import MemoryTimeOut from '@/components/composeabe/MemoryTimeOut';
import Touchable from '@/components/feedback/Touchable.vue';
import Icon from '@/components/basic/Icon.vue';
import Text from '@/components/basic/Text.vue';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration';
import ImageSwiper from '@/common/components/parts/ImageSwiper.vue';

const emit = defineEmits(['goVillage']);
const { onPublishSuccess } = useOfficialAccount();
const authStore = useAuthStore();
const villageStore = useVillageStore();
const themeContext = useTheme();
const { requireLogin } = useRequireLogin();
const { getIsVolunteer } = useUserTools();
const searchKeywords = ref('');
const showCityPopup = ref(false);
const showMyFollowPopup = ref(false);
const introClamTipRef = ref();
const introClamTipTimeout = new MemoryTimeOut('IntroClamTip', 1000 * 3600 * 30);//30h
const appConfiguration = injectAppConfiguration();

const currentRegion = ref<number | null>(null);
const { value: currentCity } = useStorageVar('currentCityName', '');
const currentLocation = useGetCurrentLocation({
  onCityChanged: (city) => {
    currentCity.value = city;
  },
});
const currentNoticeContent = ref('目前厦门市已被点亮一个社区，刚刚小亮贡献了10个光源，让湖里区点亮了一个社区');

const villageRankListLoader = useSimpleDataLoader(async () => {
  const res = await LightVillageApi.getVillageRankList({ region_id: currentRegion.value ?? undefined, num: 3 });
  return res.map((item, i) => ({
    image: item.image ?? '',
    title: item.name,
    rank: i + 1,
    id: item.id,
  }));
});
const villageUserRankListLoader = useSimpleDataLoader(async () => {
  const res = (await LightVillageApi.getVolunteerRankList({ region_id: currentRegion.value ?? undefined, num: 3 }))
    .map((item, i) => ({
      id: item.id,
      image: item.image ?? '',
      title: item.name,
      rank: i + 1,
      score: item.points,
    }));

  if (res.length >= 3) {
    //移动第一名到中间
    const first = res[0];
    ArrayUtils.removeAt(res, 0);
    ArrayUtils.insert(res, 1, first);
  }

  return res
});

const activityLoader = useSimpleDataLoader(async () => {
  return [
    {
      id: 1,
      head: 'https://mn.wenlvti.net/app_static/minnan/images/test/ImageTest1.png',
      content: '测试数据，没有接口！：福泽乡里 为全村加成+10%乡源果，可持续24小时',
      levelText: '一级',
    },
    {
      id: 2,
      head: 'https://mn.wenlvti.net/app_static/minnan/images/test/ImageTest2.png',
      content: '福泽乡里 为全村加成+10%乡源果，可持续24小时',
      levelText: '五级',
    },
    {
      id: 3,
      head: 'https://mn.wenlvti.net/app_static/minnan/images/test/ImageTest3.png',
      content: '福泽乡里 为全村加成+10%乡源果，可持续24小时',
      levelText: '十级',
    },

  ];
});


watch(currentRegion, async (newVal) => {
  await villageRankListLoader.reload();
  await villageUserRankListLoader.reload();
});

async function goDetails(item: VillageListItem) {
  showMyFollowPopup.value = false;
  const details = await LightVillageApi.getVillageDetails(item.id);
  villageStore.setCurrentVillage(details);
  await waitTimeOut(100);
  emit('goVillage')
}
async function handleChangedCity(city: string) {
  currentCity.value = city;
  try {
    const res = (await MapApi.simpleGetRegion(city)).requireData();
    currentLocation.currentLonlat.value = {
      longitude: Number(res.center.split(',')[0]),
      latitude: Number(res.center.split(',')[1]),
    };
    console.log('currentLocation.currentLonlat.value', currentLocation.currentLonlat.value);
  } catch (error) {
    console.error(error);
    return;
  }
}
function handleSelectCity(city: CityItem) {
  currentCity.value = city.name;
  showCityPopup.value = false;
  handleChangedCity(city.name);
}
function handleGoAI() {
  requireLogin(async () => {
    navTo('/pages/chat/index');
  }, '暂时需要登录后才能使用AI助手');
}
async function handleGoPublish() {
  requireLogin(async () => {
    navTo('/pages/chat/dependent/post/publish', { tag: '亮乡源' });
  }, '欢迎使用AI助手，登录后以便使用更多功能哦！');
}
async function handleLightVillage() {
  requireLogin(async () => navTo('/pages/home/light/submit-map', { city: currentCity.value }), '登录后才能点亮村社哦！');
}

async function loadInfo() {

  //如果不是志愿者，则显示认领村庄提示
  const isVolunteer = await getIsVolunteer();
  if (!isVolunteer) {
    if (introClamTipTimeout.isTimeout()) {
      introClamTipRef.value?.show();
      introClamTipTimeout.recordTime();
    }
  }

  //加载我的关注村庄
  await villageStore.loadMyFollowVillages();
  if (villageStore.myFollowVillages.length > 0) {
    const currentVillage = villageStore.loadCurrentVillage();
    if (currentVillage) {
      villageStore.setCurrentVillage(villageStore.myFollowVillages.find(p => p.id === currentVillage) as VillageListItem || villageStore.myFollowVillages[0]);
    } else {
      villageStore.setCurrentVillage(villageStore.myFollowVillages[0] as VillageListItem);
    }
  }
}

watch(() => authStore.isLogged, async (newVal) => {
  if (newVal) {
    introClamTipTimeout.reset();
    await loadInfo();
  }
});

onMounted(async () => {
  try {
    if (currentCity.value) {
      await currentLocation.setCurrentLocationWithCity(currentCity.value);
    } else {
      await currentLocation.getCurrentFuzzyLocation();
    }
  } catch (error) {
    console.error(error);
    toast('获取当前位置失败，您可以手动选择城市');
  }
  await loadInfo();
});
</script>