<?php
/*
 * @author: CloudZA(云之安) <2922619853@qq.com>
 * @hitokoto: 一场秋雨一场凉，秋心酌满泪为霜。
 * Copyright (c) 2022 by CloudZA, All Rights Reserved.
 */

include_once 'common.php';
if ( !isset($islogin)) header("Location: /");//非法访问
$title = 'Key列表';
include_once 'partials/head.php';


?>
<div id="pjax-container">
    <!--导航-->
    <div class="bg-body-light">
        <div class="content content-full">
            <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">
                <div class="flex-grow-1">
                    <h1 class="h3 fw-bold mb-2">
                        <?php echo $title ?>
                    </h1>
                </div>
                <nav class="flex-shrink-0 mt-3 mt-sm-0 ms-sm-3" aria-label="breadcrumb">
                    <ol class="breadcrumb breadcrumb-alt">
                        <li class="breadcrumb-item">
                            <a class="link-fx" href="javascript:void(0)">首页</a>
                        </li>
                        <li class="breadcrumb-item" aria-current="page">
                            <?php echo $title ?>
                        </li>
                    </ol>
                </nav>
            </div>
        </div>
</div>
    <!--导航结束-->
    <!--内容-->
<div class="content">
    <link rel="stylesheet" id="css-main" href="<?php echo __CSS__ ?>bootstrap-table.css">
    <div class="block block-rounded">
        <div class="block-header block-header-default">
            <h3 class="block-title"> Key列表 </h3>
        </div>
        <div class="block-content">
            <form method="" class="form-inline" id="toolbar">
            <div class="dropdown d-inline-block">
                <button type="button" class="btn btn-light btn-alt-secondary btn-xs" style="padding: 0.4375rem 0.925rem" onclick="viewAddKey()">
                    <span class="d-sm-inline-block fw-semibold">添加Key</span>
                </button>
            </div>
                <a class="btn btn-light btn-alt-secondary btn-xs" style="padding: 0.4375rem 0.925rem" href="javascript:delChecks()">
                    <span class="d-sm-inline-block fw-semibold">删除选中</span>
                </a>

        </form>
            <table class="text-center fs-sm mb-2 ths" id="table"></table>
        </div>
    </div>

    <div class="block block-rounded block-content p-2" id="addKey" style="display: none;margin-bottom: 0!important;">
        <div class="text-center fw-semibold fs-sm">添加Key</div>
        <div class="form-floating mb-2">
            <textarea class="form-control" id="keys" name="keys" style="height: 80px;" placeholder=">添加Key，一行一条"></textarea>
            <label class="fs-sm text-muted" for="keys">添加Key，一行一条(最多20条)</label>
        </div>
        <button class="btn btn-sm btn-alt-primary me-1 m-1" id="submitKey">
            <i class="fa fa-bolt opacity-50 me-1"></i> 保存
        </button>
    </div>

    <script>
        $(() => {
            const keysTextarea = document.getElementById('keys');
            keysTextarea.addEventListener('input', function () {
                const lines = this.value.split('\n').length;
                if (lines > 20) {
                    app.btn('最多一次添加20条Key', '我知道了')
                }
            });
        })

        function viewAddKey ()
        {
            layer.open({
                type   : 1,
                shade  : false, // 遮障可点击，透明度为0.5
                title  : false,
                content: $('#addKey'),
                cancel : () => {
                    app.notify('取消添加', 'info')
                },
            })
        }

        $('#submitKey').click(() => {
            let keysTextarea = document.getElementById('keys');
            let keysArray = keysTextarea.value.split('\n').map(s => s.trim()).filter(s => s !== '');
            if (keysArray.length > 20) {
                app.btn('最多一次添加20条Key', '我知道了')
                return
            }
            if (keysArray.length > 0) {
                app.ajax('ajax_table.php?act=addKey', {
                    keys: keysArray
                }, res => {
                    if (res.code === 200) {
                        app.btn(res.msg, '我知道了', null, () => {
                            app.pjax('keylist.php')
                        })
                    }
                    else {
                        app.btn(res.msg, '我知道了')
                    }
                })
            }
            else {
                app.btn('Key 不能为空！', null)
            }
        })

        function PopKey (key)
        {
            app.btn(key, '复制', '取消', () => {
                const $textarea = $('<textarea>').css({
                    position: 'absolute',
                    left    : '-9999px'
                }).appendTo('body');
                if ($textarea.val(key)) {
                    app.notify('复制成功', 'success')
                }
                else {
                    app.notify('复制失败', 'warning')
                }
                $textarea[0].select();
                document.execCommand('copy');
                $textarea.remove();
                console.log('Text copied to clipboard:', key);
            }, null)
        }

        function delChecks ()
        {
            const selected = $('#table').bootstrapTable('getSelections')
            if (selected.length === 0) {
                app.notify('未选择记录', 'warning')
                return;
            }
            const checkbox = []
            $.each(selected, function (key, item) {
                checkbox.push(item.id)
            })
            app.btn('确定要删除选中的内容吗？删除之后不可恢复！', '确定', '取消', () => {
                app.ajax('ajax_table.php?act=delKey', {
                    id: checkbox
                }, res => {
                    if (res.code === 200) {
                        app.notify(res.msg, 'success')
                        app.pjax('keylist.php');
                    }
                    else {
                        app.notify(res.msg, 'warning')
                    }
                })
            }, null)
        }

        function setKeyStatus (id)
        {
            let checkbox = document.getElementById('key_status_' + id);
            let status = checkbox.checked ? '1' : '0';
            console.log(status)
            app.ajax('ajax_table.php?act=setKeyStatus', {
                id    : id,
                status: status
            }, res => {
                if (res.code === 200) {
                    app.notify(res.msg, 'success')
                }
                else {
                    app.notify(res.msg, 'warning')
                }
            });
        }

        app.ajax('ajax_table.php?act=key_list', null, res => {
            if (res.code === 200) {
                let columns = [
                        {
                            field   : 'ID',
                            checkbox: true,
                        },
                        {
                            field: 'gpt_keys',
                            title: 'Secret Key',
                            formatter (value, row, index)
                            {
                                let key = value.slice(0, 10) + '...';
                                return `<a class="link-primary" href="javascript:void(0)" onclick="PopKey('${value}')" ">${key}</a>`
                            }
                        },
                        {
                            field: 'key_status',
                            title: 'Key状态',
                            formatter (value, row, index)
                            {
                                return `<div class="form-check form-switch form-check-inline" style="margin-right:0;">
                                <input class="form-check-input" type="checkbox" value="" id="key_status_${row.id}" name="key_status_${row.id}" ${(value === '1') ? 'checked' : ''} onclick="setKeyStatus(${row.id})">
                            <label class="form-check-label" for="key_status"></label>
                        </div>`
                            }
                        },
                        {
                            field: 'granted',
                            title: '总额度(美金)',
                        },
                        {
                            field: 'available',
                            title: '剩余额度(美金)',
                            formatter (value, row, index)
                            {
                                let percentage = calculateUsagePercentage(value, row.granted)
                                return `${value}<div class="progress push mt-1 mb-0" style="height: 10px;">
            <div class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: ${percentage}%;" aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
          </div>`
                            }
                        },
                        {
                            field: 'used',
                            title: '已用额度(美金)',
                            formatter (value, row, index)
                            {
                                let percentage = calculateUsagePercentage(value, row.granted)
                                return `${value}<div class="progress push mt-1 mb-0" style="height: 10px;">
            <div class="progress-bar progress-bar-striped bg-warning" role="progressbar" style="width: ${percentage}%;" aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
          </div>`
                            }
                        },
                        {
                            field: 'effective_at',
                            title: '起始时间'
                        },
                        {
                            field: 'expires_at',
                            title: '过期时间'
                        },
                        {
                            field: 'gpt_keys',
                            title: '操作',
                            formatter (value, row, index)
                            {
                                return '<a type="button" class="btn btn-sm btn-alt-primary" href="javascript:Refresh(\'' + value + '\')">刷新</a>';
                            }

                        }
                    ]
                ;
                table.initTable('table', columns, res.data.custom, null, res.data.page);
            }
        })

        function Refresh (key)
        {
            app.ajax('ajax_table.php?act=refresh_key', {key: key}, res => {
                if (res.code === 200) {
                    app.btn(res.msg, '确定', null, () => {
                        app.pjax('keylist.php');
                    })
                }
                else {
                    app.btn(res.msg)
                }
            })
        }

    </script>
</div>
</div>
    <!--内容结束-->
<?php include_once 'partials/foot.php'; ?>
