<template>
  <FlexCol :padding="[0,0,50,0]">
    <FlexCol position="absolute" :zIndex="100" :inset="{ l: 0, r: 0, t: 0 }">
      <StatusBarSpace />
      <NavBar 
        :title="loader.content.value?.title || '文章详情'"
        leftButton="back"
        :leftButtonProps="{
          buttonStyle: {
            marginLeft: '20rpx',
          },
          shape: 'round-full',
          backgroundColor: 'background.primary',
        }"
        customBack 
        @backPressed="handleBack" 
      />
    </FlexCol>
    <SimplePageContentLoader :loader="loader">
      <template v-if="loader.content.value && loader.isLoaded.value">
        <FlexCol gap="gap.md">
          <swiper 
            v-if="loader.content.value.images.length > 0"
            circular 
            :indicator-dots="true"
            :autoplay="true"
            :interval="3000"
            :duration="1000"
            :style="{ height: '500rpx' }"
          >
            <swiper-item v-for="(item, key) in loader.content.value.images" :key="key">
              <view class="item">
                <Image 
                  :src="item" 
                  width="100%"
                  :height="500"
                  mode="aspectFill" 
                  @click="onPreviewImage(key)"
                />
              </view>
            </swiper-item>
          </swiper>
          <video 
            v-else-if="loader.content.value.video"
            :src="loader.content.value.video"
            :style="{ width: '100%', height: '500rpx' }"
          />
          <Image
            v-else-if="loader.content.value.image"
            :src="loader.content.value.image"
            width="100%"
            mode="widthFix"
          />
          <FlexCol v-else>
            <StatusBarSpace />
            <Height height="40px" />
          </FlexCol>
          <FlexRow justify="space-between" padding="padding.md" >
            <FlexCol gap="gap.md">
              <H4 fontFamily="SongtiSCBlack" wrap :maxWidth="700" :lines="2">{{ loader.content.value.title }}</H4>
              <FlexRow gap="gap.md">
                <Text v-if="loader.content.value.keywords" color="text.second" :size="28">{{ loader.content.value.keywords.join(' ') }}</Text>
                <Text color="text.second" :size="28">{{ DataDateUtils.formatDate(loader.content.value.publishAt, 'YYYY-MM-dd') }}</Text>
              </FlexRow>
            </FlexCol>
          </FlexRow>
          <FlexRow :padding="[0,30,30,30]" gap="gap.lg">
            <ImageBlock3
              :src="loader.content.value.image"
              :imageWidth="80"
              :imageHeight="50"
              backgroundColor="transparent"
              @click="handleGoVillageDetails(loader.content.value.villageId)"
            >
              <template #desc>
                <FlexCol>
                  <Text 
                    :text="`来源于：${loader.content.value.villageName}`" 
                    fontConfig="lightGoldTitle" 
                    fontSize="30" 
                  />
                  <Text fontConfig="subText" fontSize="20">点此进入村（社区）主页了解更多</Text>
                </FlexCol>
              </template>
            </ImageBlock3>
            <Touchable align="center" gap="gap.md" @click.stop="handleGoUserDetails">
              <Avatar
                :url="loader.content.value.villageVolunteerAvatar"
                defaultAvatar="https://xy.wenlvti.net/app_static/images/village/PlaceholderVolunteerNew.png"
                size="50"
                radius="radius.md"
              />
              <Text class="size-ll color-title-text" :wrap="false" :maxWidth="100">投稿人：{{ loader.content.value.villageVolunteerName }}</Text>
            </Touchable>
          </FlexRow>
          <FlexCol :padding="30">
            <Parse
              v-if="loader.content.value.content"
              :content="loader.content.value.content"
            />
            <Parse
              v-if="loader.content.value.overview"
              :content="(loader.content.value.overview as string)"
            />
            <Text v-if="emptyContent">暂无简介</Text>

            <FlexRow gap="gap.md" align="center">
              <Icon icon="info" size="40" />
              <template v-if="true" >
                <Text fontConfig="subText" fontSize="fontSize.sm" text="本文章仅代表作者个人观点，" />
                <Text fontConfig="subText" fontSize="fontSize.sm" bold text="暂未通过村（社区）审核" />
              </template>
              <Text v-else fontConfig="subText" text="本文章仅代表作者个人观点" />
            </FlexRow>
          </FlexCol>
          
          <!-- 推荐 -->
          <FlexCol v-if="recommendListLoader.content.value?.length" :padding="30">
            <H5 fontFamily="SongtiSCBlack">相关推荐</H5>
            <Box2LineImageRightShadow
              titleColor="title-text"
              v-for="item in recommendListLoader.content.value"
              :key="item.id"
              :image="item.image || AppCofig.defaultImage"
              :title="item.title"
              :desc="item.desc"
              :badge="item.villageName"
              :wideImage="true"
              @click="goDetails(item.id)"
            />
          </FlexCol>
          <Height :height="100" />
          <LikeFooter 
            :content="loader.content.value" 
            @refresh="loader.reload(); isChangedStatus=true" 
          />
        </FlexCol>
      </template>
    </SimplePageContentLoader>
  </FlexCol>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { useSimpleDataLoader } from "@/components/composeabe/loader/SimpleDataLoader";
