<script setup lang="ts">
import planetBg from '@/assets/img/planetBg.png'
import { X } from 'lucide-vue-next'
import { NConfigProvider, NImage, NMessageProvider } from 'naive-ui'
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const route = useRoute()
const router = useRouter()

// 从 history state 中获取参数
const params = ref({
  communityId: '',
  tenantId: '',
  userId: '',
})
// const goldPaymentRef = ref(null)

onMounted(() => {
  const state = history.state
  if (state && state.communityId && state.tenantId) {
    params.value = {
      communityId: state.communityId,
      tenantId: state.tenantId,
      userId: state.userId,
    }
  }
  else {
    // 如果没有 state，回退到 URL 参数
    params.value = {
      communityId: route.query.communityId as string,
      tenantId: route.query.tenantId as string,
      userId: route.query.userId as string,
    }
  }
  getCommunityDetail()
  getUserInfo()
  getAttention()
})

const userStore = useUserStore()
definePageMeta({
  layout: 'planet',
})

const communityDetail = ref({})
async function getCommunityDetail() {
  try {
    const res = await request.get(`/community/detail?communityId=${params.value.communityId}&tenantId=${params.value.tenantId}`)
    if (res.code === 200) {
      communityDetail.value = res.data
    }
  }
  catch (error) {
    console.error(error)
  }
}

// 获取用户信息
const userInfo = ref({})
async function getUserInfo() {
  try {
    const res = await request.get(
      `/system/user/selectUserById?id=${params.value.userId}`,
    )
    if (res.code === 200) {
      userInfo.value = res.data
    }
  }
  catch (error) {
    console.log(error)
  }
}

// 获取关注粉丝点赞
const selectUserInfo = ref({})
async function getAttention() {
  try {
    const res = await request.get(`/attention/selectUserInfo?userId=${params.value.userId}`)
    if (res.code === 200) {
      selectUserInfo.value = res.data
    }
  }
  catch (err) {
    console.log(err)
  }
}
// const isShowGoldPayment = ref(false)
const paymentModal = ref(false)

// 确认充值弹框
const showConfirmModal = ref(false)
function onPositiveClick() {
  showConfirmModal.value = false
  paymentModal.value = true
  getQrCode()
}
function onNegativeClick() {
  showConfirmModal.value = false
}

const formRef = ref(null)
const paymentParams = ref({
  amount: 10,
  type: 'wallet',
})
const amount = ref(10)

const qrUrl = ref('')

// 初始化获取支付二维码
const paymentStatus = ref(1)
const isJoinModal = ref(false)
async function handleJoin() {
  isJoinModal.value = true
}

async function onPositiveJoinClick() {
  try {
    const data = {
      communityId: params.value.communityId,
      tenantId: params.value.tenantId,
    }
    const res = await request.post(`/community/join`, data)
    if (res.code === 200) {
      isJoinModal.value = false
      message.success('加入成功')
      setTimeout(() => {
        router.push(`/planet-detail?communityId=${params.value.communityId}&tenantId=${params.value.tenantId}`)
      }, 1000)
    }
  }
  catch (err: any) {
    if (err.code === 12202 && err.msg === '钱包余额不足，请充值') {
      showConfirmModal.value = true
    }
  }
}

function onNegativeJoinClick() {
  isJoinModal.value = false
}

function closePayment() {
  paymentModal.value = false
}
let pollingTimer: ReturnType<typeof setInterval> | undefined

async function getQrCode() {
  try {
    paymentParams.value.amount = amount.value
    const res = await request.post(`/ali/pay/doPay`, paymentParams.value)
    if (res.code === 200) {
      paymentStatus.value = 1
      qrUrl.value = res.data.url
      pollingTimer && clearTimeout(pollingTimer)
      pollingTimer = setInterval(async () => {
        try {
          const res2 = await request.get(`/order/queryTradeStatus?outTradeNo=${res.data.orderNo}`)
          if (res2.data === 2) { // 1代支付 2支付成功 4超时
            paymentStatus.value = 2
            clearTimeout(pollingTimer)
            paymentModal.value = false
            message.success('支付成功!')
          }
          else if (res2.data === 4) {
            paymentStatus.value = 4
            clearTimeout(pollingTimer)
          }
        }
        catch (err) {
          console.log('object', err)
        }
      }, 2000)
    }
  }
  catch (err) {
    console.log(err)
  }
}
// 支付成功后刷新会员信息
// function paymentSuccess() {
//   // getIsMember();
//   if (import.meta.client) {
//     window.location.reload()
//   }
// }

