<route lang="json5">
{ layout: 'tabbar', style: { navigationBarTitleText: '我的', navigationStyle: 'custom' } }
</route>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import CardMenu from '@/components/card-menu.vue'
import SectionHeading from '@/components/section-heading.vue'
import { designer, settled, treaty, vipBg, noEyes, eyes, referrerTwo } from '../../core/libs/pngs'
import { BannerMode } from '@/core/libs/models'
import { integral, coupon, order, agent, setting, vip, scan, close } from '../../core/libs/svgs'
import {
  getDesignerInfo,
  getMemberUserInfo,
  getTasks,
  storeAndPunchIn,
  getAppMemberLevelConfigs,
  getCircleTaskStatus,
  getHonorStatistics,
  getBanners,
} from '../../core/libs/requests'
import { useUserStore, useGlobalStore } from '../../store'
import { storeToRefs } from 'pinia'
import { isEmpty, set } from 'radash'
import TasksCard from './components/tasks-card.vue'
import { useRouter } from '../../core/utils/router'
import { NetImages } from '../../core/libs/net-images'
import { qrCodeString2Object, requestToast, toQrCodeString } from '../../core/utils/common'
import { QrCodeBusinessType } from '../../core/libs/enums'
import { usePermissions } from '../../composables/permissions'
import { AnalysisEventType, useAnalysis } from '@/composables/analysis'