import { useSwiperImagePreview } from "@/common/composeabe/SwiperImagePreview";
import { useLoadQuerys } from "@/components/composeabe/LoadQuerys";
import { backAndCallOnPageBack, navTo, back } from "@/components/utils/PageAction";
import { onShareTimeline, onShareAppMessage } from "@dcloudio/uni-app";
import { DataDateUtils } from "@imengyu/js-request-transform";
import SimplePageContentLoader from "@/components/loader/SimplePageContentLoader.vue";
import Parse from "@/components/display/parse/Parse.vue";
import Box2LineImageRightShadow from "@/common/components/parts/Box2LineImageRightShadow.vue";
import AppCofig from "@/common/config/AppCofig";
import VillageInfoApi from "@/api/inhert/VillageInfoApi";
import FlexRow from "@/components/layout/FlexRow.vue";
import FlexCol from "@/components/layout/FlexCol.vue";
import Image from "@/components/basic/Image.vue";
import Text from "@/components/basic/Text.vue";
import H5 from "@/components/typography/H5.vue";
import H4 from "@/components/typography/H4.vue";
import Avatar from "@/components/display/Avatar.vue";
import Touchable from "@/components/feedback/Touchable.vue";
import StatusBarSpace from "@/components/layout/space/StatusBarSpace.vue";
import NavBar from "@/components/nav/NavBar.vue";
import LikeFooter from "./components/LikeFooter.vue";
import Height from "@/components/layout/space/Height.vue";
import Icon from "@/components/basic/Icon.vue";
import ImageBlock3 from "@/components/display/block/ImageBlock3.vue";

const { onPreviewImage } = useSwiperImagePreview(() => loader.content.value?.images || []);
const emptyContent = computed(() => 
  (loader.content.value?.content || '').trim() === ''
  && (loader.content.value?.overview as string || '').trim() === ''
);

const loader = useSimpleDataLoader(async () => {
  const res = await VillageInfoApi.getInfoForDiscover(querys.value.id);
  uni.setNavigationBarTitle({ title: res.title });
  console.log('加载信息', res);
  return res;
}, false);
const recommendListLoader = useSimpleDataLoader(async () => {
  return (await VillageInfoApi.getListForDiscover({ page: 1, pageSize: 5 }))
    .list
    .filter((p) => p.id !== querys.value.id);
});

const { querys } = useLoadQuerys({ 
  id: 0,
}, (t) => loader.reload());

const isChangedStatus = ref(false);

function goDetails(id: number) {
  navTo('details', { 
    id,
  });
}

function handleGoUserDetails(id: number) {
  navTo('/pages/home/village/volunteer/detail', { id: loader.content.value?.villageVolunteerId });
}
function handleGoVillageDetails(id: number) {
  backAndCallOnPageBack('goVillage', { id });
}

function handleBack() {
  if (isChangedStatus.value) {
    backAndCallOnPageBack('refresh', { needRefresh: true });
    return;
  }
  back();
}

function getPageShareData() {
  if (!loader.content.value)
    return { title: '文章详情', imageUrl: '' }
  return {
    title: loader.content.value.title,
    imageUrl: loader.content.value.images[0],
  }
}

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