<template>
  <FlexCol :gap="20" :padding="30" :innerStyle="{
    marginTop: '-100px',
    backgroundImage: 'url(https://mn.wenlvti.net/app_static/xiangyuan/images/home/HomeBackground.jpg)',
    backgroundSize: '100% auto',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'top center',
    backgroundColor: '#7bda82',
  }">
    <Height height="100px" />
    <FlexCol align="center">
      <Image src="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/ButtonTitle.png" width="430rpx" mode="widthFix" />
      <Image src="https://mn.wenlvti.net/app_static/xiangyuan/images/home/ButtonSubTitleNew.png" width="520rpx" mode="widthFix" />
    </FlexCol>
    <Box icon="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/icon-pin-distance.png" :padding="false">
      <LightMap
        @getedCurrentLonlat="getedCurrentLonlat"
      />
      <FlexRow justify="space-between" :padding="[10, 16]">
        <ImageButton src="https://mn.wenlvti.net/app_static/xiangyuan/images/home/ButtonMainAction.png" :width="215" mode="widthFix" @click="goCommonContentList({ modelId: 18, mainBodyColumnId: 361, autoJumpFirst: true })" />
        <ImageButton src="https://mn.wenlvti.net/app_static/xiangyuan/images/home/ButtonMainLight.png" :width="215" mode="widthFix" @click="navTo('/pages/home/light/submit-map', { latitude: currentLonlat.latitude, longitude: currentLonlat.longitude })" />
        <ImageButton src="https://mn.wenlvti.net/app_static/xiangyuan/images/home/ButtonMainSupport.png" :width="215" mode="widthFix" @click="goCommonContentList({ modelId: 18, mainBodyColumnId: 362, autoJumpFirst: true })" />
      </FlexRow>
    </Box>

    <Box title="资讯动态" icon="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/icon-compass.png" showMore @moreClicked="goCommonContentList({
      title: '资讯动态',
      modelId: 18,
      mainBodyColumnId: 363,
    })">  
      <SimplePageContentLoader :loader="newsLoader">
        <FlexCol :gap="25">
          <Touchable 
            v-for="(item, i) in newsLoader.content.value"
            :key="i"
            justify="space-between"
            align="center"
            direction="row"
            @click="goCommonContentDetail(item.id)"
          > 
            <FlexCol flex="1" :gap="20">
              <Text :text="item.title" fontConfig="h5" />
              <Text :text="item.desc" fontConfig="subText" />
            </FlexCol>
            <Width :width="25" />
            <Image 
              :src="item.image" 
              :failedImage="AppCofig.defaultImage"
              :width="170" 
              :height="120" 
              :radius="15" 
              mode="aspectFill"
            />
          </Touchable>
        </FlexCol>
      </SimplePageContentLoader>
    </Box>

    <Box title="周边文化遗产" icon="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/icon-compass.png" @moreClicked="goCommonContentList({ 
      modelId: 1, 
      latitude: currentLonlat.latitude,
      longitude: currentLonlat.longitude,
      isNearby: true,
    })">  
      <SimplePageContentLoader :loader="recommendedNearbySitesLoader">
        <FlexRow wrap :gap="25">
          <Touchable 
            v-for="(item, i) in recommendedNearbySitesLoader.content.value"
            :key="i"
            direction="column"
            backgroundColor="white"
            :innerStyle="{
              flexBasis: '43%',
            }"
            :padding="13"
            :radius="15"
          > 
          <!-- @click="goCommonContentDetail(item.id)" -->
            <Text :text="item.title" fontConfig="h5" />
            <Text :text="`距离您约 ${item.distance}`" fontConfig="subText" />
            <!-- <FlexCol flex="1" :gap="20">
            </FlexCol>
            <Width :width="25" />
            <Image 
              :src="item.image" 
              :failedImage="AppCofig.defaultImage"
              :width="170" 
              :height="120" 
              :radius="15" 
              mode="aspectFill"
            /> -->
          </Touchable>
        </FlexRow>
      </SimplePageContentLoader>
    </Box>
    <!-- <Box title="线上史馆展示" icon="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/icon-ancient-gate.png">
      <SimplePageContentLoader :loader="recommendLoader">
        <FlexRow justify="space-between" align="center" wrap :gap="25">
          <Touchable 
            v-for="(item, i) in recommendLoader.content.value"
            :key="i"
            :gap="20"
            flex="0 0 48%"
            align="center"
            direction="column"
            @click="goVillageDetails(item)"
          > 
            <Image 
              :src="item.thumbnail || item.image" 
              width="100%" 
              height="200rpx" 
              :radius="15" 
              mode="aspectFill" 
            />
            <Text :text="item.title" />
          </Touchable>
        </FlexRow>
      </SimplePageContentLoader>
    </Box> -->
    <!-- <Box title="精彩推荐" icon="https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/icon-compass.png" showMore @moreClicked="$emit('goDiscover')">  
      <SimplePageContentLoader :loader="discoverLoader">
        <FlexCol :gap="25">
          <Touchable 
            v-for="(item, i) in discoverLoader.content.value"
            :key="i"
            justify="space-between"
            align="center"
            direction="row"
            @click="goDiscoverDetails(item)"
          > 
            <FlexCol flex="1" :gap="20">
              <Text :text="item.title" fontConfig="h5" />
              <Text :text="item.desc" fontConfig="subText" />
            </FlexCol>
            <Width :width="25" />
            <Image 
              :src="item.image" 
              :failedImage="AppCofig.defaultImage"
              :width="170" 
              :height="120" 
              :radius="15" 
              mode="aspectFill"
            />
          </Touchable>
        </FlexCol>
      </SimplePageContentLoader>
    </Box> -->
    <Loadmore status="nomore" />
    <Height :height="150" />
  </FlexCol>
