<script setup>
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '注册成为代理',
    navigationStyle: 'default',
  },
})

import { ref, computed, onUnmounted, onMounted } from 'vue'
import { registerByInviteCode, applyForAgent } from '@/api/agent'
import { useAgentStore } from '@/stores/agentStore'
import { useUserStore } from '@/stores/userStore'
import useApiFetch from '@/composables/useApiFetch'

const agentStore = useAgentStore()
const userStore = useUserStore()
const appName = import.meta.env?.VITE_APP_NAME || '全能查'

const phoneNumber = ref('')
const verificationCode = ref('')
const inviteCode = ref('')
const isAgreed = ref(false)
const isCountingDown = ref(false)
const countdown = ref(60)
const isPhoneDisabled = ref(false)
let timer = null

function fillInviteCode() {
  inviteCode.value = '16800'
}

onMounted(async () => {
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  const options = page?.options || {}

  if (options.invite_code) {
    inviteCode.value = decodeURIComponent(options.invite_code)
  }
  if (options.mobile) {
    phoneNumber.value = decodeURIComponent(options.mobile)
    isPhoneDisabled.value = true
  } else {
    const token = uni.getStorageSync('token')
    if (token && userStore.mobile) {
      phoneNumber.value = userStore.mobile
      isPhoneDisabled.value = true
    } else if (token) {
      try {
        await userStore.fetchUserInfo()
        if (userStore.mobile) {
          phoneNumber.value = userStore.mobile
          isPhoneDisabled.value = true
        }
      } catch (e) {
        console.error(e)
      }
    }
  }
})

const isPhoneNumberValid = computed(() => /^1[3-9]\d{9}$/.test(phoneNumber.value))

const isInviteCodeValid = computed(() => inviteCode.value.trim().length > 0)

const canRegister = computed(() =>
  isPhoneNumberValid.value &&
  verificationCode.value.length === 6 &&
  isInviteCodeValid.value &&
  isAgreed.value
)

async function sendVerificationCode() {
  if (isCountingDown.value || !isPhoneNumberValid.value) return
  if (!isPhoneNumberValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }
  if (!isInviteCodeValid.value) {
    uni.showToast({ title: '请先输入邀请码', icon: 'none' })
    return
  }

  const { data, error } = await useApiFetch('auth/sendSms')
    .post({ mobile: phoneNumber.value, actionType: 'agentApply' })
    .json()

  if (data.value && !error.value) {
    if (data.value.code === 200) {
      uni.showToast({ title: '获取成功', icon: 'success' })
      startCountdown()
    } else {
      uni.showToast({ title: data.value.msg || '获取失败', icon: 'none' })
    }
  } else {
    uni.showToast({ title: error.value || '获取失败', icon: 'none' })
  }
}

function startCountdown() {
  isCountingDown.value = true
  countdown.value = 60
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
      isCountingDown.value = false
    }
  }, 1000)
}

async function handleRegister() {
  if (!isPhoneNumberValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }
  if (!isInviteCodeValid.value) {
    uni.showToast({ title: '请输入邀请码', icon: 'none' })
    return
  }
  if (verificationCode.value.length !== 6) {
    uni.showToast({ title: '请输入6位验证码', icon: 'none' })
    return
  }
  if (!isAgreed.value) {
    uni.showToast({ title: '请先同意用户协议、隐私政策和代理管理协议', icon: 'none' })
    return
  }
  await performRegister()
}