const { option, report } = useAnalysis(false)
const official = ref(false)
const hidePoints = ref<boolean>(true)
const isPublish = ref<boolean>(false)
const router = useRouter()
const userStore = useUserStore()
const { isLogined, userInfo } = storeToRefs(userStore)
const { features, clickByPermission } = usePermissions()
const { setUserInfo } = userStore
const { data, run } = useRequest(getMemberUserInfo)
const { data: taskData, run: getTaskData } = useRequest(() => getTasks({}), {
  initialData: { list: [] },
})
const { setPublishState } = useGlobalStore()
const publishState = computed(() => useGlobalStore().publishState)
const tabbar$on = () => {
  setPublishState(true)
}
const { data: banners, run: setBanners } = useRequest(
  () => getBanners({ mode: BannerMode.StudyTour }),
  { initialData: [] },
)
const { data: taskStatusData, run: setTaskStatus } = useRequest(
  async () => ({
    data: await Promise.all<any>([
      getCircleTaskStatus().then(({ data }) => ({
        completed: data,
        btnProps: {
          content: data ? '已完成' : '去发布',
          disabled: data,
          onClick: () => tabbar$on(),
        },
      })),
      {
        btnProps: {
          content: '去打卡',
          onClick: () =>
            features.value.checkInAtStoreTask
              ? clickByPermission('scan', () => handleClickScan())
              : router.push(`/pages/mine/authentication/index`),
        },
      },
      {
        btnProps: {
          content: '去邀请',
          onClick: () => {
            console.log(userInfo.value.homePageUrl, 'userInfo.value.homePageUrl')
            userInfo.value.homePageUrl == null
              ? uni.showToast({ title: '请先配置个人主页全部信息', icon: 'none' })
              : router.push('/pages-sub/mine/invite/index')
          },
        },
      },
      {
        btnProps: {
          content: '去关注',
          // onClick: () => uni.showToast({ title: '敬请期待', icon: 'none' }),
          onClick: () =>
            uni.previewImage({
              urls: [
                'https://image.zhuchaohui.com/zhucaohui/de0f43be81ba577eda016a994ab203bb79149f09a7a919b7598ec2c0cb04c75d.png',
              ],
            }),
        },
      },
    ]),
    code: 0,
    msg: '',
  }),
  { initialData: [] },
)
const { data: designerInfo, run: setDesignerInfo } = useRequest(
  () => getDesignerInfo(userInfo.value.userId),
  { initialData: {} },
)
const { data: levelConfigs, run: setLevelConfigs } = useRequest(() => getAppMemberLevelConfigs(), {
  initialData: [],
})
const { data: statistics, run: setStatistics } = useRequest(() => getHonorStatistics())
const menus = ref([
  { title: '积分明细', icon: integral, path: '/pages-sub/mine/points/index' },
  { title: '优惠券包', icon: coupon, path: '/pages-sub/mine/coupons/index' },
  { title: '我的订单', icon: order, path: '/pages-sub/mine/orders/index' },
  { title: '专属客服', icon: agent, path: '/pages-sub/mine/agents/index' },
  { title: '个人设置', icon: setting, path: '/pages-sub/mine/setting/index' },
])
const pieces = ref([
  {
    title: '设计师成长计划',
    desc: '赋能设计共同成长',
    icon: 'https://image.zhuchaohui.com/zhucaohui/e5f83b3b61868838b0947290242488a0f51e308ca66182f8563c9a305129b119.png',
    class: 'items-start! pb-0 pr-0',
    iconSize: 102,
    gridItemClass: 'col-start-1 row-start-1 row-end-3',
    path: '/pages-sub/home/study-tour/list',
  },
  {
    title: '材料商入驻',
    desc: '提供优质材料商',
    icon: settled,
    class: 'flex-row! pb-0 pr-0',
    iconSize: 68,
    gridItemClass: 'col-start-2 row-start-1',
    path: '/pages/material/settled-in/index',
  },
  {
    title: '筑巢荟公约',
    desc: '共同遵守平台公约',
    icon: treaty,
    class: 'col-start-2 row-start-2 flex-row! pb-0',
    iconSize: 44,
    gridItemClass: 'col-start-2 row-start-2',
    path: '/pages-sub/mine/convention/index',
  },
])
const avatar = computed(() =>
  !isEmpty(userInfo.value.avatar) ? userInfo.value.avatar : NetImages.DefaultAvatar,
)
const certificationStatusText = computed(() => {
  if (!userInfo.value.userStatusEnabled) return '未认证'
  if (userInfo.value.userStatusEnabled && userInfo.value.userAuthStatus === 1) return '审核中'
  if (userInfo.value.userStatusEnabled && userInfo.value.userAuthStatus === 2) return '已驳回'
  return '通过'
})
const certificationBtnText = computed(
  () => ({ 0: '通过', 1: '审核中', 2: '已驳回' })[userInfo.value.userAuthStatus] || '去认证',
)
const isCertified = computed(
  () => userInfo.value.userStatusEnabled && userInfo.value.userAuthStatus === 0,
)
const nickNameClickHandle = async () => {
  if (isLogined.value) return
  uni.navigateTo({ url: '/pages-sub/login/index' })
}
const handleToAuthentication = (event) => {
  // 阻止事件冒泡
  event.stopPropagation()
  if (!isLogined.value){
	  router.push('/pages-sub/login/index')
  }else{
	  router.push('/pages-sub/mine/authentication/index')
  }
  
}
const handleToHomepage = () => {
  uni.navigateTo({ url: `/pages-sub/mine/homepage/index?id=${userInfo.value.userId}` })
}
const handleMenuClick = (path) => {
  path && router.push(path)
}
const handleClickScan = async () => {
  const { result } = await uni.scanCode({})
  console.log("result:" + result)
  const { type, options } = qrCodeString2Object(result)
  // console.log(type)
  if (type === QrCodeBusinessType.InStoreClockIn) {
    if (!features.value.checkInAtStoreTask)
      return router.push('/pages-sub/mine/authentication/index')
    try {
      await storeAndPunchIn({ id: options.id })
      option.value = {
        remark: `最近到店品牌: ${options.name}`,
      }
      await report(AnalysisEventType.ViewPage)
      // await storeAndPunchIn({ id: 24 })
      await router.push(`/pages-sub/mine/scan/result/index?result=${result}`)
    } catch (e) {
      if (e.code === 1000) {
        await router.push(
          `/pages-sub/mine/scan/result/index?result=${toQrCodeString(type, { name: options.name, desc: e.msg })}`,
        )
      } else {
        await uni.showToast({ title: e.msg, icon: 'none' })
      }
    }
    return
  }
  // console.log(options.path)
  if (type === QrCodeBusinessType.PagePath) {
    await router.push(options.path)
    return
  }
  await router.push(`/pages-sub/mine/scan/result/index?result=${result}`)
}
const navBarProps = ref({ customClass: 'bg-transparent!' })
onMounted(async () => {
  await setLevelConfigs()
  // 监听 tabbar 点击事件
  uni.$on('clickTabbar', (e) => {
    isPublish.value = e
  })
})
onShow(async () => {
	await setBanners()
	pieces.value[0].path = `/pages-sub/home/study-tour/list?designStudyAbroadYear=${banners.value[0].designStudyAbroadYear}&designDesc=${banners.value[0].designDesc}`
	console.log(pieces.value)
  if (isLogined.value) {
    await run()
    
    setUserInfo({
      ...userInfo.value,
      ...data.value,
    })
    await Promise.all([setDesignerInfo(), getTaskData(), setTaskStatus(), setStatistics()])    
  }
})
onPageScroll(({ scrollTop }: { scrollTop: number }) => {
  navBarProps.value.customClass = scrollTop === 0 ? 'bg-transparent!' : ''
})
</script>

