<template>
  <view class="home-container page-home d-flex flex-col bg-base">
    <Image 
      innerClass="main-banner position-absolute"
      width="100%"
      src="https://mncdn.wenlvti.net/app_static/minnan/images/home/BackgroundBanner5.jpg"
      mode="widthFix"
    />
    <view class="content d-flex flex-col wing-l">

      <!-- 分栏 -->
      <view class="shadow-base radius-l bg-base p-3">
        <!--
          点击介绍
          @click="navTo('introduction')"
        -->
        <view 
          class="main-banner-box mb-25"
        >
          <text class="title">世界闽南文化交流中心</text>
          <text>闽南文化生态保护区(厦门市)</text>
          <Image 
            innerClass="footer"
            src="https://mncdn.wenlvti.net/app_static/minnan/images/home/MainBanner2.png"
            :width="280"
            mode="widthFix"
          />
        </view>
        
        <view class="position-relative d-flex flex-row flex-wrap justify-between mt-25 row-gap-sss">
          <HomeButton
            title="常识一点通"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconMap.png"
            :size="50"
            @click="navTo('/pages/article/data/list', { pageConfigName: 'explore' })"
          />
          <HomeButton
            title="闽南新鲜事"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconDoc.png"
            :size="50"
            @click="navTo('/pages/introduction/news')"
          />
          <HomeButton
            title="遗产报你知"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconIch.png"
            :size="50"
            @click="navTo('/pages/introduction/inhert')"
          />
          <HomeButton
            title="文化新视角"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconReserch.png"
            :size="50"
            @click="navTo('/pages/article/data/list', { pageConfigName: 'research' })"
          />
          <HomeButton
            title="世界走透透"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconArtifact.png"
            :size="50"
            @click="navTo('/pages/article/data/list', { pageConfigName: 'communicate' })"
          />
          <HomeButton
            title="来厦门䢐迌"
            icon="https://mncdn.wenlvti.net/app_static/minnan/images/home/IconDiscover.png"
            :size="50"
            @click="navTo('/pages/article/data/list', { pageConfigName: 'travel' })"
          />
        </view>

        <view class="position-relative d-flex flex-row flex-wrap justify-between mt-3">
          <Box1AudioPlay
            class="w-100" 
            :title="indexAudioPlayer.currentTitle.value"
            :image="indexAudioPlayer.currentItem?.value?.image"
            :playState="indexAudioPlayer.isPlaying.value"
            :playTime="indexAudioPlayer.timeString.value"
            @playPauseClick="indexAudioPlayer.playpause"
            @arrowClick="handleGoAudioList"
            @nextClick="indexAudioPlayer.next"
            @prevClick="indexAudioPlayer.prev"
            @click="handleGoAudioList"
          />
        </view>
      </view>

      <!-- 数据统计 -->
      <SimplePageContentLoader :loader="statsLoader">
        <view v-if="statsLoader.content.value" class="d-flex flex-col justify-center mt-3 pt-3 pb-3 bg-light-page radius-base">
          <view class="d-flex flex-col">
            <StatsText
              :title="statsLoader.content.value[0].title" 
              :data="statsLoader.content.value[0].datas" 
              :type="statsLoader.content.value[0].type" 
            />
            <view class="p-2">
              <HorizontalScrollText :text="statsText1" :fontSize="26" color="text.second" :outerStyle="{ height: '40rpx' }" />
            </view>
          </view>
          <view class="border-top-light-primary pt-2 mt-3"></view>
          <view class="d-flex flex-col">
            <StatsText
              :title="statsLoader.content.value[1].title" 
              :data="statsLoader.content.value[1].datas" 
              :type="statsLoader.content.value[1].type" 
            />
            <view class="p-2">
              <HorizontalScrollText :text="statsText2" :fontSize="26" color="text.second" :outerStyle="{ height: '40rpx' }" />
            </view>
          </view>
          <view class="border-top-light-primary pt-2 mt-3"></view>
          <StatsText
            :title="statsLoader.content.value[2].title" 
            :data="statsLoader.content.value[2].datas" 
            :type="statsLoader.content.value[2].type" 
          />
          <view class="border-top-light-primary pt-2 mt-3"></view>
          <StatsText
            :title="statsLoader.content.value[3].title" 
            :data="statsLoader.content.value[3].datas" 
            :type="statsLoader.content.value[3].type" 
          />
          <view class="border-top-light-primary pt-2 mt-3"></view>
          <StatsText
            :title="statsLoader.content.value[4].title" 
            :data="statsLoader.content.value[4].datas" 
            :type="statsLoader.content.value[4].type" 
          />
        </view>
      </SimplePageContentLoader>

      <!-- 文化地图 -->
      <HomeTitle title="文化地图" />
      <view class="position-relative radius-l overflow-hidden">
        <map 
          id="map"
          class="w-100 height-400"
          :markers="mapLoader.content.value || []"
          :enable-zoom="false"
          :enable-scroll="false"
          :scale="15"
          @click="navTo('/pages/inhert/map/index', { tab: mapTab })"
        />
        <scroll-view class="map-tags position-absolute" :scroll-x="true">
          <view class="tag-bar d-flex flex-row flex-nowrap">
            <view :class="mapTab == 1 ? 'active' : ''" @click="mapTab=1">
              <text class="iconfont icon-read" />
              非遗项目
            </view>
            <view :class="mapTab == 2 ? 'active' : ''" @click="mapTab=2">
              <text class="iconfont icon-task-trip" />
              非遗传习所
            </view>
            <view :class="mapTab == 3 ? 'active' : ''" @click="mapTab=3">
              <text class="iconfont icon-task-buliding" />
              文物古迹
            </view>
            <view :class="mapTab == 4 ? 'active' : ''" @click="mapTab=4">
              <text class="iconfont icon-place" />
              传统村落
            </view>
            <view :class="mapTab == 5 ? 'active' : ''" @click="mapTab=5">
              <text class="iconfont icon-task-environment-3" />
              闽南文化景区
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 精彩推荐 -->
      <HomeTitle title="精彩推荐" />
      <SimplePageContentLoader :loader="recommendLoader">
        <view class="d-flex flex-row justify-between flex-wrap">
          <view 
            v-for="(tab, k) in recommendLoader.content.value"
            :key="k"
            class="grid4-item position-relative mb-3"
            @click="handleGoDetails(tab)"
          >
            <text 
              class="tag bg-mask-white color-primary radius-l p-1 position-absolute size-s text-lines-1"
            >
              {{ tab.title }}
            </text> 
            <Image
              width="100%"
              :height="250"
              :radius="15"
              :src="tab.thumbnail || tab.image || AppCofig.defaultImage"
              mode="aspectFit"
            />
          </view>
        </view>
      </SimplePageContentLoader>
    </view>
  </view>
  <Tabbar :current="0" />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { onShareTimeline, onShareAppMessage } from '@dcloudio/uni-app';
