<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>SIM卡信息查询</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" id="searchForm" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">查询类型</label>
                            <div class="layui-input-inline">
                                <select name="searchType" lay-verify="required">
                                    <option value="deviceId">设备号</option>
                                    <option value="iccid">ICCID</option>
                                    <option value="simNumber">SIM卡号</option>
                                    <option value="imei">IMEI</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">搜索内容</label>
                            <div class="layui-input-inline">
                                <input type="text" name="searchContent" id="searchInput" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select name="status">
                                    <option value="">全部</option>
                                    <option value="1">待激活</option>
                                    <option value="2">已激活</option>
                                    <option value="3">停机</option>
                                    <option value="4">注销</option>
                                    <option value="5">库存</option>
                                    <option value="6">可测试</option>
                                    <option value="7">失效</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="searchSubmit"><i class="layui-icon">&#xe615;</i> 搜 索</button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-export-btn"><i class="layui-icon">&#xe67d;</i> 导出</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <div class="layui-tab layui-tab-card" lay-filter="data-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">数据表格</li>
                <li>流量图表</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <table class="layui-hide" id="simTable" lay-filter="simTableFilter"></table>
                </div>
                <div class="layui-tab-item">
                    <div id="trafficChart" style="min-height:300px;padding: 10px"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../js/lay-module/echarts/echartsTheme.js" charset="utf-8"></script>
