<route lang="json">
{
  "style": {
    "navigationBarTitleText": "详情",
    "navigationBarBackgroundColor": "#fff",
    "navigationStyle": "custom"
  }
}
</route>
<script setup lang="ts">
import Tag from '@/components/tag.vue'
import {
  createCircleReview,
  getCircle,
  getCircleReviews,
  getCircleUpvotes,
  shareCircle,
} from '../../../core/libs/requests'
import { handleShareClick, handleUpvoteClick } from '../../../core/libs/actions'
import CommentItem from '../components/comment-item.vue'
import { useDictStore, useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import { isImageOrVideo, requestToast } from '../../../core/utils/common'
import dayjs from 'dayjs'
import SectionHeading from '@/components/section-heading.vue'
import BottomAppBar from '@/components/bottom-app-bar.vue'
import { likeActived, likeBlack } from '@designer-hub/assets/src/icons'
import NavBarEvo from '@/components/navbar-evo.vue'
import { useRouter } from '../../../core/utils/router'
import { usePermissions } from '../../../composables/permissions'
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html.vue'
import WdInput from 'wot-design-uni/components/wd-input/wd-input.vue'
import { getRect, addUnit } from 'wot-design-uni/components/common/util'
import Card from '@/components/card.vue'
import { get } from 'radash'
import { DictType } from '../../../core/libs/models'
import MomentVideo from '@/pages-sub/home/components/moment-video.vue'
import { ComponentExposed } from 'vue-component-type-helpers'
import { useShare } from '@/composables/share'

const { features, clickByPermission } = usePermissions()
const { shareAppMessage } = useShare()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const router = useRouter()
const dictStore = useDictStore()
const { getOptionLabel } = dictStore
const id = ref()
const current = ref(0)
const isShared = ref(false)
const commentRef = ref<InstanceType<typeof WdInput>>()
const commentItemRef = ref<InstanceType<typeof CommentItem>[]>()
const instance = getCurrentInstance()
const momentVideoRef = ref<ComponentExposed<typeof MomentVideo>[]>()
const focus = ref(false)
const hot = ref(true)
const active = ref('hot');
const { data, run } = useRequest(() => getCircle(id.value), { initialData: {} })
const { data: reviews, run: runGetReviews } = useRequest(
  () => getCircleReviews({ circleId: id.value,hot:hot.value}),
  {
    initialData: {
      list: [],
    },
  },
)
const { data: circleUpvotes, run: setCircleUpvotes } = useRequest(
  () => getCircleUpvotes(id.value),
  { initialData: { list: [], total: 0 } },
)
const swiperStyle = ref()
const reviewContent = ref('')
const reviewId = ref()
const refreshIndex = ref<number>()
const isVideo = computed(
  () => data.value?.bannerUrls?.length && isImageOrVideo(data.value.bannerUrls.at(0)) === 'video',
)
const handleChange = ({ detail }) => {
  console.log('current', current.value, detail.current)
  console.log(momentVideoRef.value)
  if (isVideo.value) {
    momentVideoRef.value[current.value]?.videoContext.pause()
  }
  current.value = detail.current
}
const setSwiperStyle = async () => {
  if (!data.value.bannerUrls.length) return
  const { screenWidth } = await uni.getSystemInfo()
  if (isImageOrVideo(data.value.bannerUrls[0]) === 'video') {
    return
  }

  const { width, height } = await uni.getImageInfo({ src: data.value.bannerUrls.at(0) })
  console.log(screenWidth / width)

  swiperStyle.value = {
    height:
      height > width
        ? addUnit(500)
        : height === width
          ? addUnit(screenWidth)
          : addUnit(
              screenWidth / width > 1
                ? height / (screenWidth / width)
                : height * (screenWidth / width),
            ),
  }
  console.log('swiperStyle', swiperStyle.value)
}
const handleSend = async () => {
  if (!reviewContent.value) {
    await uni.showToast({ title: '请输入评论内容', icon: 'none' })
    return
  }
  const { code, msg } = await createCircleReview({
    circleId: id.value,
    userId: userInfo.value.userId,
    userName: userInfo.value.nickname,
    reviewContent: reviewContent.value,
    replayReviewId: reviewId.value,
  })
  if (code !== 0) {
    await uni.showToast({ title: msg, icon: 'none' })
  } else {
    reviewContent.value = ''
    console.log('refreshIndex', refreshIndex.value)
    await uni.showToast({ title: '评论成功', icon: 'none' })
    if (refreshIndex.value !== undefined) {
      console.log(instance.refs)
      await commentItemRef.value.at(refreshIndex.value).refresh()
      reviewId.value = undefined
      refreshIndex.value = undefined
    } else {
      await runGetReviews()
    }
    focus.value = false
  }
}
const handleReplay = async (options) => {
  reviewId.value = options.reviewId
  refreshIndex.value = options.index
  focus.value = true
}
const handleDelete = async (index?: number) => {
  if (index !== undefined) {
    await commentItemRef.value.at(index).refresh()
  } else {
    await runGetReviews()
  }
}
const handleUpvote = async (index?: number) => {
  if (index !== undefined) {
    await commentItemRef.value.at(index).refresh()
  }
  await runGetReviews()
}
const toDesignerHomepage = () => {
  if (['1', '2'].includes(String(data.value?.circleType))) {
    router.push(
      `/pages-sub/mine/homepage/index?id=${data.value?.stylistId}${isShared.value ? '&isShared=true' : ''}`,
    )
  }
}
onMounted(async () => {})
onLoad(async (query?: { id: string; isShared?: boolean }) => {
  id.value = query?.id
  isShared.value = query?.isShared
  await run()
  await setSwiperStyle()
  await runGetReviews()
  await setCircleUpvotes()
})
// onShareAppMessage(async () => {
//   await shareCircle(id.value)
//   return { title: data.value?.circleDesc }
// })
onShareAppMessage(shareAppMessage)


const handleClick = async (value:boolean) => {
  active.value = value ? 'hot' : 'time';
  hot.value = value
  await runGetReviews()
};
</script>
<template>
  <view class="bg-white flex-grow">
    <NavBarEvo placeholder :isShowBack="!isShared">
      <template #prepend>
        <div class="flex items-center gap-2" @click="toDesignerHomepage">
          <wd-img width="24" height="24" round :src="data.headUrl"></wd-img>
          <div class="text-black/90 text-sm font-normal font-['PingFang_SC'] leading-[10.18px]">
            {{ data.stylistName || data.marketing }}
          </div>
        </div>
      </template>
    </NavBarEvo>
    <!-- <div class="my-4 text-black/90 text-lg font-normal font-['PingFang_SC'] leading-[10.18px]">
      {{ data?.detailsDesc }}
    </div> -->
    <template v-if="data.circleType === '1'">
      <template v-if="!isVideo">
        <div class="pos-relative">
          <div class="currentImg">{{ current + 1 }}/{{ data?.bannerUrls.length }}</div>
          <swiper
            :current="current"
            :style="swiperStyle"
            @change="handleChange"
            :indicator-dots="true"
          >
            <template v-for="it of data?.bannerUrls" :key="it">
              <swiper-item>
                <wd-img
                  width="100%"
                  height="100%"
                  :src="it"
                  mode="aspectFill"
                  :enable-preview="true"
                ></wd-img>
              </swiper-item>
            </template>
          </swiper>
        </div>
      </template>
      <template v-if="isVideo">
        <div class="relative aspect-[1.64/1]">
          <div class="currentImg">{{ current + 1 }}/{{ data?.bannerUrls.length }}</div>
          <swiper @change="handleChange">
            <template v-for="it of data?.bannerUrls" :key="it">
              <swiper-item>
                <!--                <video-->
                <!--                  ref="momentVideo"-->
                <!--                  width="100%"-->
                <!--                  class="w-full aspect-[1.64/1]"-->
                <!--                  :controls="'contimg'"-->
                <!--                  :loop="true"-->
                <!--                  :enable-progress-gesture="false"-->
                <!--                  :src="it"-->
                <!--                ></video>-->
                <MomentVideo
                  ref="momentVideoRef"
                  :src="it"
                  :enable-progress-gesture="false"
                ></MomentVideo>
              </swiper-item>
            </template>
          </swiper>
        </div>
      </template>
    </template>
    <template v-if="data.circleType === '2'">
      <div>
        <div class="aspect-[1.02/1]">
          <wd-img width="100%" height="100%" mode="aspectFill" :src="data.bannerUrls[0]"></wd-img>
        </div>
        <div class="relative">
          <div
            class="absolute top-0 left-3.5 right-3.5 box-border h-full flex items-center justify-center"
          >
            <div class="w-full px-4 py-7 bg-white rounded-2xl shadow">
              <div class="text-black/90 text-xl font-normal font-['PingFang_SC']">
                设计案例：{{ data?.caseName }}
              </div>
              <div class="mt-4 flex items-center justify-between text-black/40 text-sm">
                <div class="font-normal font-['PingFang_SC']">
                  类别:{{ getOptionLabel(DictType.circleSpaceType, data?.spaceType) }}
                </div>
                |
                <div class="text-black/40 text-sm font-normal font-['PingFang_SC']">
                  风格:{{ getOptionLabel(DictType.memberDesignStyle, data.designStyle) }}
                </div>
                |
                <div class="text-black/40 text-sm font-normal font-['PingFang_SC']">
                  面积:{{ data.spaceExtent }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <div v-if="data.circleType === '2'" class="mt-24 px-3.5">
      <SectionHeading custom-class="" title="案例描述"></SectionHeading>
    </div>
    <view v-if="data.circleType === '3'">
      <mpHtml :content="data.detailsDesc"></mpHtml>
    </view>
    <view class="m-3.5" :class="data.circleType === '2' ? 'mx-7' : ''">
      <div class="text-black/90 text-base font-normal font-['PingFang_SC']">
        {{ data?.circleDesc }}
      </div>
      <view class="my-5.5 flex gap-3.5 flex-wrap">
        <!-- <TiltedButton>按钮</TiltedButton> -->
        <template v-if="data?.tagName !== ''">
          <template v-for="it of data?.tagName?.split(',')" :key="it">
            <Tag>{{ it }}</Tag>
          </template>
        </template>
      </view>
    </view>
    <div v-if="data.circleType === '2'" class="mb-4">
      <SectionHeading custom-class="mx-3.5 my-7" title="效果图"></SectionHeading>
      <template v-for="(it, i) in data?.bannerUrls" :key="i">
        <wd-img width="100%" mode="widthFix" :src="it"></wd-img>
      </template>
    </div>
    <div class="mx-3.5">
      <div class="text-black/30 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]">
        {{ dayjs(data.createTime).format('YYYY-MM-DD HH:mm') }}
      </div>
      <!-- <view class="flex items-center my-4">
        <view class="flex items-center">
          <avatar-group-casual
            :show-number="3"
            :urls="[
              'https://via.placeholder.com/20x20',
              'https://via.placeholder.com/20x20',
              'https://via.placeholder.com/20x20',
            ]"
          ></avatar-group-casual>
          <div
            class="ml-1 text-black/60 text-sm font-normal font-['PingFang_SC'] leading-[10.18px]"
          >
            {{ circleUpvotes.total }}人赞过
          </div>
        </view>
        <view class="flex-1"></view>
        <view><wd-icon class="text-black/65" name="arrow-right" size="22px"></wd-icon></view>
      </view> -->
      <div v-if="!isShared" class="h-0.25 bg-[#dadada] my-7"></div>
      <SectionHeading v-if="!isShared" :title="`评论`" size="base">
        <template #append>
          <view v-if="reviews?.list" class="flex">
            <div @click="handleClick(true)" :class="{
        'text-black/90': active === 'hot',
        'text-black/40': active !== 'hot'
      }" class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]">
              按热度
            </div>
            <div
              class="text-xs font-normal font-['PingFang_SC'] leading-[10.18px]"
            >
              |
            </div>
            <div @click="handleClick(false)"  :class="{
        'text-black/90': active === 'time',
        'text-black/40': active !== 'time'
      }"  class="text-xs font-normal font-['PingFang_SC'] leading-[10.18px]">
              按时间
            </div>
          </view>
        </template>
      </SectionHeading>

      <view v-if="!isShared" clas="mt-8.25">
        <template v-if="reviews?.list.length">
          <template v-for="(it, i) in reviews?.list" :key="it.id">
            <CommentItem
              ref="commentItemRef"
              :options="it"
              :isChild="false"
              :index="i"
              @upvote="handleUpvote"
              @delete="handleDelete"
              @replay="handleReplay"
            ></CommentItem>
            <!-- <template v-for="child of it.childrens" :key="child.id">
              <CommentItem :options="child" :isChild="true"></CommentItem>
            </template> -->
          </template>
        </template>
        <template v-else>
          <view class="flex items-center justify-center mt-26 mb-36">
            <div class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]">
              这里空空的
            </div>
            <div
              class="ml-1.5 text-[#2f4471]/90 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]"
              @click="focus = true"
            >
              点击评论~
            </div>
          </view>
        </template>
      </view>
    </div>
    <BottomAppBar v-if="!isShared" fixed placeholder border custom-class="">
      <div class="bg-white flex items-center">
        <div class="w-[168px] bg-[#f6f6f6] rounded-[60px] px-3.5 py-2 flex items-center">
          <wd-input
            ref="commentRef"
            custom-class="bg-transparent!"
            no-border
            confirm-type="send"
            v-model="reviewContent"
            placeholder="说点什么..."
            :focus="focus"
            :cursor-spacing="16"
            @blur="focus = false"
            @confirm="handleSend"
          ></wd-input>
        </div>
        <view class="flex justify-around flex-1">
          <div>
            <template v-if="features.shareMoment">
              <button
                open-type="share"
                class="bg-transparent! p-0!"
                :data-options="data"
                @click.stop
              >
                <view
                  class="flex flex-col items-center text-[rgba(0,0,0,0.85)] text-3.5 font-400 line-height-5.5"
                >
                  <div class="w-4.5 h-4.5 flex items-center justify-center">
                    <wd-img width="15" height="15" src="/static/svgs/share.svg"></wd-img>
                  </div>
                  <view class="">{{ data?.shareCount || 0 }}</view>
                </view>
              </button>
            </template>
            <template v-else>
              <!--              <view-->
              <!--                @click.stop="clickByPermission('share', () => emits('share', options))"-->
              <!--                class="flex items-center text-[rgba(0,0,0,0.85)] text-3.5 font-400 line-height-5.5"-->
              <!--              >-->
              <!--                <wd-img width="15" height="15" src="/static/svgs/share.svg"></wd-img>-->
              <!--                <view class="ml-1">{{ props.options.shareCount }}</view>-->
              <!--              </view>-->
              <view
                class="flex flex-col items-center text-[rgba(0,0,0,0.85)] text-3.5 font-400 line-height-5.5"
                @click.stop="clickByPermission('share', () => run())"
              >
                <div class="w-4.5 h-4.5 flex items-center justify-center">
                  <wd-img width="15" height="15" src="/static/svgs/share.svg"></wd-img>
                </div>
                <view class="">{{ data?.shareCount || 0 }}</view>
              </view>
            </template>

            <!--            <button open-type="share" class="bg-transparent! p-0!">-->
            <!--            </button>-->
          </div>
          <view
            class="flex flex-col items-center text-[rgba(0,0,0,0.85)] text-3.5 font-400 line-height-5.5"
          >
            <div class="w-4.5 h-4.5 flex items-center justify-center">
              <wd-img width="15" height="15" src="/static/svgs/comment.svg"></wd-img>
            </div>
            <view class="">{{ data?.reviewCount }}</view>
          </view>
          <view
            class="flex flex-col items-center text-[rgba(0,0,0,0.85)] text-3.5 font-400 line-height-5.5"
            @click="
              clickByPermission('thumbsUp', () =>
                handleUpvoteClick(
                  {
                    upvote: data.ownUpvote,
                    circleId: data.id,
                    userId: userInfo.userId,
                    userName: userInfo.nickname,
                  },
                  () => run(),
                ),
              )
            "
          >
            <template v-if="data.ownUpvote">
              <wd-img width="18" height="18" :src="likeActived"></wd-img>
            </template>
            <template v-else>
              <wd-img width="18" height="18" :src="likeBlack"></wd-img>
            </template>
            <view>{{ data.upvoteCount }}</view>
          </view>
        </view>
      </div>
    </BottomAppBar>
    <BottomAppBar v-if="isShared" fixed placeholder>
      <div>
        <wd-button block :round="false" @click="toDesignerHomepage">查看设计师主页</wd-button>
      </div>
    </BottomAppBar>
  </view>
</template>
<style lang="scss" scope>
.currentImg {
  position: absolute;
  z-index: 2;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  top: 10rpx;
  right: 10rpx;
  padding: 4rpx 20rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
}
</style>