import { navTo } from '@/components/utils/PageAction';
import { useSimpleDataLoader } from '@/common/composeabe/SimpleDataLoader';
import { useSimpleListAudioPlayer } from '@/common/composeabe/SimpleAudioPlayer';
import { navCommonList } from '@/pages/article/common/CommonContent';
import CommonContent, { GetContentListParams } from '@/api/CommonContent';
import UnmoveableContent from '@/api/inheritor/UnmoveableContent';
import SeminarContent from '@/api/inheritor/SeminarContent';
import ProjectsContent from '@/api/inheritor/ProjectsContent';
import AppCofig from '@/common/config/AppCofig';
import VillageApi from '@/api/inhert/VillageApi';
import ScenicSpotContent from '@/api/fusion/ScenicSpotContent';
import IndexContent from '@/api/introduction/IndexContent';
import StatsText, { type StatsTextItem } from '../parts/StatsText.vue';
import HomeTitle from '@/pages/parts/HomeTitle.vue'; 
import Tabbar from '@/common/components/tabs/Tabbar.vue';
import Box1AudioPlay from '@/pages/parts/Box1AudioPlay.vue';
import SimplePageContentLoader from "@/common/components/SimplePageContentLoader.vue";
import HorizontalScrollText from '@/components/typography/HorizontalScrollText.vue';
import Image from '@/components/basic/Image.vue';
import HomeButton from '../parts/HomeButton.vue';

