<!-- LoginModal.vue -->
<template>
  <div style="--van-popup-background:transparent;--van-cell-background:transparent;">
    <van-dialog v-model:show="isVisible" :show-confirm-button="false" :closeOnClickOverlay="props.closeOnClickOverlay">
      <div class="relative pd10">
        <div class="bg-fff ulib-rt20 inner30">
          <h3 class="text-center font-34">立即登录</h3>
        </div>
        <div class="pop-form mt5">
          <div class="bg-f2 ulib-r750 inner5 mt30">
            <van-field v-model="mobile" label="" type="tel" maxlength="11" required
                       placeholder="请输入您的常用手机号码"/>
          </div>
          <div class="bg-f2 ulib-r750 inner5 mt30">
            <van-field v-model="code" label="" placeholder="验证码" maxlength="4" required type="number"
                       inputmode="numeric">
              <template #button>
                <span v-if="!is_show_count" class="text-color-theme font-26" @click.stop="getSmsCode">发送验证码</span>
                <van-count-down class="color-ccc font-26" v-else :time="count_time" @finish="onCountFinish"
                                format="ss 秒后重发"/>
              </template>
            </van-field>
          </div>
          <div class="text-center font-24 mt30">领取即同意
            <span v-for="(item,index) in item_pop_bottom_info" :key="index" class="color-184ebb"
                  @click="showPopContent(item)">{{ item.title }}</span></div>
          <div class="mt30">
            <van-button round type="danger" class="w100" :disabled="!(mobile && code)" @click.stop="handleLogin">
              确定登录
            </van-button>
          </div>
        </div>
      </div>
    </van-dialog>
    <PopContent :content="content" :show-pop="showContentPop" @update:show-pop="showContentPop = $event"/>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import api from '../utils/api.js'
import { showToast } from 'vant' // 导入Toast组件
import { getBasicConfig } from '@/utils/basicSetting'
import PopContent from '@/components/PopContent.vue' // 导入PopContent组件

// 响应式数据
const isVisible = ref(false)
const mobile = ref('')
const code = ref('')
const errorMessage = ref('')
const callback = ref(null)
const is_show_count = ref(false)
const count_time = ref(60000)

const props = defineProps({
  closeOnClickOverlay: {
    type: Boolean,
    default: true
  }
})

const showContentPop = ref(false)
const item_pop_bottom_info = ref([])
const content = ref('')
const showPopContent = (item) => {
  content.value = item.content
  showContentPop.value = true
}
onMounted(async () => {
  item_pop_bottom_info.value = await getBasicConfig('item_bottom')
})

// 显示模态框
const showModal = (cb) => {
  callback.value = cb
  isVisible.value = true
  errorMessage.value = ''
}

// 关闭模态框
const closeModal = () => {
  isVisible.value = false
  mobile.value = ''
  code.value = ''
  errorMessage.value = ''
}
/**
 * 获取短信验证码
 */
const getSmsCode = async () => {
  // 验证手机号
  if (!mobile.value) {
    showToast('请输入手机号')
    return
  }

  if (!validateMobile(mobile.value)) {
    showToast('请输入正确的手机号格式')
    return
  }

  try {
    // 调用获取验证码接口
    const result = await api.post('/auto/sms/login', { mobile: mobile.value })

    if (result.code === 200) {
      showToast('验证码发送成功')
      // 开始倒计时
      showCount()
    } else {
      showToast(result.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    showToast('获取验证码失败，请稍后重试')
  }
}

function showCount() {
  is_show_count.value = true
  count_time.value = 60000
}

function onCountFinish() {
  is_show_count.value = false
}

// 处理登录
const handleLogin = async () => {
  try {
    const response = await api.post('/auto/login/mobile', {
      mobile: mobile.value,
      code: code.value,
    })
    if (response.code === 200 && response.data.Authorization) {
      localStorage.setItem('token', response.data.Authorization)
      closeModal()
      if (callback.value) {
        callback.value()
      }
    } else {
      showToast(response.message || '登录失败')
    }
  } catch (error) {
    errorMessage.value = '登录失败，请稍后再试'
  }
}
/**
 * 验证手机号格式
 * @param {string} phone - 手机号
 * @returns {boolean} - 是否是有效的手机号
 */
const validateMobile = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}
// 暴露给父组件的方法
defineExpose({
  showModal,
  closeModal
})
</script>

<style scoped>
.w100 {
  width: 100%;
}

.pd10 {
  padding: 4vw;
}
</style>