<script setup>
definePage({
  layout: 'HomeLayout',
  style: {
    navigationBarTitleText: '推广',
    navigationStyle: 'custom',
  },
})

import { ref, computed, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import SectionTitle from '@/components/SectionTitle.vue'
import { useAgentStore } from '@/stores/agentStore'
import { useUserStore } from '@/stores/userStore'
import { getProductConfig } from '@/api/agent'
import { getShareAppMessageOptions, getShareTimelineOptions } from '@/composables/useWechatShare'

const agentStore = useAgentStore()
const userStore = useUserStore()
const { isAgent } = storeToRefs(agentStore)
const { isLoggedIn, mobile } = storeToRefs(userStore)

function toInquire(name) {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.navigateTo({ url: `/pages/promote/report?feature=${encodeURIComponent(name)}` })
}

function toInvitation() {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.navigateTo({ url: '/pages/invitation/index' })
}

function toPromote() {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.navigateTo({ url: '/pages/promote/report' })
}

function toHelp() {
  uni.navigateTo({ url: '/pages/agentSystemGuide/index' })
}

function toHistory() {
  uni.navigateTo({ url: '/pages/historyQuery/index' })
}

function toAgent() {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.switchTab({ url: '/pages/agent/index' })
}

function toWithdraw() {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.navigateTo({ url: '/pages/withdraw/index' })
}

function toTeamList() {
  if (!isAgent.value) {
    if (!isLoggedIn.value) {
      uni.showToast({ title: '正在登录中，请稍候', icon: 'none' })
      return
    } else {
      uni.showToast({ title: '请先注册成为代理', icon: 'none' })
      uni.navigateTo({ url: `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}` })
    }
    return
  }
  uni.navigateTo({ url: '/pages/teamList/index' })
}

function toService() {
  uni.navigateTo({ url: '/pages/service/index' })
}

const services = ref([
  { name: 'riskassessment', title: '个人大数据', subtitle: '个人信用 精准查询', bg: '/static/promote/personal_data_bg.png', goColor: '#6699ff', costPrice: null },
  { name: 'marriage', title: '情侣报告', subtitle: '相信才能相依 相爱才能永久', bg: '/static/promote/marriage_risk_bg.png', goColor: '#ff99cc', costPrice: null },
  { name: 'backgroundcheck', title: '入职背调', subtitle: '查询便可 慧眼识英雄', bg: '/static/promote/backgroundcheck_bg.png', goColor: '#7db3ff', costPrice: null },
  { name: 'companyinfo', title: '企业大数据', subtitle: '信任是合作 永恒的基石', bg: '/static/promote/company_bg.png', goColor: '#ffaa66', costPrice: null },
  { name: 'homeservice', title: '家政报告', subtitle: '口碑与能力 一查便知', bg: '/static/promote/housekeeping_risk_bg.png', goColor: '#66cccc', costPrice: null },
  { name: 'consumerFinanceReport', title: '消金报告', subtitle: '', bg: '/static/promote/consumer_finance_report_bg.png', goColor: '#a259ff', costPrice: null },
])

const allServices = computed(() => services.value)

function getCostPriceText(service) {
  if (isLoggedIn.value && isAgent.value && service.costPrice) return `成本价 ${service.costPrice}￥`
  if (!isLoggedIn.value) return '登录查看'
  if (!isAgent.value) return '成为代理查看'
  return '成本价 --'
}

async function fetchProductConfig() {
  const token = typeof uni !== 'undefined' && uni.getStorageSync ? uni.getStorageSync('token') : ''
  if (!token) return
  try {
    const { data, error } = await getProductConfig()
    if (data.value && !error.value && data.value.code === 200) {
      const list = data.value.data?.list || []
      services.value.forEach((s) => {
        const config = list.find((item) => item.product_en === s.name)
        if (config?.actual_base_price != null) s.costPrice = parseFloat(config.actual_base_price).toFixed(2)
      })
    }
  } catch (e) {
    console.error(e)
  }
}

onMounted(() => {})
watch([isLoggedIn, isAgent], ([loggedIn, agent]) => {
  if (loggedIn && agent) fetchProductConfig()
}, { immediate: true })

// 推广页头图（单图，已去掉轮播）
const bannerImage = '/static/promote/banner_1.png'

// 微信分享：分享给好友
onShareAppMessage(() => {
  return getShareAppMessageOptions({ path: 'pages/promote/index' })
})

// 微信分享：分享到朋友圈
onShareTimeline(() => {
  return getShareTimelineOptions({ query: 'from=timeline' })
})
</script>

<template>
  <view class="box-border from-blue-100 to-white bg-gradient-to-b">
    <view class="relative" @click="toPromote">
      <image :src="bannerImage" class="w-full block" mode="widthFix" />
    </view>
    <view class="px-6 mt-4">
      <view class="grid grid-cols-4 gap-3">
        <view class="text-center flex flex-col justify-center items-center" @click="toPromote">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/tgbg.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">推广报告</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toInvitation">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/yqxj.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">邀请下级</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toHelp">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/bzzx.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">帮助中心</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toHistory">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/wdbg.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">我的报告</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toAgent">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/zc.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">资产</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toWithdraw">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/wytx.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">我要提现</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toTeamList">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/wdxj.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">我的团队</view>
        </view>
        <view class="text-center flex flex-col justify-center items-center" @click="toService">
          <view class="h-14 w-14 bg-gradient-to-b from-white to-blue-100/10 rounded-full shadow-lg flex items-center justify-center">
            <image src="/static/promote/zxkf.png" class="h-14 w-14" mode="aspectFit" />
          </view>
          <view class="text-center mt-1 font-bold text-sm">在线客服</view>
        </view>
      </view>
    </view>
    <view class="my-2 mx-4 rounded-xl overflow-hidden shadow-xl" @click="toInvitation">
      <image src="/static/promote/tghb.png" class="w-full block" mode="widthFix" />
    </view>
    <view class="flex items-center justify-between mx-4 mb-2">
      <SectionTitle title="推广服务" />
      <view class="text-xs text-gray-500 flex items-center gap-1.5">
        <text>‹</text>
        <text>滑动查看更多</text>
        <text>›</text>
      </view>
    </view>
    <view class="relative p-4 pt-0">
      <scroll-view scroll-x class="services-scroll-container" :show-scrollbar="false">
        <view class="services-scroll-wrapper">
          <view
            v-for="(service, index) in allServices"
            :key="index"
            class="relative flex flex-col px-4 py-2 rounded-xl shadow service-card"
            :style="`background: url(${service.bg}) no-repeat; background-size: contain; background-position: center;`"
            @click="toInquire(service.name)"
          >
            <view class="flex flex-col items-start flex-1">
              <view class="mt-1 text-left text-gray-600 font-bold">{{ service.title }}</view>
              <view
                class="mt-2 rounded-lg px-2 py-1 text-xs text-white w-max flex items-center"
                :style="`background-color: ${service.goColor}`"
              >
                立即推广
                <image src="/static/index/go_icon.png" class="ml-0.5 h-3 w-3 inline-block" mode="aspectFit" />
              </view>
            </view>
            <view class="absolute bottom-0 left-0 right-0 rounded-b-xl px-2 py-1 text-xs text-white text-center">
              {{ getCostPriceText(service) }}
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<style scoped>
.services-scroll-container {
  white-space: nowrap;
  padding-bottom: 0.5rem;
}
.services-scroll-wrapper {
  display: inline-flex;
  gap: 1rem;
  padding-right: 1rem;
}
.service-card {
  width: 120px;
  height: 120px;
  flex-shrink: 0;
  display: inline-block;
}
</style>
