@extends('adminlte::page')

@section('title', '收件箱')

@section('content_header')
<h1>收件箱</h1>
@stop

@section('content')
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <form id="search-form" method="get">
                <div class="card-body">
                    <div class="row">
                        <div class="col-3">
                            <div class="form-group">
                                <label>Email</label>
                                <select name="mail" class="form-control">
                                    <option value="">全部</option>
                                    @foreach($mail_address_list as $mail_address)
                                    <option value="{{$mail_address->mail}}">{{$mail_address->mail}}</option>
                                    @endforeach
                                </select>

                            </div>
                        </div>
                        <div class="col-2">
                            <div class="form-group">
                                <label>状态</label>
                                <select name="is_read" class="form-control">
                                    <option value="-1">全部</option>
                                    <option value="0">未读</option>
                                    <option value="1">已读</option>
                                </select>

                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="card">

            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>发件人</th>
                            <th>收件人</th>
                            <th>标题</th>
                            <th>接收时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="mail-list">
                        @if($mail_list->isEmpty())
                        <tr id="default-note">

                            <td colspan="5">
                                <div class="alert alert-default" role="alert">
                                    还没收到邮件哦
                                </div>
                            </td>
                        </tr>
                        @else
                        @foreach($mail_list as $mail)
                        <tr>
                            <td>{{$mail->from}}</td>
                            <td>{{$mail->to}}</td>
                            <td>{{$mail->title}}</td>
                            <td>{{$mail->received_at}}</td>
                            <td>
                                <button class="btn btn-primary info-btn btn-sm" data-key="{{$mail->key}}"
                                    type="button">查看</button>
                            </td>
                        </tr>
                        @endforeach
                        @endif
                        <!-- 更多行 -->
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                {{ $mail_list->links() }}
            </div>

        </div>
    </div>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- iframe 用于展示 API 返回的内容 -->
                    <iframe id="modalIframe"></iframe>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    @stop

    @section('css')
    {{-- Add here extra stylesheets --}}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css"
        crossorigin="anonymous" referrerpolicy="no-referrer" />

    <style>
        #modalIframe {
            width: 100%;
            height: auto;
            border: 1px solid #ced4da;
            border-radius: .2rem;
            padding: .375rem .75rem;
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: #495057;
            background-color: #fff;
            background-clip: padding-box;
            transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
        }

        #modalIframe:focus {
            color: #495057;
            background-color: #fff;
            border-color: #80bdff;
            outline: 0;
            box-shadow: 0 0 0 .2rem rgba(0, 123, 255, .25);
        }
    </style>
    @stop

    @section('js')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" crossorigin="anonymous"
        referrerpolicy="no-referrer"></script>
    <script>
        let email = "";
        let isRequestPending = false;
        let countdown = 5;
        let total = "{{$total}}";

        let csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        function dateFmt(dateString) {
            let date = new Date(dateString);

            let year = date.getFullYear();
            let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
            let day = String(date.getDate()).padStart(2, '0');
            let hours = String(date.getHours()).padStart(2, '0');
            let minutes = String(date.getMinutes()).padStart(2, '0');
            let seconds = String(date.getSeconds()).padStart(2, '0');

            let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return formattedDate;
        }



        $(function () {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                }
            });

            setInterval(function () {
                $.get('/refresh-csrf', function (data) {
                    csrfToken = data.csrfToken
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': data.csrfToken
                        }
                    });
                });
            }, 1000 * 60);


            $('#myModal').on('shown.bs.modal', function () {
                let iframeHeight = $('#modalIframe').contents().find("html").height();
                if (iframeHeight <= 600) {
                    $('#modalIframe').css('height', 600);
                } else if (iframeHeight >= 800) {
                    $('#modalIframe').css('height', 800);
                } else {
                    $('#modalIframe').css('height', iframeHeight);
                }
            });


            $('[name="mail"]').val('{{request()->input("mail")}}');
            $('[name="is_read"]').val('{{request()->input("is_read")}}');

            var countdownTimer = setInterval(function () {
                $.ajax({
                    url: '/home/total',  // 替换为你的后端接口
                    type: 'POST',
                    data: $('#search-form').serialize(),
                    success: function (response) {
                        if (response.data.total > total) {
                            $('#search-form').submit();
                        }
                        // 在这里处理你的响应数据
                    },
                    error: function (xhr, status, error) {

                        if (xhr.status == 419) {
                            window.location.reload();
                        }

                        console.error('请求失败:', error);
                        toastr.error(error, "请求失败");
                    },
                    complete: function () {
                        isRequestPending = false;
                    }
                });
            }, 5000);

            $('#search-form select').change(function () {
                $('#search-form').submit();
            });


            $(document).on('click', '.info-btn', function () {
                let key = $(this).data('key');
                let apiUrl = '/home/mail/' + key;

                // 发送 AJAX 请求获取 API 数据
                $.ajax({
                    url: apiUrl,
                    method: 'POST',
                    success: function (response) {
                        try {
                            // 解码 base64
                            let decodedContent = atob(response.data.body);
                            let uint8Array = new Uint8Array(decodedContent.split("").map(char => char.charCodeAt(0)));
                            let text = new TextDecoder('utf-8').decode(uint8Array);
                            $('#modalIframe').attr('srcdoc', text);

                            let decodedTitle = atob(response.data.title);
                            uint8Array = new Uint8Array(decodedTitle.split("").map(char => char.charCodeAt(0)));
                            text = new TextDecoder('utf-8').decode(uint8Array);

                            $('#exampleModalLabel').text(text);
                            // 显示模态框
                            $('#myModal').modal('show');


                        } catch (e) {
                            toastr.error("服务端返回了预料之外的数据.", "数据获取失败");
                            console.error('Error parsing API response or decoding base64:', e);
                        }
                    },
                    error: function (error) {
                        toastr.error("status code:" + error.status, "数据获取失败");
                        console.error('Error fetching API data:', error);
                    }
                });
            });


        });
    </script>
    @stop