<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 } from '../../core/libs/pngs'
import { integral, coupon, order, agent, setting, vip, scan } from '../../core/libs/svgs'
import {
  getDesignerInfo,
  getMemberUserInfo,
  getTasks,
  storeAndPunchIn,
  getAppMemberLevelConfigs,
  getCircleTaskStatus,
} from '../../core/libs/requests'
import { useUserStore } from '../../store'
import { storeToRefs } from 'pinia'
import { isEmpty } 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'

const router = useRouter()
const userStore = useUserStore()
const { isLogined, userInfo } = storeToRefs(userStore)
const { features } = usePermissions()
const { setUserInfo } = userStore
const { data, run } = useRequest(getMemberUserInfo)
const { data: taskData, run: getTaskData } = useRequest(() => getTasks({}), {
  initialData: { list: [] },
})
const { data: taskStatusData, run: setTaskStatus } = useRequest(
  async () => ({
    data: await Promise.all<any>([
      getCircleTaskStatus().then(({ data }) => ({
        completed: data,
        btnProps: {
          content: data ? '已完成' : '去发布',
          disabled: data,
          onClick: () => router.push('/pages/publish/moment/index?circleType=1'),
        },
      })),
      {
        btnProps: {
          content: '去打卡',
          onClick: () =>
            features.value.checkInAtStoreTask
              ? uni.showToast({ title: '请到店扫码完成', icon: 'none' })
              : router.push(`/pages/mine/authentication/index`),
        },
      },
      {
        btnProps: {
          content: '去邀请',
          onClick: () => router.push('/pages/mine/invite/index'),
        },
      },
      {
        btnProps: {
          content: '去关注',
          onClick: () => uni.showToast({ title: '敬请期待', icon: 'none' }),
        },
      },
    ]),
    code: 0,
    msg: '',
  }),
  { initialData: [] },
)
const { data: designerInfo, run: setDesignerInfo } = useRequest(
  () => getDesignerInfo(userInfo.value.userId),
  { initialData: {} },
)
const { data: levelConfigs, run: setLevelConfigs } = useRequest(() => getAppMemberLevelConfigs(), {
  initialData: [],
})
const menus = ref([
  { title: '积分明细', icon: integral, path: '/pages/mine/points/index' },
  { title: '优惠券包', icon: coupon, path: '/pages/mine/coupons/index' },
  { title: '我的订单', icon: order, path: '/pages/mine/orders/index' },
  { title: '专属客服', icon: agent, path: '/pages/mine/agents/index' },
  { title: '个人设置', icon: setting, path: '/pages/mine/setting/index' },
])
const levels = ref({
  1: {
    color: '#3b5369',
    bgImg:
      'https://image.zhuchaohui.com/zhucaohui/997de03a59d201c7b5dc124561925431abdc849cc7044ad4fb7c758bc12fafb2.png',
  },
  2: {
    color: '#3b5369',
    bgImg:
      'https://image.zhuchaohui.com/zhucaohui/77b6712b1cab7e769b630010be01eceec6cdd27f6947777b5a805e3cbf077db4.png',
  },
  3: {
    color: '#3b5369',
    bgImg:
      'https://image.zhuchaohui.com/zhucaohui/60811dfd5c5a4fa7502cfc2ff3db188849d4f9363849420ba72e32c03f20eca5.png',
  },
  4: {
    color: '#65341d',
    bgImg:
      'https://image.zhuchaohui.com/zhucaohui/236227e8094b50dafb21039c259b6fef9c9960a3347ae4286beddee23871e662.png',
  },
})
const pieces = ref([
  {
    title: '设计师成长计划',
    desc: '赋能设计共同成长',
    icon: designer,
    class: 'items-start! pb-0 pr-0',
    iconSize: 102,
    gridItemClass: 'col-start-1 row-start-1 row-end-3',
  },
  {
    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/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/login/index' })
}
const handleToAuthentication = () => {
  if (!isLogined.value) return router.push('/pages/login/index')
  router.push('/pages/mine/authentication/index')
}
const handleToHomepage = () => {
  uni.navigateTo({ url: '/pages/mine/homepage/index' })
}
const handleMenuClick = (path) => {
  path && router.push(path)
}
const handleClickScan = async () => {
  const { result } = await uni.scanCode({})
  console.log(result)
  // const a = qrCodeString2Object('WIFI:S:KM;T:WPA;P:km666888;H:false;;')
  // console.log(a)
  // console.log(toQrCodeString('到店', { a: 1, orderId: 2222 }))
  // console.log(qrCodeString2Object(toQrCodeString('到店', { a: 1, orderId: 2222 })))
  const { type, options } = qrCodeString2Object(result)
  if (type === QrCodeBusinessType.InStoreClockIn) {
    if (!features.value.checkInAtStoreTask) return router.push('/pages/mine/authentication/index')
    try {
      await storeAndPunchIn({ id: options.id })
      // await storeAndPunchIn({ id: 24 })
      router.push(`/pages/mine/scan/result/index?result=${result}`)
    } catch (e) {
      if (e.code === 1000) {
        router.push(
          `/pages/mine/scan/result/index?result=${toQrCodeString(type, { name: options.name, desc: e.msg })}`,
        )
      } else {
        uni.showToast({ title: e.msg, icon: 'none' })
      }
    }
    return
  }
  router.push(`/pages/mine/scan/result/index?result=${result}`)
}
const navBarProps = ref({ customClass: 'bg-transparent!' })
onMounted(async () => {
  await setLevelConfigs()
})
onShow(async () => {
  if (isLogined.value) {
    await run()
    setUserInfo({
      ...userInfo.value,
      ...data.value,
    })
    await Promise.all([setDesignerInfo(), getTaskData(), setTaskStatus()])
    console.log(taskStatusData.value)
  }
})
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 #left>
        <wd-button
          v-if="isLogined"
          type="text"
          size="small"
          custom-class="p-0!"
          :round="false"
          @click="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="ms-3.5 ml-3.5">
          <div
            class="text-white text-xl font-normal font-['PingFang_SC'] leading-normal"
            @click="nickNameClickHandle"
          >
            {{ !isLogined ? '请点击登录' : userInfo?.nickname }}
          </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/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">
          <wd-img custom-class="vertical-bottom" :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()"
          >
            <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-[#8FB8DB]']"
          :style="{
            backgroundImage: `url(${levels[userInfo.level?.level]?.bgImg})`,
            color: levels[userInfo.level?.level]?.color,
          }"
        >
          <div class="flex items-center">
            <div class="flex-1"></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="router.push('/pages/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">
                {{ 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>
      <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>
  </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);
  }
}
</style>
