@extends('layouts.auth')

@section('title', '找回密码')

@push('styles')
<link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
<link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
<link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
<link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
<link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
<link rel="stylesheet" href="{{ asset('Admin/css/other/login.css') }}">
<style>
.step-panel { display: none; }
.step-panel.active { display: block; }
.code-input-group { display: flex; align-items: center; }
.code-input-group .layui-input { width: calc(100% - 110px); border-top-right-radius: 0; border-bottom-right-radius: 0; }
.send-code-btn { width: 110px; height: 38px; line-height: 38px; border-top-left-radius: 0; border-bottom-left-radius: 0; cursor: pointer; font-size: 13px; text-align: center; white-space: nowrap; }
.send-code-btn.disabled { cursor: not-allowed; opacity: 0.6; }
</style>
@endpush

@section('content')
<div class="login-page">
    <div class="layui-row">
        <div class="layui-col-sm6 login-bg">
            <img class="login-bg-img" src="{{ asset('Admin/images/banner.png') }}" alt="">
        </div>
        <div class="layui-col-sm6 login-form">
            <div class="layui-form" lay-filter="form-submit">
                <div class="form-center">
                    <div class="form-center-box">
                        <div class="top-log-title">
                            <img class="top-log" src="{{ asset('Admin/images/logo.png') }}" alt="CMSPRO">
                            <span>用户中心</span>
                        </div>
                        <div class="top-desc">找回密码</div>

                        <div id="step1" class="step-panel active" style="margin-top: 30px;">
                            <form id="sendCodeForm">
                                @csrf
                                <div class="layui-form-item">
                                    <div class="layui-input-wrap">
                                        <div class="layui-input-prefix">
                                            <i class="fa fa-envelope"></i>
                                        </div>
                                        <input type="email" name="email" lay-verify="required|email" placeholder="请输入注册邮箱" autocomplete="off" class="layui-input" lay-reqText="邮箱不能为空">
                                    </div>
                                </div>
                                <div class="login-btn">
                                    <button type="button" id="sendCodeBtn" class="layui-btn login" onclick="sendCode()">发送验证码</button>
                                </div>
                                <div style="text-align: center; margin-top: 12px;">
                                    想起密码了？<a href="{{ url('/user/login') }}" style="color: #16b777;">去登录</a>
                                </div>
                            </form>
                        </div>

                        <div id="step2" class="step-panel" style="margin-top: 30px;">
                            <form id="resetForm">
                                @csrf
                                <input type="hidden" name="email" id="resetEmail">
                                <div style="font-size: 14px; color: #666; margin-bottom: 15px;">
                                    验证码已发送到 <span id="showEmail" style="color: #16b777; font-weight: bold;"></span>，请查收
                                </div>
                                <div class="layui-form-item">
                                    <div class="code-input-group">
                                        <input type="text" name="code" lay-verify="required" placeholder="请输入6位验证码" autocomplete="off" class="layui-input" maxlength="6" style="letter-spacing: 4px; text-align: center;" lay-reqText="验证码不能为空">
                                        <button type="button" id="resendCodeBtn" class="layui-btn layui-btn-primary layui-btn-sm send-code-btn" onclick="resendCode()">重新发送</button>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-wrap">
                                        <div class="layui-input-prefix">
                                            <i class="layui-icon layui-icon-password"></i>
                                        </div>
                                        <input type="password" name="password" lay-verify="required" placeholder="新密码（6-20位）" autocomplete="off" class="layui-input" lay-affix="eye" lay-reqText="新密码不能为空">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-wrap">
                                        <div class="layui-input-prefix">
                                            <i class="layui-icon layui-icon-password"></i>
                                        </div>
                                        <input type="password" name="password_confirmation" lay-verify="required" placeholder="确认新密码" autocomplete="off" class="layui-input" lay-affix="eye" lay-reqText="确认密码不能为空">
                                    </div>
                                </div>
                                <div class="login-btn">
                                    <button type="button" id="resetPasswordBtn" class="layui-btn login" onclick="resetPassword()">重置密码</button>
                                </div>
                                <div style="text-align: center; margin-top: 12px;">
                                    <a href="javascript:void(0)" onclick="backToStep1()" style="color: #999;">返回重新输入邮箱</a>
                                </div>
                            </form>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script>
