<template>
  <div>
    <v-form @submit.prevent>
      <v-text-field v-model="loginData.query.phone" placeholder="请输入手机号" color="#00897B" variant="outlined" density="compact" :rules="phoneRules">
        <template v-slot:prepend-inner>
          <span class="d-flex">
            <v-icon icon="mdi-cellphone" size="20"></v-icon>
            <span class="d-flex" id="menu-activator">
              <span class="phone-number">{{ currentAear }}</span>
              <v-icon size="20">mdi-chevron-down</v-icon>
            </span>
            <v-menu activator="#menu-activator">
              <v-list>
                <v-list-item v-for="(item, index) in items" :key="index" :value="index" @click="handleChangeCurrentAear">
                  <v-list-item-title>{{ item.title }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </span>
        </template>
      </v-text-field>
      <v-text-field v-model="loginData.query.code" placeholder="请输入验证码" color="#00897B" variant="outlined" density="compact" prepend-inner-icon="mdi-security" :rules="[v=> !!v || '请填写验证码']">
        <template #append-inner>
          <span v-if="showCode" class="login-code" @click="handleCode">获取验证码</span>
          <span v-else class="disable">重新获取{{ count }}s</span>
        </template>
      </v-text-field>
    </v-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { setCodeTime } from '@/utils/code'
defineOptions({ name: 'phone-index' })
const phoneRules = ref([
  value => {
    if (value) return true
    return '请输入手机号'
  },
  value => {
    if (value?.length <= 11) return true
    return 'Name must be less than 10 characters.'
  }
])
// 手机号区域
const currentAear = ref('中国大陆')
const items = [
  { title: '中国大陆', value: '86' },
  { title: '中国香港', value: '852' },
  { title: '中国澳门', value: '853' },
  { title: '西班牙', value: '34' }
]
const handleChangeCurrentAear = (e) => {
  currentAear.value = e.target.innerText
}

// 获取验证码
const showCode = ref(true)
const count = ref(0)
const timer = ref(null)
const handleCode = () => {
  // 先校验手机号
  count.value = 60
  setTime()
}
const setTime = () => {
  showCode.value = false
  timer.value = setInterval(() => {
    let number = count.value
    if (number > 0 && number <= 60) {
      count.value--
      setCodeTime(number - 1)
    } else {
      showCode.value = true
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}
const autoTimer = () => {
  count.value = 0
  if(!count.value) return
  setTime()
}
autoTimer()

const loginData = reactive({
  query: {
    phone: '',
    code: ''
  }
})
</script>

<style lang="scss" scoped>
.login-code {
  width: 62px;
  color: #00897B; 
  font-size: 12px; 
  cursor: pointer;
}
.disable {
  width: 72px;
  color: grey;
  font-size: 12px;
}
::v-deep .phone-number {
  font-size: 12px;
  width: 50px;
}
</style>