define(['jquery'], function ($) {
    var Controller = {
        index: function () {
            var getColor = function (color) {
                if (!color || color === '—') return '#95a5a6';
                if (color.indexOf('红') !== -1) return '#e74c3c';
                if (color.indexOf('蓝') !== -1) return '#3498db';
                if (color.indexOf('绿') !== -1) return '#2ecc71';
                return '#95a5a6';
            };

            var ball = function (num, color) {
                return '<span class="num-ball-sm" style="background-color:' + getColor(color) + ';">' + num + '</span>';
            };

            function loadData() {
                var periods = parseInt($('#dash-periods').val()) || 30;
                if (periods < 10) periods = 10;
                if (periods > 100) periods = 100;
                $('#dash-content').html('<div class="text-center" style="padding:60px;"><i class="fa fa-spinner fa-spin fa-2x"></i><br><span class="text-muted">' + __('Loading') + '</span></div>');

                $.ajax({
                    url: 'history/dashboard',
                    type: 'GET',
                    data: {periods: periods},
                    dataType: 'json',
                    success: function (ret) {
                        if (ret.code != 1) {
                            $('#dash-content').html('<div class="alert alert-danger">' + (ret.msg || '加载失败') + '</div>');
                            return;
                        }
                        render(ret.data);
                    },
                    error: function () {
                        $('#dash-content').html('<div class="alert alert-danger">请求失败，请重试</div>');
                    }
                });
            }

            function render(data) {
                var hc = data.hotcold, cw = data.colorwave, zo = data.zodiac;
                var oe = data.oddeven, bs = data.bigsmall, sp = data.special, tn = data.tailnumbers;

                var html = '';

                html += '<div class="dash-section"><h4>🔥❄️ 冷热号码</h4><div class="row">';
                html += '<div class="col-sm-6"><div class="dash-card" style="border-left:3px solid #e74c3c;"><div style="color:#e74c3c;font-weight:bold;margin-bottom:8px;">热号 Top 5</div>';
                for (var i = 0; i < 5; i++) html += ball(hc.hot[i].num, hc.hot[i].color) + ' ';
                html += '</div></div>';
                html += '<div class="col-sm-6"><div class="dash-card" style="border-left:3px solid #3498db;"><div style="color:#3498db;font-weight:bold;margin-bottom:8px;">冷号 Top 5</div>';
                for (var i = 0; i < 5; i++) html += ball(hc.cold[i].num, hc.cold[i].color) + ' ';
                html += '</div></div></div></div>';

                html += '<div class="dash-section"><h4>📊 比例分析</h4><div class="row">';
                html += '<div class="col-sm-4"><div class="dash-card"><div id="colorwave-chart" style="width:100%;height:200px;"></div></div></div>';
                html += '<div class="col-sm-4"><div class="dash-card"><div id="oddeven-chart" style="width:100%;height:200px;"></div></div></div>';
                html += '<div class="col-sm-4"><div class="dash-card"><div id="bigsmall-chart" style="width:100%;height:200px;"></div></div></div>';
                html += '</div></div>';

                html += '<div class="dash-section"><h4>⭐ 生肖排名</h4><div id="zodiac-chart" style="width:100%;height:250px;"></div></div>';

                html += '<div class="dash-section"><h4>📈 特码走势</h4><div id="special-chart" style="width:100%;height:280px;"></div></div>';

                html += '<div class="dash-section"><h4>🔢 尾数频率</h4><div id="tail-chart" style="width:100%;height:220px;"></div></div>';

                $('#dash-content').html(html);

                // 波色饼图
                if (typeof echarts !== 'undefined') {
                    var cwDom = document.getElementById('colorwave-chart');
                    if (cwDom) {
                        var cwChart = echarts.init(cwDom);
                        cwChart.setOption({
                            tooltip: {trigger: 'item', formatter: '{b}: {c} ({d}%)'},
                            series: [{
                                type: 'pie', radius: '60%',
                                data: [
                                    {value: cw.red, name: '红波', itemStyle: {color: '#e74c3c'}},
                                    {value: cw.blue, name: '蓝波', itemStyle: {color: '#3498db'}},
                                    {value: cw.green, name: '绿波', itemStyle: {color: '#2ecc71'}}
                                ],
                                label: {show: true, formatter: '{b}\n{d}%'},
                                emphasis: {itemStyle: {shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)'}}
                            }],
                            grid: {top: 0, bottom: 0}
                        });
                        $(window).on('resize', function(){ cwChart.resize(); });
                    }

                    // 奇偶饼图
                    var oeDom = document.getElementById('oddeven-chart');
                    if (oeDom) {
                        var oeChart = echarts.init(oeDom);
                        oeChart.setOption({
                            tooltip: {trigger: 'item', formatter: '{b}: {c} ({d}%)'},
                            series: [{
                                type: 'pie', radius: '60%',
                                data: [
                                    {value: oe.odd, name: '奇数', itemStyle: {color: '#e74c3c'}},
                                    {value: oe.even, name: '偶数', itemStyle: {color: '#3498db'}}
                                ],
                                label: {show: true, formatter: '{b}\n{d}%'},
                                emphasis: {itemStyle: {shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)'}}
                            }],
                            grid: {top: 0, bottom: 0}
                        });
                        $(window).on('resize', function(){ oeChart.resize(); });
                    }

                    // 大小饼图
                    var bsDom = document.getElementById('bigsmall-chart');
                    if (bsDom) {
                        var bsChart = echarts.init(bsDom);
                        bsChart.setOption({
                            tooltip: {trigger: 'item', formatter: '{b}: {c} ({d}%)'},
                            series: [{
                                type: 'pie', radius: '60%',
                                data: [
                                    {value: bs.big, name: '大数', itemStyle: {color: '#f39c12'}},
                                    {value: bs.small, name: '小数', itemStyle: {color: '#2ecc71'}}
                                ],
                                label: {show: true, formatter: '{b}\n{d}%'},
                                emphasis: {itemStyle: {shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)'}}
                            }],
                            grid: {top: 0, bottom: 0}
                        });
                        $(window).on('resize', function(){ bsChart.resize(); });
                    }
                }

                // 生肖柱状图
                if (typeof echarts !== 'undefined' && zo.list && zo.list.length > 0) {
                    var zDom = document.getElementById('zodiac-chart');
                    if (zDom) {
                        var zChart = echarts.init(zDom);
                        zChart.setOption({
                            tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
                            grid: {left: 50, right: 20, bottom: 30, top: 10},
                            xAxis: {type: 'category', data: zo.list.map(function(z){return z.animal;})},
                            yAxis: {type: 'value', splitNumber: 3},
                            series: [{type: 'bar', data: zo.list.map(function(z){return z.count;}), itemStyle: {color: '#626c91'}, label: {show: true, position: 'top', fontSize: 12, color: '#333'}}]
                        });
                        $(window).on('resize', function(){ zChart.resize(); });
                    }
                }

                // 特码走势
                if (typeof echarts !== 'undefined' && sp.expects && sp.expects.length > 0) {
                    var chartDom = document.getElementById('special-chart');
                    if (chartDom) {
                        var chart = echarts.init(chartDom);
                        var colorMap = {'红': '#e74c3c', '蓝': '#3498db', '绿': '#2ecc71'};
                        var itemColors = sp.colors.map(function(c) {
                            if (c.indexOf('红') !== -1) return colorMap['红'];
                            if (c.indexOf('蓝') !== -1) return colorMap['蓝'];
                            if (c.indexOf('绿') !== -1) return colorMap['绿'];
                            return '#95a5a6';
                        });
                        chart.setOption({
                            tooltip: {trigger: 'axis', formatter: function(p) {
                                return '期号: ' + p[0].axisValue + '<br/>特码: <b style="color:' + itemColors[p[0].dataIndex] + '">' + p[0].data + '</b>';
                            }},
                            xAxis: {type: 'category', data: sp.expects, axisLabel: {rotate: 45, fontSize: 10}},
                            yAxis: {type: 'value', min: 0, max: 50},
                            series: [{type: 'line', data: sp.specials, smooth: true, symbolSize: 8, itemStyle: {color: function(p) { return itemColors[p.dataIndex]; }}, areaStyle: {color: 'rgba(52,152,219,0.05)'}}],
                            grid: {left: 50, right: 20, bottom: 50, top: 20}
                        });
                        $(window).on('resize', function () { chart.resize(); });
                    }
                }

                // 尾数柱状图
                if (typeof echarts !== 'undefined' && tn.all && tn.all.length > 0) {
                    var tDom = document.getElementById('tail-chart');
                    if (tDom) {
                        var tChart = echarts.init(tDom);
                        var sorted = tn.all.slice().sort(function(a,b){return a.tail - b.tail;});
                        tChart.setOption({
                            tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
                            grid: {left: 50, right: 20, bottom: 30, top: 10},
                            xAxis: {type: 'category', data: sorted.map(function(t){return t.tail;})},
                            yAxis: {type: 'value', splitNumber: 3},
                            series: [{type: 'bar', data: sorted.map(function(t){return t.count;}), itemStyle: {color: '#23b7e5'}, label: {show: true, position: 'top', fontSize: 12, color: '#333'}}]
                        });
                        $(window).on('resize', function(){ tChart.resize(); });
                    }
                }
            }

            $('#btn-dash-refresh').on('click', loadData);
            loadData();
        }
    };

    return Controller;
});