<template>
  <view>
    <wd-navbar
      fixed
      safeAreaInsetTop
      custom-class="bg-transparent!"
      :bordered="false"
      v-bind="navBarProps"
    >
      <template v-if="!publishState" #left>
        <wd-button
          v-if="isLogined"
          type="text"
          size="small"
          custom-class="p-0!"
          :round="false"
          @click="clickByPermission('scan', () => handleClickScan())"
        >
          <wd-img width="25" height="25" :src="scan" custom-class="vertical-bottom"></wd-img>
        </wd-button>
      </template>
    </wd-navbar>
    <div
      class="bg-black/30 flex flex-col justify-end box-border bg-[url(https://image.zhuchaohui.com/zhucaohui/c706ec14a5a927c10e9e1fa0153affb11bbdd9255882e18c67ee82687ff9813a.png)] bg-[length:100%_auto]"
      :class="[isCertified ? 'aspect-[0.94/1] pb-44' : 'aspect-[1.15/1] pb-20']"
    >
      <div class="my-6.5 px-3.5 flex">
        <!-- <img class="w-[72px] h-[72px] rounded-full border border-white" :src="avatar" /> -->
        <div class="relative">
          <wd-img
            custom-class="rounded-full border border-white overflow-hidden"
            :width="72"
            :height="72"
            :src="avatar"
          ></wd-img>
          <wd-img
            v-if="userInfo?.level"
            custom-class="absolute! level-circle"
            :width="79"
            :height="80"
            :src="userInfo?.level?.avatar"
          ></wd-img>
        </div>
        <div class="ms-3.5 ml-3.5">
          <div class="flex items-center gap-1.25">
            <div
              class="text-white text-xl font-normal font-['PingFang_SC'] leading-normal"
              @click="nickNameClickHandle"
            >
              {{ !isLogined ? '请点击登录' : userInfo?.nickname }}
            </div>
            <div v-if="isCertified">
              <div
                class="w-[76px] h-6 relative"
                @click="router.push(`/pages-sub/mine/honors/index?id=${userInfo?.userId}`)"
              >
                <div
                  class="w-[76px] h-[18px] left-3 pl-1 top-[1.5px] absolute bg-[#4f4b42] rounded-[3px] border border-solid border-[#a89f89]"
                >
                  <div
                    class="text-center text-[#f2e3c4] text-xs font-normal font-['PingFang_SC'] leading-normal"
                  >
                    荣誉徽章:{{ statistics?.badgeCount }}
                  </div>
                </div>
                <wd-img width="23" height="23" :src="NetImages.HonorsLogo"></wd-img>
              </div>
            </div>
          </div>
          <div
            v-if="!isCertified"
            class="mt-2 w-[63px] h-[26px] bg-black/10 rounded-[20px] border border-white/60 flex items-center justify-center"
          >
            <div
              class="text-center text-white text-xs font-normal font-['PingFang_SC'] leading-normal"
            >
              <!-- 未认证 -->
              {{ certificationStatusText }}
            </div>
          </div>
          <div v-if="isCertified" class="flex items-center text-white" @click="handleToHomepage">
            <div
              class="text-center text-white text-sm font-normal font-['PingFang_SC'] leading-normal"
            >
              个人主页
            </div>
            <wd-icon name="arrow-right"></wd-icon>
          </div>
        </div>
      </div>
      <div
        class="px-3.5 flex items-center"
        @click="router.push('/pages-sub/mine/homepage/statistics/index')"
      >
        <div class="flex items-center">
          <div class="text-white text-base font-normal font-['PingFang_SC'] leading-normal mr-1">
            <!-- 0 -->
            {{ designerInfo?.shareCount || 0 }}
          </div>
          <div
            class="text-center text-[#e9e7e4] text-xs font-normal font-['PingFang_SC'] leading-normal"
          >
            分享
          </div>
        </div>

        <div class="h-4 w-[2px] mx-4 bg-[#e9e7e4]"></div>

        <div class="flex items-center">
          <div class="text-white text-base font-normal font-['PingFang_SC'] leading-normal mr-1">
            <!-- 0 -->
            {{ designerInfo?.viewCount || 0 }}
          </div>
          <div
            class="text-center text-[#e9e7e4] text-xs font-normal font-['PingFang_SC'] leading-normal"
          >
            浏览
          </div>
        </div>

        <div class="h-4 w-[2px] mx-4 bg-[#e9e7e4]"></div>

        <div class="flex items-center">
          <div class="text-white text-base font-normal font-['PingFang_SC'] leading-normal mr-1">
            <!-- 0 -->
            <!-- {{designerInfo.c}} -->
            {{ designerInfo?.winCustomerCount || 0 }}
          </div>
          <div
            class="text-center text-[#e9e7e4] text-xs font-normal font-['PingFang_SC'] leading-normal"
          >
            获客
          </div>
        </div>
      </div>
    </div>
    <div class="relative top--18" v-if="!isCertified">
      <div class="mx-3.5 box-border absolute left-0 right-0 top-0">
        <wd-img :src="vipBg" width="100%" mode="widthFix"></wd-img>
      </div>
      <div class="mx-3.5 box-border absolute left-0 right-0 top-0 p-3.5">
        <div class="flex items-center" @click="router.push('/pages-sub/mine/levels/index')">
          <wd-img :src="vip" width="35" mode="widthFix"></wd-img>
          <div
            class="ml-2 text-center text-[#faeac6] text-sm font-normal font-['PingFang_SC'] leading-normal"
          >
            查看会员等级权益
          </div>
          <div class="flex-1"></div>
          <div
            class="w-[83px] h-[29px] bg-gradient-to-l from-[#ffdab6] to-[#ffebd5] rounded-[30px] flex items-center justify-center"
            @click="handleToAuthentication($event)"
          >
            <div
              class="text-[#9e5934] text-[13px] font-normal font-['PingFang_SC'] leading-relaxed flex items-center gap-1"
            >
              <!-- 去认证 -->
              <!-- {{ !isCertified ? '去认证' : certificationStatusText }} -->
              {{ certificationBtnText }}
              <div
                class="w-3.5 h-3.5 bg-gradient-to-tl from-[#773b19] to-[#9e5a34] rounded-full flex items-center justify-center"
              >
                <wd-icon name="play" size="12" color="#ffead2"></wd-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template v-else>
      <div class="relative top--36">
        <div
          class="mx-3.5 absolute left-0 right-0 top--4 aspect-[1.93/1] rounded-2.5 p-3.5 box-border bg-[length:100%]"
          :class="['text-[#65341d]']"
          :style="{
            // backgroundImage: `url(${levels[userInfo.level?.level]?.bgImg})`,
            // color: levels[userInfo.level?.level]?.color,
            backgroundImage: `url(${userInfo.level?.icon})`,
          }"
        >
          <div class="flex items-center">
            <div class="flex-1"></div>
			<div class="mr-[140rpx] pt-[10px]" @click="hidePoints= !hidePoints">
				<wd-img :src="hidePoints?noEyes:eyes" width="20" height="20"></wd-img>
			</div>
            <div
              class="bg-gradient-to-r from-[#333333] to-[#20201e] rounded-tl-[20px] rounded-bl-[20px] mr--3.5 px-2 mt-3"
              @click.stop="router.push('/pages-sub/mine/levels/index')"
            >
              <div class="text-xs font-normal font-['PingFang_SC'] leading-relaxed color-[#f3f3f3]">
                更多等级权益
              </div>
            </div>			
          </div>
          <div class="flex items-end mt-10">
            <div>
              <span class="text-4xl font-normal font-['D-DIN_Exp'] mr-1">
                {{ hidePoints?"****":userInfo.level?.point }}
              </span>
              <span class="text-center text-xs font-normal font-['PingFang_SC']">积分</span>
            </div>
            <div class="flex-1"></div>
            <div class="text-sm font-normal font-['PingFang_SC']">
              会员号：{{ userInfo.level?.cardCode }}
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="relative h-4 box-border bg-transparent rounded-b-[50%] z-1"></div> -->
    </template>
    <view
      class="relative bottom-4 py-1 px-3.5"
      :class="[
        userInfo.userStatusEnabled
          ? 'bg-[url(https://image.zhuchaohui.com/zhucaohui/f12b86304c84eec692f4c8f040a06c63fe7110359b8a4a1262b97b1eef6b605c.png)] bg-[length:100%]'
          : 'bg-neutral-100 rounded-t-2xl',
      ]"
    >
      <div class="flex justify-around my-6">
        <template v-for="({ title, icon, path }, i) in menus" :key="i">
          <div class="flex flex-col items-center" @click="handleMenuClick(path)">
            <div class="relative flex-col justify-start items-start inline-flex">
              <wd-img :src="icon" width="24" height="24" custom-class="vertical-bottom"></wd-img>
            </div>
            <div
              class="mt-2 text-black/90 text-[12.86px] font-normal font-['PingFang_SC'] leading-relaxed"
            >
              {{ title }}
            </div>
          </div>
        </template>
      </div>
	  <div @click="router.push('/pages-sub/mine/refferrer/index')" class="flex items-center px-[30rpx] py-[40rpx] bg-white mb-[20rpx] rounded-[32rpx]" v-if="isLogined">
		  <wd-img width="44" height="44" :src="referrerTwo"></wd-img>
		  <div class="flex-grow ml-[20rpx]">
			  <div class="text-[32rpx]">引荐设计师赚积分</div>
			  <div class="text-[24rpx] text-black/40">邀请新设计师可得积分奖励</div>
		  </div>
		  <div class="bg-black rounded-[8rpx] text-white text-[24rpx] w-[134rpx] h-[56rpx] text-center line-height-[56rpx]">立即查看</div>
	  </div>
      <TasksCard
        v-if="isLogined"
        custom-class="my-6"
        :items="
          taskData.list.map((it, i) => ({
            ...it,
            ...(taskStatusData[i] || {}),
          }))
        "
      ></TasksCard>
      <SectionHeading custom-class="my-6" title="和筑巢荟一起共同成长"></SectionHeading>
      <CardMenu :items="pieces" custom-class="grid-cols-2" />
    </view>
    <!-- <wd-overlay :show="official" @click="official = false">
		<view class="wrapper" @click.stop="">
		    <wd-img :width="'100%'" :height="'100%'" src="https://image.zhuchaohui.com/zhucaohui/de0f43be81ba577eda016a994ab203bb79149f09a7a919b7598ec2c0cb04c75d.png" mode="widthFix"></wd-img>
			<wd-img @click="official = false" :src="close" width="28" height="28" custom-class="vertical-bottom"></wd-img>
		</view>
	</wd-overlay> -->
  </view>
</template>

<style scoped lang="scss">
.uni-button:after {
  position: '' bsolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  content: '';
  background: #03f463;
  transform: skewX(15deg);
}
.aaaa {
  &::before {
    position: '' bsolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    content: '';
    background: #03f463;
    transform: skewX(15deg);
  }
}
.wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 540rpx;
  transform: translate(-50%, -50%);
}
:deep(.vertical-bottom) {
  left: 50%;
  transform: translateX(-50%);
}
:deep(.level-circle) {
  top: -18rpx;
  left: -10rpx;
}
</style>
