<template>
    <div class="user-card">
        <UserHeader />
        <UserText :user-text="userText" @back="handleBack" />
        <el-form class="user-form" ref="bindPhoneFormRef" :model="bindPhoneForm" :rules="bindPhoneRules">
            <el-form-item class="phone-item" prop="phone">
                <el-select v-model="bindPhoneForm.countryCode" :teleported="false" value-key="code" placeholder="国家"
                    size="large">
                    <el-option v-for="item in countryOptions" :key="item.code" :label="item.code" :value="item.code">
                        <div class="country-option">
                            <span class="country-name">{{ item.name }}</span>
                            <span class="country-code">{{ item.code }}</span>
                        </div>
                    </el-option>
                </el-select>
                <el-input v-model="bindPhoneForm.phone" placeholder="请输入手机号" clearable size="large" />
            </el-form-item>
            <UserCaptcha v-model="bindPhoneForm.code" @sendCode="handleSendCode" :show-send-button="showSendButton"
                :send-state="sendState" />
            <el-form-item class="form-submit">
                <el-button type="primary" @click="handleSubmit">确认绑定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">

defineOptions({
  name: 'BindPhone'
})
// alert('绑定邮箱')
// type类型
import type { FormInstance, FormRules } from 'element-plus'
// 组件
import UserHeader from './components/Header.vue'
import UserText from './components/Text.vue'
import UserCaptcha from './components/Captcha.vue'
//用户校验规则
import { emailRules, codeRules } from './config/rules'
import { useUserStore } from '@/stores/modules/user'
import { sendCaptcha, initCaptchaState, clearCaptchaTimer } from '@/utils/sendCaptcha'
import { countryOptions } from '@/views/user/config/mock'

const userStore = useUserStore()
const router = useRouter()

//userText 实例
const userText = ref({
    backText: '返回',
    account: ''
})

// bindPhone 表单实例
const bindPhoneFormRef = ref<FormInstance>()
const bindPhoneForm = ref({
    phone: '',
    code: '',
    countryCode: '+86',
})
const bindPhoneRules = ref<FormRules>({
    phone: emailRules().phone,
    code: codeRules().code,
})


// 验证码实例
const showSendButton = ref<boolean>(true)
const sendState = ref<object>({
    isCounting: false,
    countdown: 0,
})
//初始化验证码倒计时状态（添加页面前缀隔离不同页面的倒计时状态）
const phoneCaptchaState = initCaptchaState('phone', 60, 'bindphone_phone');
// 邮箱验证码状态
const { isCounting: phoneIsCounting, countdown: phoneCountdown } = phoneCaptchaState

//方法
// 统一更新sendState的方法
const updateSendState = (type: string) => {
    sendState.value = {
        isCounting: phoneIsCounting,
        countdown: phoneCountdown
    }
}
// 初始化时根据当前activeTab更新sendState（避免刷新后丢失）
const initSendState = () => {
    const currentType = 'phone'
    updateSendState(currentType)
}
onMounted(() => {
    // 页面加载时立即执行，恢复倒计时
    initSendState()
})


// 定义发送验证码接口
const sendCodeApi = async () => {
    // 发送验证码参数
    const sendParams = {
        mobile: bindPhoneForm.value.phone,
        type: 'resetPass_code'
    }
    return userStore.sendCode(sendParams)
}

//发送验证码
const handleSendCode = async () => {
    const currentType = 'phone'
    // 第二步：确定类型、接收方、对应的倒计时状态和发送函数
    const type: string = currentType || 'phone'
    const receiver = bindPhoneForm.value.phone;
    const currentCaptchaState = phoneCaptchaState;

    // 第三步：调用封装的发送函数（传正确的函数，而非字符串）
    await sendCaptcha(
        type,
        receiver,
        currentCaptchaState, // 只更新当前类型的倒计时状态
        () => sendCodeApi() // 传入返回Promise的函数
    );

    //把状态同步给子组件
    updateSendState(type)
}
// 组件卸载时清除定时器（关键：防止内存泄漏）
onUnmounted(() => {
    clearCaptchaTimer(phoneCaptchaState);
});




/**
 * @description: 返回
 */
const handleBack = () => {
    router.back()
}

// 提交表单
const handleSubmit = async () => {
    if (!bindPhoneFormRef.value) return;
    await bindPhoneFormRef.value.validate();
}
</script>

<style scoped lang="scss">
.user-card{
    .user-text{
        margin-bottom: 0;
    }
}
.user-form {
  .phone-item {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }

    .el-select {
      width: 120px;
      margin-right: 10px;

      .country-option {
        width: 120px;
        display: flex;
        justify-content: space-between;
      }

      :deep(.el-select-dropdown__item) {
        padding: 0 16px 0 16px;
      }
    }
  }

  .forgot-password {
    font-size: 14px;
    color: #409eff;
    text-decoration: none;
  }

  .form-submit {
    margin-top: 18px;

    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
}
</style>
