<template>
  <view class="min-h-screen bg-[#D1D6FF]">
    <image src="/static/image/invitation_agent_apply.png" alt="邀请代理申请" mode="widthFix" class="w-full" />

    <!-- 统一状态处理容器 -->
    <view class="flex flex-col items-center justify-center">
      <!-- 审核中状态 -->
      <view v-if="displayStatus === 0" class="text-center">
        <text class="text-xs text-gray-500 block">您的申请正在审核中</text>
        <view class="bg-gray-200 p-1 rounded-3xl shadow-xl mt-1">
          <view class="text-xl font-bold px-8 py-2 bg-gray-400 text-white rounded-3xl shadow-lg cursor-not-allowed">
            审核进行中
          </view>
        </view>
      </view>

      <!-- 审核通过状态 -->
      <view v-if="displayStatus === 1" class="text-center">
        <text class="text-xs text-gray-500 block">您已成为认证代理方</text>
        <view class="bg-green-100 p-1 rounded-3xl shadow-xl mt-1" @click="goToHome">
          <view
            class="text-xl font-bold px-8 py-2 bg-gradient-to-t from-green-500 to-green-300 text-white rounded-3xl shadow-lg cursor-pointer">
            进入应用首页
          </view>
        </view>
      </view>

      <!-- 审核未通过状态 -->
      <view v-if="displayStatus === 2" class="text-center">
        <text class="text-xs text-red-500 block">审核未通过，请重新提交</text>
        <view class="bg-red-100 p-1 rounded-3xl shadow-xl mt-1" @click="agentApply">
          <view
            class="text-xl font-bold px-8 py-2 bg-gradient-to-t from-red-500 to-red-300 text-white rounded-3xl shadow-lg cursor-pointer">
            重新提交申请
          </view>
        </view>
      </view>

      <!-- 未申请状态（包含邀请状态） -->
      <view v-if="displayStatus === 3" class="text-center">
        <text class="text-xs text-gray-500 block">{{ isSelf ? '立即申请成为代理人' : '邀您注册代理人' }}</text>
        <view class="bg-gray-100 p-1 rounded-3xl shadow-xl mt-1" @click="agentApply">
          <view
            class="text-xl font-bold px-8 py-2 bg-gradient-to-t from-blue-500 to-blue-300 text-white rounded-3xl shadow-lg cursor-pointer">
            立即成为代理方
          </view>
        </view>
      </view>
    </view>

    <AgentApplicationForm v-model:show="showApplyPopup" @submit="submitApplication" @close="showApplyPopup = false"
      :ancestor="ancestor" />
  </view>
</template>

<script setup>
import { ref, computed, onBeforeMount } from 'vue'
import { getAgentInfo, applyAgent } from '@/apis/agent'
import AgentApplicationForm from '@/components/AgentApplicationForm.vue'

const showApplyPopup = ref(false)
const status = ref(3) // 默认为未申请状态
const ancestor = ref("")
const isSelf = ref(true)
let intervalId = null // 保存定时器 ID

// 计算显示状态（当isSelf为false时强制显示为3）
const displayStatus = computed(() => {
  return !isSelf.value ? 3 : status.value
})

// 打开申请表单
const agentApply = () => {
  showApplyPopup.value = true
}

// 跳转到首页
const goToHome = () => {
  clearInterval(intervalId)
  uni.switchTab({
    url: '/pages/index'
  })
}

const getAgentInformation = async () => {
  const token = uni.getStorageSync("token")
  if (!token) {
    return
  }

  try {
    const res = await getAgentInfo()
    if (res.code === 200 && res.data) {
      // 将代理信息存入缓存
      uni.setStorageSync("agentInfo", {
        level: res.data.level,
        isAgent: res.data.is_agent, // 判断是否是代理
        status: res.data.status, // 获取代理状态 0=待审核，1=审核通过，2=审核未通过，3=未申请
        agentID: res.data.agent_id,
        mobile: res.data.mobile,
        isRealName: res.data.is_real_name,
        expiryTime: res.data.expiry_time
      })
      status.value = res.data.status
      console.log('代理信息已获取并存入缓存')
    }
  } catch (error) {
    console.error('获取代理信息失败', error)
  }
}
// 提交代理申请
const submitApplication = async (formData) => {
  try {
    const { region, mobile, wechat_id, code } = formData
    let postData = {
      region,
      mobile,
      wechat_id,
      code,
    }

    if (!isSelf.value) {
      postData.ancestor = ancestor.value
    }

    const res = await applyAgent(postData)

    if (res.code === 200) {
      showApplyPopup.value = false
      uni.showToast({
        title: "已提交申请",
        icon: 'success'
      })

      if (res.data.accessToken) {
        uni.setStorageSync('token', res.data.accessToken)
        uni.setStorageSync('refreshAfter', res.data.refreshAfter)
        uni.setStorageSync('accessExpire', res.data.accessExpire)
        refreshAgentStatus()
      }
    } else {
      uni.showToast({
        title: res.msg || '申请失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 定时刷新代理状态
const refreshAgentStatus = () => {
  if (status.value === 3) {
    if (intervalId) clearInterval(intervalId)

    intervalId = setInterval(() => {
      if (status.value !== 3) {
        clearInterval(intervalId)
        intervalId = null
        return
      }
      getAgentInformation()
    }, 2000)
  } else {
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
  }
}

onLoad(() => {
  const token = uni.getStorageSync('token')
  if (token) {
    // 从缓存中获取代理信息
    const agentInfo = uni.getStorageSync('agentInfo')
    if (agentInfo) {
      status.value = agentInfo.status || 3
    }
    getAgentInformation()
  }
})

// 页面卸载时清除定时器
onUnload(() => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
})
</script>

<route type="page" lang="json">{
  "layout": "page",
  "title": "代理申请",
  "auth": true
}</route>