<?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:74:"/home/wwwroot/juliang/fa/public/../application/index/view/index/phone.html";i:1737081335;}*/ ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $gongsi; ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #444;
            background: linear-gradient(to bottom, #e0f7fa, #f1f8e9); /* 更柔和的背景渐变 */
            background-attachment: fixed;
            background-repeat: no-repeat;
            background-size: cover;
        }

        h2 {
            text-align: center;
            color: #00796b; /* 更深的绿色 */
            font-weight: 500;
            margin-bottom: 30px;
        }

        .container {
            padding: 30px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1); /* 更柔和的阴影 */
            max-width: 100%;
            width: 100%;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 15px;
        }

        label {
            margin-right: 10px;
            font-weight: 400;
            color: #555; /* 改为更深的灰色 */
        }

        input[type="text"],
        select,
        button {
            padding: 12px;
            font-size: 15px; /* 增加输入框和按钮的字体大小 */
            border: 1px solid #ccc;
            border-radius: 8px;
            background-color: #fafafa;
            color: #333;
            transition: all 0.3s ease;
            width: 100%; 
            box-sizing: border-box; 
        }

        input[type="text"]:focus,
        select:focus,
        button:hover {
            border-color: #00796b; /* 按钮和输入框获得焦点时，边框变为绿色 */
            background-color: #e0f2f1; /* 更柔和的按钮悬停背景 */
        }

        button {
            background-color: #00796b;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
            padding: 12px 25px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        button:hover {
            background-color: #004d40; /* 更深的绿色 */
        }

        button:disabled {
            background-color: #b2dfdb;
            cursor: not-allowed;
        }

        .summary-group {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            margin-top: 10px;
            gap: 10px;
        }
        
        .form-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.form-item {
    flex: 0 0 48%; /* 让每个元素占据大约一半的宽度 */
    margin-bottom: 10px;
}
.summary-group {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

#income-ecpm-group {
    display: flex;
    justify-content: space-between;
    gap: 20px; /* 可根据需要调整间距 */
}

#totalCost, #ecpmValue {
    margin: 0;
}


label, select, input, button {
    display: block;
    width: 100%;
    margin-bottom: 8px;
}


        #totalCost,
        #ecpmValue {
            font-family: 'Arial', sans-serif;
            font-size: 16px;
            color: #444;
            padding: 8px 18px;
            display: inline-block;
            background-color: #f7f7f7;
            border: 1px solid #ddd;
            border-radius: 8px;
        }

        #result {
            width: 100%;
            margin-top: 20px;
            overflow-x: auto;
            max-height: 600px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th,
        td {
            padding: 14px;
            border: 1px solid #e0e0e0;
            text-align: left;
        }

        th {
            background-color: #f0f0f0;
            font-weight: 500;
            color: #333;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        tr:hover {
            background-color: #f1f1f1;
        }

        .pagination {
            justify-content: space-between;
            margin-top: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
            color: #00796b;
        }

        .pagination button {
            padding: 12px 18px;
            margin: 0 5px;
            border-radius: 6px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .custom-showModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2);
            display: none;
        }

        .modal-content {
            background-color: #fff;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            width: 80%;
            max-width: 400px;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .custom-showModal h3 {
            margin-top: 0;
            color: #00796b;
        }

        .custom-showModal p {
            font-size: 14px;
            margin: 10px 0;
            color: #555;
        }

        .custom-showModal button {
            background-color: #00796b;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .custom-showModal button:hover {
            background-color: #004d40;
        }

        .close-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            cursor: pointer;
            background-color: #00796b;
            color: white;
            height: 30px;
            width: 30px;
            border-radius: 50%;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: none;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: background-color 0.3s;
        }

        .close-btn:hover {
            background-color: #004d40;
        }

        @media (max-width: 768px) {
            .form-group {
                flex-direction: column;
                align-items: stretch;
            }

            button {
                width: 100%;
                margin-bottom: 10px;
            }

            #result {
                max-height: 400px;
            }

            .summary-group {
                align-items: stretch;
            }
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/zh.js"></script>
</head>


<body>