async function performRegister() {
  try {
    const { data, error } = await registerByInviteCode({
      mobile: phoneNumber.value,
      code: verificationCode.value,
      referrer: inviteCode.value.trim(),
    })

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        uni.setStorageSync('token', data.value.data.accessToken)
        uni.setStorageSync('refreshAfter', data.value.data.refreshAfter)
        uni.setStorageSync('accessExpire', data.value.data.accessExpire)

        if (data.value.data.agent_id) {
          agentStore.updateAgentInfo({
            isAgent: true,
            agentID: data.value.data.agent_id,
            level: data.value.data.level || 1,
            levelName: data.value.data.level_name || '普通代理',
          })
        }

        uni.showToast({ title: '注册成功', icon: 'success' })
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/index' })
        }, 500)
      } else {
        uni.showToast({ title: data.value.msg || '注册失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: error.value || '注册失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('注册失败:', err)
    uni.showToast({ title: '注册失败，请重试', icon: 'none' })
  }
}

function toUserAgreement() {
  uni.navigateTo({ url: '/pages/userAgreement/index' })
}

function toPrivacyPolicy() {
  uni.navigateTo({ url: '/pages/privacyPolicy/index' })
}

function toAgentManageAgreement() {
  uni.navigateTo({ url: '/pages/agentManageAgreement/index' })
}

onUnmounted(() => {
  if (timer) clearInterval(timer)
})

function onClickLeft() {
  uni.navigateBack()
}
</script>

<template>
  <view class="login-layout">
    <image
      class="login-bg-image"
      src="/static/login/login_bg.png"
      mode="aspectFill"
    />
    <view class="login px-4 relative z-10" style="padding-top: 44px;">
      <view class="mb-8 pt-20 text-left">
        <view class="flex flex-col items-center">
          <image class="h-16 w-16 rounded-full shadow block" src="/static/login/logo.png" mode="aspectFit" />
          <image class="h-12 mt-4 block" src="/static/login/logo_title.png" mode="widthFix" />
        </view>
      </view>

      <view class="login-form">
        <view class="form-item">
          <view class="form-label">邀请码</view>
          <view class="input-with-btn flex-1">
            <input
              v-model="inviteCode"
              class="form-input"
              type="text"
              placeholder="请输入邀请码"
            />
            <view class="get-invite-code-btn" @click="fillInviteCode">获取邀请码</view>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">手机号</view>
          <input
            v-model="phoneNumber"
            class="form-input flex-1"
            type="number"
            placeholder="请输入手机号"
            maxlength="11"
            :disabled="isPhoneDisabled"
          />
        </view>

        <view class="form-item">
          <view class="form-label">验证码</view>
          <view class="verification-input-wrapper flex-1">
            <input
              v-model="verificationCode"
              class="form-input verification-input"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
            />
            <view
              class="get-code-btn"
              :class="{ disabled: isCountingDown || !isPhoneNumberValid || !isInviteCodeValid }"
              @click="sendVerificationCode"
            >
              {{ isCountingDown ? `${countdown}s` : '获取验证码' }}
            </view>
          </view>
        </view>

        <view class="agreement-wrapper">
          <wd-checkbox v-model="isAgreed" />
          <view class="agreement-text">
            我已阅读并同意
            <text class="agreement-link" @click.stop="toUserAgreement">《用户协议》</text>
            <text class="agreement-link" @click.stop="toPrivacyPolicy">《隐私政策》</text>
            和
            <text class="agreement-link" @click.stop="toAgentManageAgreement">《代理管理协议》</text>
          </view>
        </view>

        <view class="notice-text">
          未注册手机号注册后将自动生成账号并成为代理，并且代表您已阅读并同意
        </view>

        <button
          class="login-btn"
          :class="{ disabled: !canRegister }"
          :disabled="!canRegister"
          @click="handleRegister"
        >
          注册成为代理
        </button>
      </view>
    </view>
  </view>
</template>

<style scoped>
.login-layout {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

.login-bg-image {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.login-form {
  background-color: #fff;
  padding: 2rem;
  margin-top: 0.5rem;
  box-shadow: 0 0 24px rgba(63, 63, 63, 0.06);
  border-radius: 8px;
}

.form-item {
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  border: none;
  border-bottom: 1px solid #ebedf0;
}

.input-with-btn {
  position: relative;
  display: flex;
  align-items: center;
}

.input-with-btn .form-input {
  padding-right: 5rem;
}

.get-invite-code-btn {
  position: absolute;
  right: 0;
  color: #1989fa;
  font-size: 14px;
  padding: 0.5rem;
  font-weight: 500;
}

.form-label {
  font-size: 15px;
  color: #323233;
  margin-right: 1rem;
  font-weight: 500;
  min-width: 4rem;
  flex-shrink: 0;
}

.form-input {
  width: 100%;
  padding: 14px 0;
  font-size: 15px;
  color: #323233;
  background-color: transparent;
}

.form-input:disabled {
  color: #969799;
  background-color: transparent;
}

.verification-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.verification-input {
  flex: 1;
  padding-right: 5rem;
}

.get-code-btn {
  position: absolute;
  right: 0;
  color: #1989fa;
  font-size: 14px;
  padding: 0.5rem;
  font-weight: 500;
}

.get-code-btn.disabled {
  color: #c8c9cc;
}

.agreement-wrapper {
  display: flex;
  align-items: flex-start;
  margin-top: 1.5rem;
  margin-bottom: 1rem;
}

.agreement-wrapper :deep(.wd-checkbox) {
  margin-right: 8px;
  flex-shrink: 0;
}

.agreement-text {
  font-size: 12px;
  color: #646566;
  line-height: 1.4;
}

.agreement-link {
  color: #1989fa;
}

.notice-text {
  font-size: 11px;
  color: #969799;
  line-height: 1.5;
  margin-bottom: 2rem;
}

.login-btn {
  width: 100%;
  padding: 14px;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 0.25em;
}

.login-btn.disabled {
  background-color: #c8c9cc;
}
</style>