// function closeGoldPayment() {
//   isShowGoldPayment.value = false
//   if (goldPaymentRef.value) {
//     goldPaymentRef.value.isVisible = false
//   }
// }

// // 是否是会员
// const isMember = ref(false)
// async function getIsMember() {
//   try {
//     const res = await request.get('/member/isMember')
//     if (res.code === 200) {
//       isMember.value = res.data
//     }
//   }
//   catch (err) {
//     console.log(err)
//   }
// }
// getIsMember()
// 获取关注
// async function getAttention() {
//   try {
//     const res = await request.get('/attention/selectUserInfo')
//     if (res.code === 200) {
//       selectUserInfo.value = res.data
//     }
//   }
//   catch (err) {
//     console.error(err)
//   }
// }
// getAttention()
</script>

<template>
  <div class="min-h-screen bg-[#F7F8FA]">
    <div class="relative">
      <!-- 背景图片区域 -->
      <div class="h-[300px] w-full bg-[#E8F3FF]">
        <img :src="planetBg" alt="背景图片" class="w-full h-full object-cover">
      </div>

      <!-- 主要内容区域 -->
      <div class="absolute inset-x-0 top-[30px]">
        <div class="max-w-[1140px] mx-auto">
          <!-- 用户基本信息 -->
          <client-only>
            <div class="flex items-center gap-4 mb-6">
              <img :src="communityDetail.imageUrl" class="w-[224px] h-[224px] rounded" alt="头像">
              <div class="flex flex-col justify-between h-[224px] w-full">
                <div class="flex flex-col gap-3">
                  <div class="text-[20px] font-medium text-[#192029]">
                    {{ communityDetail.communityName }}
                  </div>
                  <div class="text-[14px] text-[#878d95]">
                    最新更新时间: {{ communityDetail.lastUpdateTime }}
                  </div>
                  <div class="text-[14px] flex gap-8">
                    <div class="flex items-center gap-3">
                      <img v-for="(item, index) in communityDetail.avatarList" :key="index" :src="item" class="w-[20px] h-[20px] rounded-full" alt="头像">
                      <div>
                        成员数量: {{ communityDetail.userNum }}
                      </div>
                    </div>
                    <div>
                      累计更新内容: {{ communityDetail.updateNum }}
                    </div>
                    <div>
                      星球创建天数: {{ communityDetail.createDay }}
                    </div>
                  </div>
                </div>

                <div class="flex justify-between p-2 rounded bg-white  items-center">
                  <div class="flex items-center gap-2 text-[#fc4141]">
                    <span class="font-bold text-[28px]">{{ communityDetail.price ? communityDetail.price : '免费' }}</span>  <span v-if="communityDetail.price" class="text-[16px]">金币</span>
                  </div>
                  <div
                    class="text-white text-[14px] flex items-center justify-center cursor-pointer w-[128px] h-[40px] bg-[linear-gradient(207deg,#3BEDFF_0%,#328AFE_100%)] rounded-lg"
                    @click="handleJoin"
                  >
                    立即加入
                  </div>
                </div>
              </div>
            </div>
          </client-only>
          <div class="max-w-[1140px] mx-auto bg-white rounded-lg p-4">
            <div class="text-[20px] pb-4">
              星球概况
            </div>
            <div class="flex gap-4 bg-[#F9FBFF] rounded-lg p-2">
              <div class="w-[80px] h-[80px] rounded">
                <img class="rounded-full w-full h-full object-cover" :src="userInfo.avatar" alt="星球概况">
              </div>
              <div class="flex flex-col justify-between py-2">
                <div class="flex gap-4">
                  <div class="text-[20px] font-medium text-[#192029]">
                    {{ userInfo.nickName }}
                  </div>
                  <!-- <div>
                关注
              </div> -->
                </div>
                <div class="flex gap-4">
                  <div>{{ selectUserInfo.bean }}粉丝</div>
                  <div>{{ selectUserInfo.attention }}关注</div>
                  <div>{{ Number(selectUserInfo.imageLikeNum) + Number(selectUserInfo.modelLikeNum) }}获赞</div>
                </div>
              </div>
            </div>
            <div class="text-[16px] text-[#4a5563] my-5">
              {{ communityDetail.description }}
            </div>
            <div>
              <div class="font-bold text-[20px]">
                付费通知
              </div>
              <div class="bg-[#F9FBFF] rounded-lg p-4 mt-2">
                <div>1、付费后，你可以使用当前付款的帐号在有效期内查看、参与内容互动，向星主、群成员提问。 </div>
                <div>2、本星球由星主自行创建，加入前请确认风险，平台不提供相关保证。若发现违反法律法规的星球，请勿加入，并投诉。</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <NConfigProvider>
      <NMessageProvider>
        <GoldPayment
          v-if="isShowGoldPayment"
          ref="goldPaymentRef"
          :is-member="isMember"
          @payment-success="paymentSuccess"
          @close-payment="closeGoldPayment"
        />
      </NMessageProvider>
    </NConfigProvider> -->
    <n-modal
      v-model:show="showConfirmModal"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      content="余额不足，是否确认充值？"
      positive-text="确认"
      negative-text="算了"
      @positive-click="onPositiveClick"
      @negative-click="onNegativeClick"
    />

    <n-modal
      v-model:show="paymentModal"
      :preset="null"
      :mask-closable="false"
      transform-origin="center"
      class="custom-modal"
    >
      <div class="bg-white rounded-xl w-200 p-4">
        <X class="absolute top-1 right-1 cursor-pointer" @click="closePayment" />
        <div class="mb-4 mt-6 flex">
          <n-form
            ref="formRef"
            :label-width="80"
            :model="paymentParams"
            size="large"
            label-placement="left"
            style="width: 240px"
          >
            <n-form-item label="输入金币" path="modelProduct.modelName">
              <n-input v-model:value="amount" type="number" placeholder="输入积分" />
            </n-form-item>
          </n-form>
          <n-button type="primary" class="mt-1 ml-2" @click="getQrCode">
            确定
          </n-button>
        </div>
        <div class="flex justify-center items-center my-4">
          <div class="w-30 h-30 flex justify-center items-center relative">
            <n-qr-code :value="qrUrl" :size="90" style="padding: 0;" />
            <div v-if="paymentStatus === 4" class="absolute top-0 left-0 w-full h-full flex cursor-pointer flex-col justify-center items-center bg-opacity-50 bg-black text-white" @click="getQrCode">
              请点击刷新<RotateCcw />
            </div>
          </div>
          <div class="flex justify-center ml-2 flex-col pb-[14px]">
            <div class="flex items-baseline">
              <div class="text-[#222] font-medium mr-1">
                支付
              </div>
              <div class="text-[#814600] mr-1">
                <span class="text-[16px] mr-1">¥</span>
                <span class="text-[40px]">{{ paymentParams.amount }}</span>
              </div>
            </div>
            <div class="flex items-center mb-1">
              <img src="@/assets/img/alipay.png" class="mr-1"> 请扫码完成支付
            </div>
            <div class="text-[12px]">
              <span class="text-[#999]">
                开通即代表同意
              </span>
              <span class="text-[#814600]">
                《魔创未来会员协议》
              </span>
            </div>
          </div>
        </div>
      </div>
    </n-modal>
    <!-- 是否加入弹框 -->
    <n-modal
      v-model:show="isJoinModal"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      content="是否确认加入星球？"
      positive-text="确认"
      negative-text="算了"
      @positive-click="onPositiveJoinClick"
      @negative-click="onNegativeJoinClick"
    />
  </div>
</template>

<style lang="scss" scoped>
.member-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 16.66%;
  height: 40px;
  border: 1px solid #f0f0f0;
  font-size: 12px;
  font-weight: 400;
  margin-right: -1px;
  margin-bottom: -1px;
}
</style>