<div class="container">
    <div id="chartsContainer" style="display: none; margin-top: 20px;">
        <button id="closeChartsBtn">关闭图表</button>
        <canvas id="openIdChart"></canvas>
        <canvas id="timeChart"></canvas>
    </div>
    <div id ="newContainer">
        <h1><?php echo $gongsi; ?></h1>
        <div class="form-group">
    <div class="form-item">
        <label for="dropdownList">游戏名称:</label>
        <select id="dropdownList"></select>
    </div>
    
    <div class="form-item">
        <label for="datePicker">日期:</label>
        <input type="text" id="datePicker" autocomplete="off">
    </div>

    <div class="form-item">
        <label for="inputOpenIdList">OpenID:</label>
        <input type="text" id="inputOpenIdList" placeholder="OpenID">
    </div>

    <div class="form-item">
        <label for="itemsPerPage">每页条数:</label>
        <select id="itemsPerPage">
            <option value="500">500</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>

    <div class="form-item">
        <button id="submitBtn">查询</button>
    </div>

    <div class="form-item">
        <button id="toggleChartsBtn">查看图表</button>
    </div>
</div>


        <!-- 查询总收入和 ECPM 的内容 -->
       <div class="summary-group">
    <button id="extraRequestBtn">查询ECPM</button>
    <div id="income-ecpm-group">
        <div id="totalCost">总收入: <span id="totalIncome">0</span></div>
        <div id="ecpmValue">ECPM: <span id="ecpm">0</span></div>
    </div>
</div>


        <div id="loader" class="loader-container">
            <div class="loader"></div>
            <div class="loader-text">加载中···</div>
        </div>

        <div id="result">
            <table>
                <thead>
                <tr>
                    <th>Id</th>
                    <th id="sortCost" data-order="asc">广告单价<span class="sort-arrow"></span></th>
                    <th id="sortEventTime" data-order="asc">日期时间<span class="sort-arrow"></span></th>
                    <th>OpenId</th>
                    <th>IP</th>
                    <th>地区</th>
                    <th>手机品牌</th>
                    <th>手机型号</th>
                    <th>系统版本</th>
                    <th>事件名称</th>

                    <!--                    <th>头像</th>-->
                    <!--                    <th>抖音名称</th>-->
                </tr>
                </thead>
                <tbody id="dataBody"></tbody>
            </table>
        </div>

        <div class="pagination" id="pagination">
            <button id="prevPage" disabled>上一页</button>
            <button id="nextPage" disabled>下一页</button>
            <span id="pageInfo"></span>
            <span id="totalRows"></span>
            <span id="totalCostOnPage"></span>

            <label for="jumpToPage">跳转到第</label>
            <input type="number" id="jumpToPage" min="1" style="width: 50px;">
            <button id="jumpPageBtn">跳转</button>
        </div>

        <div id="errorContainer" style="color: red;"></div>
    </div>
