<template>
    <div class="phone-modify-modal">
        <el-dialog
            v-model="visible"
            title="修改手机号"
            width="400px"
            :close-on-click-modal="false"
            :close-on-press-escape="true"
            @close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
                class="phone-form"
            >
                <!-- 当前手机号 -->
                <el-form-item label="当前手机号">
                    <span class="current-phone">{{ maskPhoneNumber(currentPhone) }}</span>
                </el-form-item>

                <!-- 新手机号 -->
                <el-form-item label="新手机号" prop="newPhone">
                    <el-input
                        v-model="formData.newPhone"
                        placeholder="请输入新手机号"
                        maxlength="11"
                    >
                        <template #prefix>
                            <span class="phone-prefix">+86</span>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 验证码 -->
                <el-form-item label="验证码" prop="verifyCode">
                    <div class="verify-code-container">
                        <el-input
                            v-model="formData.verifyCode"
                            placeholder="请输入验证码"
                            maxlength="6"
                        />
                        <el-button
                            :disabled="!canSendCode || countdown > 0"
                            @click="sendVerifyCode"
                            class="send-code-btn"
                        >
                            {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="handleConfirm"
                    >
                        确认修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/store';

export default {
    name: 'PhoneModifyModal',
    props: {
        modelValue: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:modelValue', 'success'],
    setup(props, { emit }) {
        const store = useMainStore();
        const formRef = ref(null);
        const loading = ref(false);
        const countdown = ref(0);
        let countdownTimer = null;

        const visible = computed({
            get: () => props.modelValue,
            set: (value) => emit('update:modelValue', value)
        });

        // 表单数据
        const formData = reactive({
            newPhone: '',
            verifyCode: ''
        });

        // 当前手机号
        const currentPhone = computed(() => store.user?.phone || '');

        // 是否可以发送验证码
        const canSendCode = computed(() => {
            return /^1[3-9]\d{9}$/.test(formData.newPhone);
        });

        // 表单验证规则
        const formRules = {
            newPhone: [
                { required: true, message: '请输入新手机号', trigger: 'blur' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
            ],
            verifyCode: [
                { required: true, message: '请输入验证码', trigger: 'blur' },
                { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' }
            ]
        };

        // 手机号脱敏显示
        const maskPhoneNumber = (phone) => {
            if (!phone) return '未绑定';
            if (phone.length === 11) {
                return `${phone.slice(0, 3)} **** ${phone.slice(7)}`;
            }
            return phone;
        };

        // 监听弹窗显示状态
        watch(visible, (newVal) => {
            if (newVal) {
                resetForm();
            } else {
                stopCountdown();
            }
        });

        // 重置表单
        const resetForm = () => {
            formData.newPhone = '';
            formData.verifyCode = '';
            formRef.value?.clearValidate();
        };

        // 发送验证码
        const sendVerifyCode = async () => {
            if (!canSendCode.value) return;

            try {
                loading.value = true;
                
                // 这里调用发送验证码的API
                // await api.sendPhoneVerifyCode(formData.newPhone);
                
                // 模拟API调用
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                ElMessage.success('验证码已发送');
                startCountdown();
                
            } catch (error) {
                console.error('发送验证码失败:', error);
                ElMessage.error('发送验证码失败，请重试');
            } finally {
                loading.value = false;
            }
        };

        // 开始倒计时
        const startCountdown = () => {
            countdown.value = 60;
            countdownTimer = setInterval(() => {
                countdown.value--;
                if (countdown.value <= 0) {
                    stopCountdown();
                }
            }, 1000);
        };

        // 停止倒计时
        const stopCountdown = () => {
            if (countdownTimer) {
                clearInterval(countdownTimer);
                countdownTimer = null;
            }
            countdown.value = 0;
        };

        // 确认修改
        const handleConfirm = async () => {
            try {
                await formRef.value?.validate();
                
                loading.value = true;
                
                // 这里调用修改手机号的API
                // await api.modifyPhone({
                //     newPhone: formData.newPhone,
                //     verifyCode: formData.verifyCode
                // });
                
                // 模拟API调用
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                // 更新store中的用户信息
                await store.updateUserInfo({
                    phone: formData.newPhone
                });
                
                ElMessage.success('手机号修改成功');
                emit('success');
                visible.value = false;
                
            } catch (error) {
                console.error('修改手机号失败:', error);
                ElMessage.error('修改失败，请重试');
            } finally {
                loading.value = false;
            }
        };

        // 关闭弹窗
        const handleClose = () => {
            visible.value = false;
        };

        return {
            visible,
            formRef,
            formData,
            formRules,
            currentPhone,
            canSendCode,
            countdown,
            loading,
            maskPhoneNumber,
            sendVerifyCode,
            handleConfirm,
            handleClose
        };
    }
};
</script>

<style lang="scss" scoped>
.phone-modify-modal {
    .phone-form {
        .current-phone {
            color: #606266;
            font-size: 16px;
        }

        .phone-prefix {
            color: #909399;
            margin-right: 8px;
        }

        .verify-code-container {
            display: flex;
            gap: 8px;

            .el-input {
                flex: 1;
            }

            .send-code-btn {
                white-space: nowrap;
                min-width: 100px;
            }
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #303133;
        }

        :deep(.el-input__inner) {
            border-radius: 6px;
        }

        :deep(.el-form-item) {
            margin-bottom: 20px;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;

        .el-button--primary {
            background-color: #0A2463;
            border-color: #0A2463;

            &:hover {
                background-color: #083354;
                border-color: #083354;
            }
        }
    }

    :deep(.el-dialog__header) {
        text-align: center;

        .el-dialog__title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .phone-modify-modal {
        :deep(.el-dialog) {
            width: 90% !important;
            margin: 5vh auto !important;
        }

        .phone-form {
            :deep(.el-form-item__label) {
                width: 80px !important;
                font-size: 14px;
            }

            .verify-code-container {
                flex-direction: column;
                gap: 12px;

                .send-code-btn {
                    min-width: auto;
                }
            }
        }
    }
}
</style> 