<route lang="json">
{
  "style": {
    "navigationStyle": "custom"
  }
}
</route>
<script setup lang="ts">
import MomentItem from '@/components/moment-item.vue'
import {
  createBrowseHistory,
  deleteCircle,
  getCircles,
  getDesignerInfo,
  getUserInfoById,
  updateDesignerInfo,
  shareCircle,
} from '../../../core/libs/requests'
import { useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import { NetImages } from '../../../core/libs/net-images'
import PageHelper from '@/components/page-helper.vue'
import BottomAppBar from '@/components/bottom-app-bar.vue'
import { useRouter } from '../../../core/utils/router'
import NavbarEvo from '@/components/navbar-evo.vue'
import { useMessage } from 'wot-design-uni'
import { requestToast } from '../../../core/utils/common'
import { ComponentExposed } from 'vue-component-type-helpers'
import dayjs from 'dayjs'
import wechatChannels from '@designer-hub/assets/src/libs/assets/wechatChannels'
import { handleUpvoteClick, handleShareClick } from '../../../core/libs/actions'
import { usePermissions } from '../../../composables/permissions'

const { features } = usePermissions()
const { alert, confirm } = useMessage()
const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const pageHelperRef = ref<ComponentExposed<typeof PageHelper>>()
const id = ref()
const isShared = ref(false)
const tab = ref('2')
const tabs = ref([
  { label: '案例', value: '2' },
  { label: '动态', value: '1' },
  // { label: '视频', value: '0' },
])
const viewDuration = ref(0)
const viewStartAt = ref<Date>()
const { data: memberInfo, run: setMemberInfo } = useRequest(() => getUserInfoById(id.value), {
  initialData: {},
})
const { data: designerInfo, run: setDesignerInfo } = useRequest(() => getDesignerInfo(id.value), {
  initialData: {},
})
const isOwn = computed(() => userInfo.value?.userId === id.value)
const skills = computed(() =>
  [
    {
      label: '从业年限',
      value: designerInfo.value?.serviceYears,
      show: designerInfo.value?.serviceYears,
    },
    {
      label: '客户',
      value: designerInfo.value?.serviceCustomerCount,
      show: designerInfo.value?.serviceCustomerCount,
    },
    {
      label: '设计费',
      value: `${designerInfo.value?.designFee}元/㎡`,
      show: designerInfo.value?.designFee,
    },
  ].filter(({ show }) => show),
)
const query = computed(() => ({
  circleType: tab.value,
  stylistId: id.value,
}))
const handleMomentDelete = async (id) => {
  confirm({
    title: '警告',
    msg: '确定要删除吗？',
    beforeConfirm: async ({ resolve }) => {
      await requestToast(() => deleteCircle(id))
      await pageHelperRef.value?.refresh()
      resolve(true)
    },
  })
}
const handleLike = async (options) => {
  await handleUpvoteClick({
    ...options,
    userId: userInfo.value.userId,
    userName: userInfo.value.nickname,
  })
  pageHelperRef.value?.refresh()
}
const handle2Video = () => {
  try {
    uni.openChannelsUserProfile({ finderUserName: designerInfo.value?.videoNumber })
  } catch (e) {
    uni.showToast({
      title: '打开失败',
      icon: 'none',
    })
  }
}
const handleUnbundle = async () => {
  confirm({
    title: '警告',
    msg: '确定要解绑吗？',
    beforeConfirm: async ({ resolve }) => {
      await requestToast(
        () =>
          updateDesignerInfo({
            id: designerInfo.value.id,
            userId: designerInfo.value.userId,
            videoNumber: '',
          }),
        { success: true, successTitle: '解绑成功' },
      )
      await setDesignerInfo()
      resolve(true)
    },
  })
}
onLoad(async (query: { id: string; isShared?: string }) => {
  if (query.id) {
    id.value = query.id
  } else {
    id.value = userInfo.value.userId
    // memberInfo.value =
  }
  if (query.isShared) {
    isShared.value = true
  }
  await setMemberInfo()
  await setDesignerInfo()
  if (!isOwn.value) {
    viewStartAt.value = new Date()
  }
})
onShow(async () => {
  await setDesignerInfo()
})
onUnload(async () => {
  if (!isOwn.value) {
    viewDuration.value = dayjs().diff(viewStartAt.value, 'seconds')
    const { data, code } = await createBrowseHistory({
      stylistId: id.value,
      bizType: '浏览',
      duration: viewDuration.value.toString(),
    })
  }
})
onShareAppMessage(async ({ from, target }) => {
  const res: Page.CustomShareContent = {}
  if (from === 'button') {
    if (target.dataset.type === 'homepage') {
      res.title = `${userInfo.value.nickname}: “${designerInfo.value.designDesc}”`
      res.imageUrl = designerInfo.value?.sharePageUrl
      res.path = `/pages/mine/homepage/index?id=${id.value}&isShared=true`
    } else {
      if (!features.value.shareMoment) {
        return handleShareClick()
      }
      await shareCircle(target.dataset.options.id)
      res.path = `/pages/home/moment/index?id=${target.dataset.options.id}&isShared=true`
      res.imageUrl = target.dataset.options.bannerUrls[0]
      res.title = `${target.dataset.options.stylistName}: ${target.dataset.options.circleDesc}`
    }
  }
  if (from === 'menu') {
    res.title = `${userInfo.value.nickname}: “${designerInfo.value.designDesc}”`
    res.imageUrl = designerInfo.value?.sharePageUrl
    res.path = `/pages/mine/homepage/index?id=${id.value}&isShared=true`
  }
  return res
})
onShareTimeline(() => ({}))
defineExpose({
  navBarFixed: false,
})
</script>
<template>
  <div class="flex-grow flex flex-col">
    <NavbarEvo transparent dark :isShowBack="!isShared"></NavbarEvo>
    <div class="relative">
      <wd-img
        width="100%"
        :src="designerInfo?.homePageUrl || NetImages.DesigerHomepageDefaultBg"
        mode="aspectFill"
        custom-class="aspect-[1.14/1]"
      />
      <div class="absolute bottom-0 left-0 right-0">
        <div class="bg-gradient-to-t from-black to-transparent">
          <div class="flex min-h-27">
            <div
              class="w-18 h-18 border-white border border-solid mx-3.5 rounded-full overflow-hidden"
            >
              <wd-img
                width="100%"
                height="100%"
                :src="isOwn ? userInfo?.avatar : memberInfo?.avatar || NetImages.DefaultAvatar"
              ></wd-img>
            </div>
            <div class="pb-8 flex-1">
              <div class="text-white text-2xl font-normal font-['PingFang_SC'] leading-normal">
                {{ memberInfo.name }}
              </div>
              <div class="flex flex-wrap gap-4">
                <template v-for="(it, i) in designerInfo?.personalIdentity?.split('、')" :key="i">
                  <div
                    class="h-6 px-2 bg-black/10 rounded-[30px] border border-solid border-white/60 justify-center items-center gap-2.5 inline-flex"
                  >
                    <div
                      class="text-center text-white text-[10px] font-normal font-['PingFang_SC'] leading-normal"
                    >
                      <!-- 创设空间事务所创始人 -->
                      {{ it }}
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-grow flex flex-col bg-white rounded-t-2xl relative bottom-4 gap-5 px-3.5 pt-5">
      <div class="flex gap-4" v-if="skills.length">
        <template v-for="(it, i) in skills" :key="i">
          <div>
            <span
              class="mr-0.575 text-black/90 text-base font-normal font-['PingFang_SC'] leading-[26.98px]"
            >
              {{ it.value }}
            </span>
            <span
              class="text-center text-black/40 text-sm font-normal font-['PingFang_SC'] leading-[26.98px]"
            >
              {{ it.label }}
            </span>
          </div>
          <div v-if="i < skills?.length - 1" class="leading-[26.98px] text-black/60">|</div>
        </template>
      </div>
      <div class="text-black/80 text-sm font-normal font-['PingFang_SC'] leading-normal">
        {{ designerInfo?.designDesc }}
      </div>
      <div
        v-if="isOwn || designerInfo?.videoNumber"
        class="bg-gradient-to-t from-[#fdf6ee] to-[#fefdfc] rounded-[10px] border border-[#fff4e6] border-solid flex items-center px-3.5 py-5 gap-3"
        @click="handle2Video"
      >
        <div>
          <div class="w-[37.01px] h-[37.01px] bg-[#fa9d3b] rounded-lg">
            <wd-img width="100%" height="100%" :src="wechatChannels"></wd-img>
          </div>
          <div
            v-if="isOwn && (designerInfo?.videoNumber ?? '') !== ''"
            @click.stop="handleUnbundle"
          >
            <div
              class="text-[#da7e1e] text-[9px] font-normal font-['PingFang_SC'] leading-normal flex items-center"
            >
              解绑
              <wd-icon name="arrow-right" size="12"></wd-icon>
            </div>
          </div>
        </div>
        <div class="flex-1">
          <div class="text-black/90 text-sm font-normal font-['PingFang SC'] leading-normal">
            {{ designerInfo?.videoNumber ? '个人视频号' : '视频号' }}
          </div>
          <div class="text-black/40 text-xs font-normal font-['PingFang SC'] leading-normal">
            {{
              designerInfo?.videoNumber
                ? '案例分享，打造专属生活美学空间'
                : '您还没有关联视频号 ， 快去关联吧~'
            }}
          </div>
        </div>
        <div>
          <div
            v-if="designerInfo?.videoNumber"
            class="text-[#e08e38] text-xs font-normal font-['PingFang SC'] leading-normal"
          >
            去看看
          </div>
          <div
            v-else
            class="h-7 px-4 py-0.5 bg-[#fa9d3b] rounded-[20px] justify-center items-center gap-2.5 inline-flex"
            @click.stop="router.push('/pages/mine/homepage/channels/index')"
          >
            <div
              class="text-center text-white text-xs font-normal font-['PingFang SC'] leading-normal"
            >
              去关联
            </div>
          </div>
        </div>
      </div>
      <div>
        <wd-tabs v-model="tab" custom-class="bg-transparent!">
          <template v-for="({ label, value }, index) in tabs" :key="index">
            <wd-tab :title="label" :name="value"></wd-tab>
          </template>
        </wd-tabs>
        <PageHelper
          ref="pageHelperRef"
          class="flex-grow flex flex-col bg-[#f6f6f6] mx--3.5"
          custom-class=""
          :request="getCircles"
          :query="query"
        >
          <template #default="{ source }">
            <div class="p-3.5 flex flex-col bg-[#f6f6f6] gap-3.5">
              <template v-for="it of source.list" :key="it.id">
                <view class="">
                  <MomentItem
                    :options="it"
                    :is-own="userInfo.userId === it.stylistId"
                    @delete="handleMomentDelete"
                    @like="handleLike"
                  ></MomentItem>
                </view>
              </template>
            </div>
          </template>
        </PageHelper>
      </div>
    </div>
    <BottomAppBar fixed placeholder>
      <div class="flex gap-7.5">
        <div class="flex-1" v-if="userInfo.userId === Number(id)">
          <wd-button block :round="false" @click="router.push(`/pages/mine/homepage/edit/index`)">
            编辑
          </wd-button>
        </div>
        <div class="flex-1" v-if="userInfo.userId === Number(id)">
          <wd-button block :round="false" open-type="share" data-type="homepage">分享</wd-button>
        </div>
        <div class="flex-1" v-if="userInfo.userId !== Number(id)">
          <wd-button
            block
            :round="false"
            @click="router.push(`/pages/mine/homepage/consult/index`)"
          >
            预约咨询
          </wd-button>
        </div>
      </div>
    </BottomAppBar>
  </div>
</template>