const mapCtx = uni.createMapContext('map');
const mapTab = ref(1);
const mapLoader = useSimpleDataLoader(async () => {
  let list ;
  switch (mapTab.value) {
    default:
    case 1:
      list = (await ProjectsContent.getContentList(new GetContentListParams(), 1, 6)).list
      break;
    case 2:
      list = (await SeminarContent.getContentList(new GetContentListParams(), 1, 6)).list
      break;
    case 3:
      list = (await UnmoveableContent.getContentList(new GetContentListParams(), 1, 6)).list
      break;
    case 4:
      list = (await VillageApi.getVallageList()).slice(1, 10)
      break;
    case 5:
      list = (await ScenicSpotContent.getContentList(new GetContentListParams(), 1, 6)).list
      break;
  }  
  const res = list.map((p) => {
    return {
      ...p,
      id: p.id,
      longitude: Number(p.longitude),
      latitude: Number(p.latitude),
      iconPath: p.thumbnail,
      width: 40,
      height: 40,
    };
  });
  mapCtx.includePoints({
    points: res.map(p => {
      if (!p.longitude || !p.latitude) {
        p.longitude = AppCofig.defaultLonLat[0];
        p.latitude = AppCofig.defaultLonLat[1];
      }
      return {
        latitude: p.latitude,
        longitude: p.longitude,
      }
    }),
    padding: [20, 20, 20, 20],
  });
  return res;
}, true, undefined, true);

watch(mapTab, () => mapLoader.loadData(undefined, true));

const indexAudioPlayer = useSimpleListAudioPlayer(async () => {
  return (await CommonContent.getContentList(new GetContentListParams()
    .setModelId(5)
    .setMainBodyColumnId(321)
  , 1, 10)).list.sort((a, b) => -1).map((p) => {
    return {
      id: p.id,
      title: p.title,
      image: p.thumbnail || p.image,
      src: p.audio as string, 
    }
  });
})
function handleGoAudioList() {
  navTo('/pages/inhert/language/list') 
}

const recommendLoader = useSimpleDataLoader(async () => {
  const list = [];
  list.push(...(await ProjectsContent.getContentList(new GetContentListParams(), 1, 6)).list.map((p) => {
    p.itemType = 'intangible';
    return p;
  }));
  list.push(...(await CommonContent.getContentList(new GetContentListParams()
    .setModelId(1)
  , 1, 6)).list.map((p) => {
    p.itemType = p.type == GetContentListParams.TYPE_VIDEO ? 'video' : 'artifact';
    return p;
  }));
  return list;
});
const statsText1 = ref('');
const statsText2 = ref('');
const statsLoader = useSimpleDataLoader(async () => {
  const data = (await IndexContent.getStats());

  let sumInheritor = 0;
  let sumProject = 0;
  const topLevelProject = data.ichData.find((p: any) => p.level_text == '人类非遗')?.total || 0;
  const secondLevelProject = data.ichData.find((p: any) => p.level_text == '国家级')?.total || 0;
  const thirdLevelProject = data.ichData.find((p: any) => p.level_text == '省级')?.total || 0;
  const forthLevelProject = data.ichData.find((p: any) => p.level_text == '市级')?.total || 0;

  const topLevelInheritor = data.inheritorData.find((p: any) => p.level_text == '国家级')?.total || 0;
  const secondLevelInheritor = data.inheritorData.find((p: any) => p.level_text == '省级')?.total || 0;
  const thirdLevelInheritor = data.inheritorData.find((p: any) => p.level_text == '市级')?.total || 0;

  const projects = (data.ichData as any[]).filter((p: any) => [ '人类非遗', '国家级', '省级', '市级' ].includes(p.level_text)).map((item: any) => {
    if (item.level_text != '人类非遗')
      sumProject += item.total;
    return {
      title: item.level_text,
      value: item.total,
      titleSuffix: '项',
      type: 'forth',
      onClick: () => navTo('/pages/inhert/intangible/list', { tab: 0, level: item.level }),
    } as StatsTextItem
  });
  const inheritors = data.inheritorData.filter((p: any) => [ '国家级', '省级', '市级' ].includes(p.title)).map((item: any) => {
    sumInheritor += item.total;
    return {
      title: item.title,
      value: item.total,
      titleSuffix: '人',
      type: 'normal',
      onClick: () => navTo('/pages/inhert/inheritor/list', { level: item.level }),
    }
  });

  statsText1.value = `目前厦门市非遗项目市级以上共有 ${sumProject} 项，其中：国家级 ${secondLevelProject} 项（含 ${topLevelProject} 项为人类非遗）、省级 ${thirdLevelProject} 项、市级 ${forthLevelProject} 项。`;
  statsText2.value = `目前厦门市非遗传承人市级以上共有 ${sumInheritor} 人，其中：国家级 ${topLevelInheritor} 人、省级 ${secondLevelInheritor} 人、市级 ${thirdLevelInheritor} 人。`;

  return [
    {
      title: '非物质文化遗产代表性项目',
      datas: projects
    },
    {
      title: '非物质文化遗产代表性传承人',
      datas: inheritors
    },
    {
      title: '非物质文化遗产传习中心',
      datas: data.ichCenter.map((item: any) => {
        return {
          title: item.title,
          value: item.total,
          titleSuffix: '处',
          type: 'normal',
          onClick: () => navTo('/pages/inhert/seminar/list', { region: item.id }),
        }
      }),
    },
    {
      title: '重要相关历史风貌区',
      datas: data.historyData.map((item: any) => {
        return {
          title: item.title,
          value: item.total,
          titleSuffix: '处',
          onClick: () => {
            switch (item.title) {
              case '世界文化遗产':
                navCommonList({
                  title: '世界文化遗产',
                  modelId: 17,
                  mainBodyColumnId: 310
                });
                break;
              case '传统村落':
                navTo('/pages/inhert/village/list');
                break;
              case '重点区域':
                navCommonList({
                  title: '重点区域',
                  modelId: 17,
                  mainBodyColumnId: 283
                });
                break;
            }
          },
        }
      }),
    },
    {
      title: '闽南文化重要相关文物古迹',
      type: 'none',
      datas: data.minnanCr.map((item: any) => {
        return {
          title: item.title,
          value: item.total,
          titleSuffix: '处',
          onClick: () => navTo('/pages/inhert/artifact/list', {
            level: item.level
          }),
        }
      }),
    },
  ]

});