</div>
<!-- 模态框 -->
<div id="modal" class="modal">
    <div class="modal-content">
        <span class="close-btn">&times;</span>
        <p id="modal-text"></p>
        <button id="modal-ok-btn" class="modal-ok-btn">确定</button>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 清空下拉框
        $('#dropdownList').empty();

        var gameList = <?php echo $game_list; ?>;
        if(gameList.length != 0){
            // 遍历 gameList 对象，添加选项到下拉框
            $.each(gameList, function(key, value) {
                $('#dropdownList').append($('<option></option>').val(key).text(value));
            });
        }

        // 设置日期选择器为今天的日期
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
        $('#datePicker').val(formattedDate);

        flatpickr("#datePicker", {
            dateFormat: "Y-m-d",
            locale: "zh" // 设置为中文
        });


        let currentPage = 1;
        let itemsPerPage = 500; // 默认每页条数
        let sortField = 'cost'; // 默认排序字段
        let sortOrder = 'desc'; // 默认排序方向
        let openIdChart;
        let timeChart;
        function fetchData() {

            const game = $('#dropdownList').val();
            const open_id_list = $('#inputOpenIdList').val();
            const date = $('#datePicker').val();

            const pageSize = itemsPerPage;

            $('#loader').show();

            $.ajax({
                url: '/',  // 替换为你的 API 端点
                type: 'GET',
                data: {
                    game_list: game,
                    open_id_list: open_id_list,
                    time: date,
                    page: currentPage,
                    pageSize: pageSize,
                    sort: sortField,  // 添加 sort 字段
                    order: sortOrder,  // 添加 order 字段
                },
                success: function (data) {
                    // 假设 data 返回的格式是 { totalIncome: number, ecpm: number, items: Array }
                    if(data.code == 0){
                        alert(data.err_msg)
                    }else{
                        renderTable(data.rows);
                        updatePagination(data.total); // 更新分页信息
                        const openIdData = JSON.parse(data.openIdData); // 解析 OpenID 数据
                        const timeData = JSON.parse(data.timeData); // 解析时间段数据
                        // 假设你的 API 返回 openIdData 和 timeData
                        drawCharts(openIdData,timeData);
                    }
                },
                error: function (error) {
                    alert('数据加载失败');
                },
                complete: function () {
                    $('#loader').hide();
                }
            });
        }

        function fetchTotal() {
            const game = $('#dropdownList').val();
            const date = $('#datePicker').val();

            $('#loader').show();

            $.ajax({
                url: '/index/index/get_ecpm',  // 替换为你的 API 端点
                type: 'GET',
                data: {
                    game_list: game,
                    time: date,
                },
                success: function (data) {
                    if(data.arr.code == 1 ){
                        $('#totalIncome').text(data.arr.totalCost || 0);
                        $('#ecpm').text(data.arr.ecpm || 0);

                    }else{
                        alert(data.arr.err_msg)
                    }
                },
                error: function (error) {
                    alert('数据加载失败');
                },
                complete: function () {
                    $('#loader').hide();
                }
            });
        }