<script src="../js/lay-module/echarts/echarts.js" charset="utf-8"></script>
<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script type="text/html" id="statusTpl">
    {{#  if(d.status === 1){ }}
    <span class="layui-badge layui-bg-orange">待激活</span>
    {{#  } else if(d.status === 2){ }}
    <span class="layui-badge layui-bg-green">已激活</span>
    {{#  } else if(d.status === 3){ }}
    <span class="layui-badge layui-bg-red">停机</span>
    {{#  } else if(d.status === 4){ }}
    <span class="layui-badge layui-bg-black">注销</span>
    {{#  } else if(d.status === 5){ }}
    <span class="layui-badge layui-bg-blue">库存</span>
    {{#  } else if(d.status === 6){ }}
    <span class="layui-badge layui-bg-cyan">可测试</span>
    {{#  } else if(d.status === 7){ }}
    <span class="layui-badge">失效</span>
    {{#  } }}
</script>
<script th:inline="javascript">

    layui.use(['form', 'table','layer','element'], function () {
        var table = layui.table
            ,form = layui.form
            ,layer = layui.layer
            ,element = layui.element;

        var flowChart;
        function initEcharts() {
            if (!flowChart) {
                flowChart = echarts.init(document.getElementById('trafficChart'), 'theme');
            }
        }
        function updateFlowChart(simData) {
            initEcharts();

            var used = simData.used ? (simData.used / 1000) : 0;
            var remaining = simData.remaining ? (simData.remaining / 1000) : 0;
            var total = simData.total ? (simData.total / 1000) : (used + remaining);

            var option = {
                title: {
                    text: 'SIM卡流量使用情况',
                    left: 'center',
                    top: 20,
                    textStyle: {
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}MB ({d}%)'
                },
                legend: {
                    orient: 'horizontal',  // 改为水平布局
                    bottom: 20,           // 放在底部
                    left: 'center',       // 居中对齐
                    itemWidth: 25,
                    itemHeight: 14
                },
                series: [
                    {
                        name: '流量使用情况',
                        type: 'pie',
                        radius: ['40%', '60%'],  // 调整饼图大小
                        center: ['50%', '50%'],  // 居中显示
                        avoidLabelOverlap: false,
                        label: {
                            show: true,
                            position: 'outside', // 标签位置改为外部
                            formatter: function(params) {
                                return params.name + '\n' +
                                    params.value + 'MB\n' +
                                    params.percent + '%';
                            },
                            fontSize: 14,
                            lineHeight: 20
                        },
                        labelLine: {
                            show: true,
                            length: 15,
                            length2: 10
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 16,
                                fontWeight: 'bold'
                            }
                        },
                        data: [
                            {
                                value: used,
                                name: '已使用流量',
                                itemStyle: { color: '#FF5722' }
                            },
                            {
                                value: remaining,
                                name: '剩余流量',
                                itemStyle: { color: '#009688' }
                            }
                        ]
                    }
                ]
            };

            document.getElementById('trafficChart').style.height = '400px';

            flowChart.setOption(option);
            flowChart.resize();  // 重新调整大小

        }

        var data_cols = [
            {field: 'deviceid', title: '设备号'},
            {field: 'iccid', title: 'ICCID'},
            {field: 'msisdn', title: 'SIM 卡号'},
            {field: 'imei', title: 'IMEI'},
            {field: 'updateTime', title: '更新时间',templet: "<div>{{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"},
            {field: 'status', title: '状态',templet: '#statusTpl'},
            {field: 'remaining', title: '剩余流量(MB)', templet: function(d) {
                return d.remaining ? (d.remaining / 1000).toFixed(2) : '0';
            }},
            {field: 'used', title: '已使用流量(MB)', templet: function(d) {
                return d.used ? (d.used / 1000).toFixed(2) : '0';
            }},
            {field: 'total', title: '总流量(MB)', templet: function(d) {
                return d.total ? (d.total / 1000).toFixed(2) : '0';
            }}

        ];

        form.render();
        table.render({
            elem: '#simTable',
            url: '/sim/list',
            toolbar: '#toolbarDemo', //开启头部工具栏
            defaultToolbar: ['filter'],
            cols: [
                data_cols
            ],
            limits: [20, 50, 100, 200, 300],
            limit: 20,
            page: true,
            skin: 'line',
            done: function(res) {
            if(res.code !== 0) {
                layer.msg(res.msg || '查询失败', {icon: 2});
            }
        }
        });

        form.verify({
            searchContent: function(value, item) {
                var type = $('select[name="searchType"]').val();
                if(!value) {
                    return '请输入搜索内容';
                }
                if(type === 'iccid' && !/^\d{19,20}$/.test(value)) {
                    return 'ICCID必须是19-20位数字';
                }
                if(type === 'simNumber' && !/^\d{11,13}$/.test(value)) {
                    return 'SIM卡号必须是11-13位数字';
                }
            }
        });

        form.on('submit(searchSubmit)', function(data){
            var loadIndex = layer.load(1);
            table.reload('simTable', {
                page: {
                    curr: 1
                }
                ,where: {
                    searchType: data.field.searchType,
                    searchContent: data.field.searchContent,
                    status: data.field.status
                }
                ,done: function(res) {
                    layer.close(loadIndex);
                    if(res.code !== 0) {
                        layer.msg(res.msg || '查询失败', {icon: 2});
                    } else if(res.count === 0) {
                        layer.msg('未找到符合条件的数据', {icon: 0});
                    }else if(res.count === 1) {
                        // 当查询结果只有一条数据时，使用该数据绘制饼图
                        updateFlowChart(res.data[0]);
                    }
                }
            });
            return false;
        });
        
        form.on('submit(data-export-btn)', function (data) {
            layer.open({
                type: 1,
                title: '导出选项',
                shadeClose: true,
                content: `
                    <div style="padding: 20px;">
                        <div class="layui-form" lay-filter="exportForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">导出范围</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="exportRange" value="current" title="当前页" checked>
                                    <input type="radio" name="exportRange" value="all" title="全部数据">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="confirmExport">确定</button>
                                    <button type="reset" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `,
                success: function(layero, index) {
                    form.render('radio', 'exportForm');
                    
                    // 监听导出确认
                    form.on('submit(confirmExport)', function(formData) {
                        var searchData = data.field;
                        var url = '/sim/export?';
                        if (searchData.searchType) {
                            url += 'searchType=' + searchData.searchType;
                        }
                        if (searchData.searchContent) {
                            url += '&searchContent=' + encodeURIComponent(searchData.searchContent);
                        }
                        if (searchData.status) {
                            url += '&status=' + searchData.status;
                        }
                        
                        // 获取当前表格的页大小（limit）
                        var currentLimit = layui.table.cache.simTable ? layui.table.cache.simTable.limit : 20;
                        
                        // 添加导出范围参数
                        var exportAll = formData.field.exportRange === 'all';
                        url += '&exportAll=' + exportAll;
                        
                        // 如果导出当前页，则传递页大小
                        if (!exportAll) {
                            url += '&pageSize=' + currentLimit;
                        }
                        
                        window.location.href = url;
                        layer.close(index);
                        return false;
                    });
                }
            });
            
            return false;
        });

        //监听Tab切换，重新resize图表，否则显示不出来
        element.on('tab(data-tab)', function(data){
            if(data.index === 1 && flowChart) {
                flowChart.resize();
            }
        });

        // 监听窗口大小变化
        window.addEventListener('resize', function() {
            if (flowChart) {
                flowChart.resize();
            }
        });
    });
</script>
</body>
</html>