function handleGoDetails(item: any) {
  switch (item.itemType) {
    case 'artifact': 
      navTo('/pages/inhert/artifact/details', { id: item.id });
      break;
    case 'intangible': 
      navTo('/pages/inhert/intangible/details', { id: item.id });
      break;
    case 'video': 
      navTo('/pages/video/details', { id: item.id, modelId: item.modelId, mainBodyColumnId: item.mainBodyColumnId });
      break;
    default:
      navTo('/pages/article/details', { id: item.id, modelId: item.modelId, mainBodyColumnId: item.mainBodyColumnId });
      break;
  }
}

onShareTimeline(() => {
  return {}; 
})
onShareAppMessage(() => {
  return {}; 
})
</script>

<style lang="scss">
.page-home {

  .main-banner {
    top: 0rpx;
  }
  .content {
    margin-top: 400rpx;
  }

  .map-tags {
    left: 0;
    top: 0;
    padding: 15rpx 0;
    font-size: 25rpx;

    .tag-bar {
      padding: 0 20rpx;

      view {
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-shrink: 0;
        border-radius: 40rpx;
        padding: 10rpx 15rpx;
        background-color: #f7f3e8;
        color: #d9492e;
        margin-right: 10rpx;

        .iconfont {
          margin-right: 8rpx;
        }
        &.active {
          background-color: #d9492e;
          color: #f7f3e8;
        }
      }
    }
  }
  .grid4-item {
    width: 320rpx;

    .tag {
      top: 2rpx; 
      right: 2rpx;
      z-index: 20;
    }
  }
  .main-banner-box {
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-radius: 15rpx;
    background: linear-gradient(180deg, #E5CDAB 0%, #F0E3D6 100%), #F7F3E8;
    padding: 30rpx 20rpx;
    font-family: "SongtiSCBlack";
    color: #432A04;

    .title {
      font-size: 40rpx;
    }
    text {
      font-size: 35rpx;
      margin-top: 10rpx;
    }
    .more {
      margin-top: 30rpx;
      padding: 10rpx 18rpx;
      width: 180rpx;

      &.badge {
        background-image: url('https://mncdn.wenlvti.net/app_static/minnan/images/home/MainBanner.png');
        background-size: 100% auto;
        background-repeat: no-repeat;
      }

      text {
        font-family: initial;
        font-size: 30rpx;
      }
    }
    .footer {
      position: absolute;
      right: -80rpx;
      bottom: -10rpx;
      width: 180rpx;
      z-index: 2;
      height: auto;
    }
  }
}
</style>