$.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
});
layui.use(['toast', 'form', 'jquery'], function() {
    var toast = layui.toast;
    var form = layui.form;
    var $ = layui.jquery;

    function sendCode() {
        if (! form.checkInput(document.querySelector('#sendCodeForm input[name=email]'))) return;

        var email = $('input[name=email]').val();
        var btn = $('#sendCodeBtn');
        btn.text('发送中...').addClass('disabled');

        $.ajax({
            url: '/api/user/password/email-code',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({ email: email }),
            success: function(res) {
                btn.text('发送验证码');
                if (res.code === 0) {
                    $('#resetEmail').val(email);
                    $('#showEmail').text(email);
                    $('#step1').removeClass('active');
                    $('#step2').addClass('active');
                    toast.success({ title: res.message || '验证码已发送' });
                } else {
                    toast.error({ title: res.message || '发送失败' });
                    btn.removeClass('disabled');
                }
            },
            error: function(xhr) {
                btn.text('发送验证码').removeClass('disabled');
                toast.error({ title: xhr.responseJSON?.message || '请求失败' });
            }
        });
    }

    window.sendCode = sendCode;

    function resendCode() {
        var email = $('#resetEmail').val();
        var btn = $('#resendCodeBtn');
        btn.text('发送中...').addClass('disabled');

        $.ajax({
            url: '/api/user/password/email-code',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({ email: email }),
            success: function(res) {
                if (res.code === 0) {
                    toast.success({ title: res.message || '验证码已重发' });
                    startCountdown(btn);
                } else {
                    toast.error({ title: res.message || '发送失败' });
                    btn.text('重新发送').removeClass('disabled');
                }
            },
            error: function(xhr) {
                btn.text('重新发送').removeClass('disabled');
                toast.error({ title: xhr.responseJSON?.message || '请求失败' });
            }
        });
    }

    window.resendCode = resendCode;

    function startCountdown(btn) {
        var seconds = 60;
        btn.addClass('disabled');
        var timer = setInterval(function() {
            seconds--;
            btn.text(seconds + 's 后重发');
            if (seconds <= 0) {
                clearInterval(timer);
                btn.text('重新发送').removeClass('disabled');
            }
        }, 1000);
    }

    function resetPassword() {
        var formData = {};
        $('#resetForm').serializeArray().forEach(function(item) { formData[item.name] = item.value; });

        if (!formData.code || !formData.password || !formData.password_confirmation) {
            toast.error({ title: '请填写完整信息' });
            return;
        }

        if (formData.password !== formData.password_confirmation) {
            toast.error({ title: '两次密码输入不一致' });
            return;
        }

        if (formData.password.length < 6 || formData.password.length > 20) {
            toast.error({ title: '密码长度需在6-20位之间' });
            return;
        }

        var btn = $('#resetPasswordBtn');
        btn.text('提交中...').addClass('disabled');

        $.ajax({
            url: '/api/user/password/reset-by-code',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res) {
                if (res.code === 0) {
                    toast.success({ title: res.message || '密码重置成功' }, function() {
                        window.location.href = '{{ url('/user/login') }}';
                    });
                } else {
                    toast.error({ title: res.message || '重置失败' });
                    btn.text('重置密码').removeClass('disabled');
                }
            },
            error: function(xhr) {
                btn.text('重置密码').removeClass('disabled');
                toast.error({ title: xhr.responseJSON?.message || '请求失败' });
            }
        });
    }

    window.resetPassword = resetPassword;

    window.backToStep1 = function() {
        $('#step2').removeClass('active');
        $('#step1').addClass('active');
    };
});
</script>
@endpush