// 查询数据成功后绘制图表
        function drawCharts(openIdData, timeData) {
            const ctxOpenId = document.getElementById('openIdChart').getContext('2d');
            const ctxTime = document.getElementById('timeChart').getContext('2d');

            // 清除之前的图表
            if (openIdChart) openIdChart.destroy();
            if (timeChart) timeChart.destroy();

            // 创建 OpenID 总 Cost 图表
            openIdChart = new Chart(ctxOpenId, {
                type: 'bar',
                data: {
                    labels: Object.keys(openIdData),
                    datasets: [{
                        label: '总 Cost',
                        data: Object.values(openIdData),
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '图1：不同OPENID/COST总和',
                            font: {
                                size: 20 // 调整字体大小
                            }
                        }
                    }
                }
            });

            // 创建时间段总 Cost 图表
            timeChart = new Chart(ctxTime, {
                type: 'line',
                data: {
                    labels: Object.keys(timeData),
                    datasets: [{
                        label: '总 Cost',
                        data: Object.values(timeData),
                        fill: false,
                        borderColor: 'rgba(153, 102, 255, 1)',
                        tension: 0.1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '图2：各时间段COST总和',
                            font: {
                                size: 20 // 调整字体大小
                            }
                        }
                    }
                }
            });
        }
        function renderTable(items) {
            const dataBody = $('#dataBody');
            let totalCost = 0; // 初始化当前页的总费用

            dataBody.empty();
            items.forEach(item => {
                totalCost += parseFloat(item.cost); // 累加每一项的 cost
                dataBody.append(`
           <tr>
                <td>${item.id}</td>
                <td>${item.cost}</td>
                <td>${item.event_time}</td>
                <td>
                    ${item.open_id}
                    <button class="copy-btn" data-open-id="${item.open_id}">复制</button>
                </td>
                <td>${item.ip}</td>
                <td>${item.location}</td>
                <td>${item.brand}</td>
                <td>${item.model}</td>
                <td>${item.edition}</td>
                <td>${item.event_name}</td>
            </tr>
        `);
            });

            // 更新当前页总费用
            $('#totalCostOnPage').text(`当前表格数据总费用: ${totalCost.toFixed(2)}`);

            // 绑定复制按钮事件
            $('.copy-btn').on('click', function() {
                const openId = $(this).data('open-id');
                const tempInput = document.createElement('input');
                tempInput.value = openId;
                document.body.appendChild(tempInput);
                tempInput.select();
                document.execCommand('copy');
                document.body.removeChild(tempInput);
                alert('复制成功: ' + openId);
            });
        }

        function alert(message) {
            const modal = $('#modal');
            const modalText = $('#modal-text');
            const closeBtn = $('.close-btn');
            const okBtn = $('#modal-ok-btn');

            modalText.text(message);
            modal.css('display', 'flex'); // 显示模态框

            // 关闭按钮和 OK 按钮点击时隐藏模态框
            closeBtn.off().click(function () {
                modal.hide(); // 隐藏模态框
            });
            okBtn.off().click(function () {
                modal.hide(); // 隐藏模态框
            });

            // 点击模态框外部也隐藏模态框
            $(window).off('click').click(function (event) {
                if (event.target === modal[0]) {
                    modal.hide(); // 隐藏模态框
                }
            });
        }


        let totalPages = 0; // 定义总页数变量

        function updatePagination(totalItems) {
            totalPages = Math.ceil(totalItems / itemsPerPage); // 更新总页数
            $('#prevPage').prop('disabled', currentPage === 1);
            $('#nextPage').prop('disabled', currentPage === totalPages || totalPages === 0);
            $('#pageInfo').text(`第 ${currentPage} 页，共 ${totalPages} 页`);

            // 更新总行数
            $('#totalRows').text(`数据行数: ${totalItems}`);
        }
        $('#submitBtn').click(function () {
            currentPage = 1; // 重置到第一页
            itemsPerPage = $('#itemsPerPage').val(); // 获取用户选择的每页条数
            fetchData();
        });

        $('#nextPage').click(function () {
            currentPage++;
            fetchData();
        });

        $('#prevPage').click(function () {
            currentPage--;
            fetchData();
        });

        $('#extraRequestBtn').click(function () {
            fetchTotal();
        });

        $('#sortCost').click(function () {
            // 获取当前排序顺序
            const currentOrder = this.getAttribute('data-order');

            // 切换排序顺序
            const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            this.setAttribute('data-order', newOrder);

            sortOrder = (sortOrder === 'asc') ? 'desc' : 'asc'; // 切换排序方向
            sortField = 'cost';
            fetchData(); // 重新请求数据
        });
        $('#sortEventTime').click(function () {
            // 获取当前排序顺序
            const currentOrder = this.getAttribute('data-order');

            // 切换排序顺序
            const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            this.setAttribute('data-order', newOrder);

            sortOrder = (sortOrder === 'asc') ? 'desc' : 'asc'; // 切换排序方向
            sortField = 'event_time';

            // 重新请求数据并传递排序参数
            fetchData(newOrder); // 传递新的排序顺序
        });

        // 页码跳转功能
        $('#jumpPageBtn').click(function () {
            const jumpPage = parseInt($('#jumpToPage').val());
            if (!isNaN(jumpPage) && jumpPage > 0 && jumpPage <= totalPages) {
                currentPage = jumpPage;
                fetchData();
            } else if (jumpPage > totalPages) {
                alert(`页码不能大于总页数: ${totalPages}`);
            } else {
                alert("请输入有效的页码");
            }
        });

        // 事件：点击关闭图表按钮
        $('#closeChartsBtn').click(function () {
            $('#chartsContainer').hide(); // 隐藏图表
            $('#newContainer').show(); // 打开页面
        });
        function adjustChartHeight() {
            const containerHeight = $('#chartsContainer').height();
            const chartHeight = (containerHeight - 20) / 2; // 减去 gap 和 padding
            $('#openIdChart').attr('height', chartHeight);
            $('#timeChart').attr('height', chartHeight);
        }

        // 在显示图表时调整图表高度
        $('#toggleChartsBtn').click(function () {
            $('#chartsContainer').show(); // 显示图表
            adjustChartHeight(); // 调整图表高度
            $('#newContainer').hide(); // 打开页面
        });

        // 当窗口大小变化时重新调整图表高度
        $(window).resize(function() {
            if ($('#chartsContainer').is(':visible')) {
                adjustChartHeight();
            }
        });
        // 初始数据加载
        if(gameList.length != 0){
            fetchData();
        }else{
            $(".container").hide();
        }
    });
</script>
</body>
</html>
