<?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 = '卡密列表';
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"> <?php echo $title ?> </h3>
            <div class="block-options">
                <button type="button" class="btn btn-light btn-alt-secondary btn-xs" style="padding: 0.4375rem 0.925rem" onclick="showExportCard()">
                    导出卡密
                </button>
            </div>
        </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">生成卡密</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="generate_card" style="display: none;margin-bottom: 0!important;">
        <div class="text-center fw-semibold fs-sm">生成卡密</div>
        <div class="mt-2 mb-2" id="user_plans_div">
            <label class="form-label fs-sm text-muted" for="card_plans">选择套餐</label>
            <select class="form-select" id="card_plans" name="card_plans">
                <?php foreach (getPlans() as $value): ?>
                    <option value="<?php echo $value[ 'id' ] ?>"><?php echo $value[ 'name' ] ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mt-2 mb-2">
            <label class="form-label fs-sm text-muted" for="generate_num">生成数量</label>
            <input type="number" class="form-control form-control-alt" id="generate_num" name="generate_num" required placeholder="最大100张" max="100">
        </div>
        <button class="btn btn-sm btn-alt-primary me-1 m-1" onclick="submitCard()">
            <i class="fa fa-bolt opacity-50 me-1"></i> 生成
        </button>
    </div>

    <div class="block block-rounded block-content p-2" id="exportCardView" style="display: none;margin-bottom: 0!important;width: 272px;">
        <div class="text-center fw-semibold fs-sm">导出卡密</div>
        <div class="mt-2 mb-2" id="user_plans_div">
            <label class="form-label fs-sm text-muted" for="exp_card_plans">卡密套餐</label>
            <select class="form-select " id="exp_card_plans" name="exp_card_plans">
                <?php foreach (getPlans() as $value): ?>
                    <option value="<?php echo $value[ 'id' ] ?>"><?php echo $value[ 'name' ] ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mt-2 mb-2" id="user_plans_div">
            <label class="form-label fs-sm text-muted" for="card_status">使用状态</label>
            <select class="form-select " id="card_status" name="card_status">
                    <option value="0">未使用</option>
                    <option value="1">已使用</option>
            </select>
        </div>
        <button class="btn btn-sm btn-alt-primary me-1 m-1" onclick="exportCard()">
            <i class="fa fa-bolt opacity-50 me-1"></i> 导出
        </button>
    </div>

    <script>

        function viewAddKey ()
        {
            layer.open({
                type   : 1,
                shade  : false, // 遮障可点击，透明度为0.5
                title  : false,
                content: $('#generate_card'),
                cancel : () => {

                },
            })
        }

        function submitCard ()
        {
            if (app.getval('#generate_num') > 100) {
                app.btn('最多一次生成一百张', '我知道了')
                return ''
            }
            app.ajax('ajax_table.php?act=generate_card', {
                plans       : app.getval('#card_plans'),
                generate_num: app.getval('#generate_num')
            }, res => {
                if (res.code === 200) {
                    app.btn(res.msg, '我知道了', null, () => {
                        app.pjax('card_list.php')
                    })
                }
                else {
                    app.btn(res.msg, '我知道了')
                }
            })
        }

        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=delCard', {
                    id: checkbox
                }, res => {
                    if (res.code === 200) {
                        app.notify(res.msg, 'success')
                        setTimeout(() => {
                            app.pjax('card_list.php');
                        }, 1000)
                    }
                    else {
                        app.notify(res.msg, 'warning')
                    }
                })
            }, null)
        }

        function showExportCard ()
        {
            layer.open({
                type   : 1,
                shade  : false, // 遮障可点击，透明度为0.5
                title  : false,
                content: $('#exportCardView'),
                cancel : () => {

                },
            })
        }

        function exportCard ()
        {
            app.ajax('ajax_table.php?act=export_card', {
                exp_card_plans: app.getval('#exp_card_plans'),
                card_status   : app.getval('#card_status'),
            }, res => {
                if (res.code === 200) {
                    console.log(res)
                    const text = couponsToText(res.data);

                    const blob = new Blob([text], {type: 'text/plain'});
                    const url = URL.createObjectURL(blob);

                    const link = document.createElement('a');
                    link.download = '[<?php echo WEB_NAME ?> - 卡密信息].txt';
                    link.href = url;
                    link.click();

                    // 清理临时URL
                    URL.revokeObjectURL(url);
                }
                else if (res.code === 201) {
                    app.btn(res.msg, '我知道了')
                }
                else {
                    app.btn('导出失败', '我知道了')
                }
            })
        }

        function couponsToText (data)
        {
            return data.coupons.map(coupon => coupon.coupon).join('\n');
        }


        app.ajax('ajax_table.php?act=card_list', null, res => {
            if (res.code === 200) {
                let columns = [
                    {
                        field   : 'ID',
                        checkbox: true,
                    },
                    {
                        field: 'plan_name',
                        title: '套餐名称',
                    },
                    {
                        field: 'coupon',
                        title: '卡密信息',
                        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: 'is_used',
                        title: '是否使用',
                        formatter (value, row, index)
                        {
                            let colour = 'btn-alt-secondary'
                            if (value === '0') {
                                colour = 'btn-alt-warning'
                                value = '未使用'
                            }
                            else if (value === '1') {
                                colour = 'btn-alt-success'
                                value = '已使用'
                            }
                            else {
                                value = '未知'
                            }
                            return `<span class="btn btn-xs ${colour}">${value}</span>`
                        }
                    },
                    {
                        field: 'created_at',
                        title: '创建时间',
                    },
                    {
                        field: 'used_at',
                        title: '使用时间',
                        formatter (value, row, index)
                        {
                            if (!value) {
                                value = '未使用'
                            }
                            return value
                        }
                    }
                ];
                table.initTable('table', columns, res.data.custom, null, res.data.page);
            }
        })

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