</template>

<script setup lang="ts">
import { navTo } from '@/components/utils/PageAction';
import { useSimpleDataLoader } from '@/common/composeabe/SimpleDataLoader';
import { ref } from 'vue';
import VillageApi from '@/api/inhert/VillageApi';
import VillageInfoApi from '@/api/inhert/VillageInfoApi';
import Box from '@/common/components/parts/Box.vue';
import SimplePageContentLoader from '@/common/components/SimplePageContentLoader.vue';
import AppCofig from '@/common/config/AppCofig';
import Image from '@/components/basic/Image.vue';
import Text from '@/components/basic/Text.vue';
import Loadmore from '@/components/display/loading/Loadmore.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Height from '@/components/layout/space/Height.vue';
import Width from '@/components/layout/space/Width.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';
import Grid from '@/components/layout/grid/Grid.vue';
import GridItem from '@/components/layout/grid/GridItem.vue';
import LightMap from '../components/LightMap.vue';
import ImageButton from '@/components/basic/ImageButton.vue';
import CommonContent, { GetContentListParams } from '@/api/CommonContent';
import UnmoveableContent from '@/api/inheritor/UnmoveableContent';
import { goCommonContentDetail, goCommonContentList } from '../article/common/CommonContent';
import { toast } from '@/components/utils/DialogAction';

const currentLonlat = ref<{ longitude: number, latitude: number }>({ longitude: 0, latitude: 0 });
const isLightMode = ref(false);

function getedCurrentLonlat(lonlat: { longitude: number, latitude: number }) {
  currentLonlat.value = lonlat;
  recommendedNearbySitesLoader.loadData();
}

function goVillageDetails(e: any) {
  const id = typeof e.markerId == 'number' ? e.markerId : e.id;
  uni.setStorageSync('VillageTemp', JSON.stringify(villageLoader.content.value?.find(p => p.id == id)));
  setTimeout(() => {
    navTo('/pages/home/village/details', { id: id });
  }, 200);
}

/** 根据两点经纬度计算直线距离（米），Haversine 公式 */
function getDistanceMeters(
  lon1: number, lat1: number,
  lon2: number, lat2: number
): number {
  const R = 6371000; // 地球半径 米
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}
function getDistance(longitude: number, latitude: number): string {
  const meters = getDistanceMeters(longitude, latitude, currentLonlat.value.longitude, currentLonlat.value.latitude);
  if (meters < 100) return '一百米内';
  if (meters < 1000) return `${Math.round(meters / 100) * 100}米`;
  return `${Math.round(meters / 1000)}km`;
}

const recommendedNearbySitesLoader = useSimpleDataLoader(async () => {
  const res = (await CommonContent.getContentList(new GetContentListParams()
    .setModelId(UnmoveableContent.modelId)
    .setSelfValues({
      longitude: currentLonlat.value.longitude,
      latitude: currentLonlat.value.latitude,
    }), 1, 8, undefined, true)).list;

  for (const item of res) 
    item.distance = getDistance(item.longitude, item.latitude);
  return res;
});

const villageLoader = useSimpleDataLoader(async () => {
  const res = (await VillageApi.getVallageList(undefined, 1)).map((p, i) => ({
    ...p,
    id: p.id ?? i,
    title: p.villageName,
    longitude: Number(p.longitude),
    latitude: Number(p.latitude),
    width: 30,
    height: 30,
    iconPath: p.thumbnail || p.image,
  }));
  return res;
});

const recommendLoader = useSimpleDataLoader(async () => {
  //const category = (await CommonContent.getCategoryList(151)).find(p => p.title == '省级');
  return (await VillageApi.getVallageList(undefined, 1));
});

const discoverLoader = useSimpleDataLoader(async () => {
  return (await VillageInfoApi.getListForDiscover(1, 10)).list.map((item) => {
    return {
      ...item,
      image: (item.thumbnail || item.image) as string,
      desc: item.desc || '',
      title: item.title,
    }
  })
});

const newsLoader = useSimpleDataLoader(async () => {
  return (await CommonContent.getContentList(new GetContentListParams()
    .setModelId(18)
    .setMainBodyColumnId(363)
  , 1, 8)).list;
});

function goDiscoverDetails(item: any) {
  navTo('/pages/home/discover/details', {
    id: item.id,
    collectModelId: item.collectModuleId,
    collectModelInternalName: item.collectModuleInternalName,
  });
}

function goList(keywords: string) {
}

</script>