{% load i18n %}

<script src="/static/js/echarts.min.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
        <script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>

<style>
    .charts{
        height: 95%;
        width: 100%;
    }
    #qty{
        height:340px;
        width: 100%;
    }
    .pie-charts{        
        height:500px;
        width: 58%;
    }
    #col-chart {
        width: 100%;
        height: 100%;
    }

    .btn-last-month,
    .btn-next-month {
        background: #f5f5f5;
        color: #666666;
        border: 1px solid #d5d5d5;
        box-shadow: 1px 1px 7px #d5d5d5;
    }
    .panel-like {
        padding: 10px 0 0 0;
        border: 1px solid #d5d5d5;
        border-radius: 20px;
        box-shadow: 1px 8px 11px #dbdbdb;
        display: inline-block;
    }
    #ranking {
        margin-left: 1%;
        width: 98%;
    }
    #ranking2 {
        margin-left: 1%;
        width: 98%;
        margin-top: 2rem;
    }
    .red {
        color: red;
    }
    .green {
        color: green;
    }
    #ranking-list {
        padding: 0 1rem;
    }
    #ranking-list2 {
        padding: 0 1rem;
    }
    .ranking-list-item {
        list-style: none;
        height: 3rem;
        line-height: 3rem;
        font-size: 1.7rem;
        transition: all 100ms;
        padding: 0.1rem;
        cursor: pointer;
    }
    .ranking-list-item:hover {
        color: white;
        background:rgb(21, 120, 177);
        border-radius: 7px;
    }
    .ranking-list-item:active {
        color: white;
        background:rgb(17, 69, 99);
        border-radius: 7px;
    }
    .input-group-addon {
        box-shadow: inset 1px 1px 1px #d5d5d5;
    }
    .rank-title {
        text-align: center;
        color: #000;
        font-size: 1.8rem;
        font-weight: bold;
    }
    .rank-number {
        text-shadow: 1px 1px 3px #d5d5d5;
    }
    .row-charts {
        width: 100%;
    }
    .pie-charts {
        width: 100%;
    }
    .row-charts {
        margin-top: 2rem;
    }
    .detail-box {
        position: fixed;
        width: 100rem;
        height: 70rem;
        background: #fff;
        border:1px solid #d5d5d5;
        border-radius: 14px;
        left: 50%;
        top: 50%;
        margin-left: -50rem;
        margin-top: -35rem;
        box-shadow: 1px 1px 7px #d2d2d2;
        z-index: 99;
        animation: fadeIn 300ms;
        display: none;
        transition: all 150ms;
    }
    .detail-box-topbar {
        width: 100%;
        height: 6rem;
        border-bottom: 1px solid #d5d5d5;
        border-radius: 7px 0 0;
        display: flex;
        justify-content:center;
        background: #31708f14;
    }
    #detailBoxCloseWrapper {
        position: absolute;
        width: 100%;
        bottom: 0;
        height: 6rem;
        padding: 0.4rem;
    }
    .detail-box-title {
        height: 6rem;
        line-height: 6rem;
        font-size: 2.5rem;
        text-align: center;
        /* text-shadow: 1px 1px 1px #d5d5d5; */
        letter-spacing: 1px;
        color: #000;
        font-family: '宋体';
        font-weight: bold;
        
    }
    #detailBoxClose {
        background: #548ac0;
        height: 5rem;
        border-radius: 7px;
        color: #fff;
        text-align: center;
        line-height: 5rem;
        font-size: 1.5rem;
        letter-spacing: 1px;
        border: 1px solid #fff;
        cursor: pointer;
    }
    #detailBoxClose:active {
        background: #335270;
    }
    .detail-box-table {
        padding: 3rem;
    }
    .form-control {
        box-shadow: 1px 1px 7px #d5d5d5;
        cursor: pointer;
    }
    .blury {
        filter: blur(2px) brightness(0.8);
    }
    .fadeOut {
        animation: fadeout 200ms;
    }
    @keyframes fadeout {
        0% {transform: translateX(0) scale(1); opacity: 1;}
        100% {transform: translateX(350px) scale(0.4); opacity: 0}
    }
    @keyframes fadeIn {
        0% {transform: translateX(350px) scale(0.4);}
        100% {transform: translateX(0) scale(1);}
    }
</style>
<script type="text/javascript">
    $(document).ready(function(){
        var detailSelected = 0;
        var agentData = [{{agents.data|safe}}];
        var detailData = [];
        
        
        $('#detailBoxClose').click(function() {
            $('.detail-box').addClass('fadeOut');
            setTimeout(function() {
                $('.detail-box').removeClass('fadeOut');
                $('.detail-box').hide();
            }, 180)
        });
        //agent
        $('#ranking-list li').click(function(e) {
            if($('.detail-box').is(':hidden')) {
                detailSelected = e.currentTarget.dataset.id;
                $('.detail-box-title').text(agentData[0][detailSelected].name);
                $('.detail-box').show();
                query_detail(e.currentTarget.dataset.comp_to_id, "agent", -1);
            }
        });
        //series
        $('#ranking-list2 li').click(function(e) {
            if($('.detail-box').is(':hidden')) {
                detailSelected = e.currentTarget.dataset.id;
                console.log(e);
                $('.detail-box-title').text(e.currentTarget.dataset.name);
                $('.detail-box').show();
                query_detail(e.currentTarget.dataset.comp_to_id, "series", detailSelected);
            }
        });
        $('#year').val('{{y}}');
        $('#month').val('{{m}}');
        function query_detail(comp_to_id, type, series) {
            
            $('.detail-box').addClass('blury');
            var year = $('#year').val();
            var month = $('#month').val();
            var comp_to_id = comp_to_id;
            var cid = {{cid}};
            var url = `/sales/ajax/query/month/details/?cid=${cid}&comp_to_id=${comp_to_id}&year=${year}&month=${month}&type=${type}`
            if(series != -1) {
                url = `/sales/ajax/query/month/details/?cid=${cid}&comp_to_id=${comp_to_id}&year=${year}&month=${month}&type=${type}&series=${series}`
            }
            table.clear();
            table.destroy();
            $.ajax({
                url: url,
                success: function(res) {
                    detailData = res.value;
                    generateDataTable();
                    table.order([1, 'desc']).draw()  //做默认降序
                    $('.detail-box').removeClass('blury');
                }
            })
        }

        var table = $('#tb').DataTable({
            dom: 'Bfrtip',
            autoWidth: true,
            buttons: [{extend:'excelHtml5',text: '导出到Excel'}],
            language:lng,
            columns: [
                { data: "name"},
                { data: "count"}
        ],
            data: detailData
        });
        function generateDataTable() {
            table = $('#tb').DataTable({
                dom: 'Bfrtip',
                autoWidth: true,
                buttons: [{extend:'excelHtml5',text: '导出到Excel'}],
                language:lng,
                columns: [
                    { data: "name"},
                    { data: "count"}
            ],
                data: detailData
            });
        }

        // table.columns().every( function () {
        //     var that = this;
        //     $('input', this.footer() ).on( 'keyup change clear', function () {
        //         if ( that.search() !== this.value ) {
        //             that.search( this.value ).draw();
        //         }
        //     });
        // });

        var cht_qty=echarts.init(document.getElementById('qty'));
        var qty_option={
            title : {
                text: '{{y}}年{{m}}月销售量曲线图',
                x:'center'
            },
            xAxis: {
                type: 'category',
                data: {{quantitys.category|safe}},
                name: '日期',
                nameLocation: 'end'
            },
            yAxis: {
                type: 'value',
                name: '销量/箱',
                nameLocation: 'end'
            },
            label: {
              show: true,
              position: 'top',
              textColor: '#000',
            },
            tooltip : {
                trigger: 'item',
                formatter: "{{y}}-{{m}}-{b} 销售出库: {c} (箱) "
            },
            series: [{
                data: {{quantitys.data|safe}},
                type: 'line',
                smooth: true
            }]
        };
        cht_qty.setOption(qty_option);
/*
        var cht_prd = echarts.init(document.getElementById('prd'));
        var prd_option = {
            title : {
                text: '销量排名前10产品：',
                x:'left'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} "
            },

            series: [{
                data: {{products.data|safe}},
                selectedMode: 'single',
                type: 'pie',
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                radius: '65%',
                label: {
                    normal: {
                        show: true,

                        textStyle : {
                                    fontWeight : 400 ,
                                    fontSize : 16    //文字的字体大小
                        },
                        formatter:'{b}:{d}%'
                    }
                }
            }]

        };
        cht_prd.setOption(prd_option);
*/
/*
        var cht_agt=echarts.init(document.getElementById('agt'));
        var agt_option={
            title : {
                text: '销量排名前10经销商：',
                x:'left'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} "
            },
            series: [{
                data: {{agents.data|safe}},
                type: 'pie',
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                radius: '65%',
                label: {
                    normal: {
                        show: true,

                        textStyle : {
                                    fontWeight : 400 ,
                                    fontSize : 16    //文字的字体大小
                        },
                        formatter:'{b}:{d}%'
                    }
                }
            }]
        };
        cht_agt.setOption(agt_option);
        */
        var d = [];
        {% for i in products.data %}
            d.push(`{{i.name}}`);
        {% endfor %}
        var col_chart_option = {
            grid: {
                containerLabel: true,
                left:'280px',
            },
            title : {
                text: '销量排名前20产品',
                x:'center'
            },

            xAxis: {
                type:'value',
                name: '销量'
            },
            yAxis: {
                type: 'category',
                data: d,
                axisLabel: {
                    show: true,

                }
            },
            label: {
                show: true,
                position: 'right',
                textColor: '#000'
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : {c} "
            },
            series: [
                {
                    type: 'bar',
                    data: {{ products.data|safe }}
                }
            ]
        };
        var col_crt = echarts.init(document.getElementById('col-chart'));
        col_crt.setOption(col_chart_option);

        $('#month').change(function() {
            var selectedMonth = $(this).children('option:selected').val();
            var year = $('#year').val();
            $.RefreshContent('{{request.path}}?year='+year+'&month='+selectedMonth);

        });
        $('#year').change(function() {
            var selectedYear = $(this).children('option:selected').val();
            var month = $('#month').val();
            $.RefreshContent('{{request.path}}?year='+selectedYear+'&month='+month);

        });
        $('.btn-qry').click(function(){
            var y=$('#year').val();
            var m=$('#month').val();
            $.RefreshContent('{{request.path}}?year='+y+'&month='+m);
        });
        $('.btn-next-month').click(function () {
            var y = $('#year').val();
            var m = zfill(parseInt($('#month').val()) + 1, 2);
            if(m == '13') {
                m = '01';
                y = parseInt(y) + 1;
            }
            $.RefreshContent('{{request.path}}?year='+y+'&month='+m);
        });
        $('.btn-last-month').click(function () {
            var y = $('#year').val();
            var m = zfill(parseInt($('#month').val()) - 1, 2);
            if(m == '00') {
                m = '12';
                y = parseInt(y) - 1;
            }
            $.RefreshContent('{{request.path}}?year='+y+'&month='+m);
        });
        $('#toggle').click(function() {
            if(qty_option.label.show == true){
                $('#toggle').html("<span class='uncheck'>☐</span> 曲线图销量指示");
                qty_option.label.show = false;
                cht_qty.setOption(qty_option);
            }else if(qty_option.label.show == false) {
                $('#toggle').html("<span class='check'>🗹</span> 曲线图销量指示");
                qty_option.label.show = true;
                cht_qty.setOption(qty_option);
            }
        });
        function trend() {
            if({{ prev_total }} && {{ total }}) {
                var pt = {{ prev_total }};
                var t = {{ total }};
                var compare = Math.floor( ((t - pt)/pt)*10000 )/ 100;
                if(compare > 0){
                    $('#trend').html(` 相较上月总量<span class='red'>▲ <b>${compare}</b></span>%`);
                }else if(compare < 0){
                    $('#trend').html(` 相较上月总量<span class='green'>▼ <b>${compare}</b></span>%`);
                }else $('#trend').html(` 没有比较数据 `);
            }
        };
        function zfill(num, n) {
          var len = num.toString().length;
          while(len < n) {
            num = "0" + num;
            len++;
          }
          return num;
        }
        trend();

    });


</script>

<div class="subtitle">
    <ol class="breadcrumb">
        <li>{% trans "图表数据" %}</li>
        <li>{% trans "月销量分析" %} </li>
    </ol>
</div>


<!--startprint-->
<form role="form"  class="form-inline" id="printForm">
    <div class='col-sm-2 input-group pull-left'>
        <span class="input-group-addon"> {% trans "年份" %} </span>
        <select id='year' class='form-control'>
            {% for yr in years %}    
                <option>{{yr}}</option>
            {% endfor %}
        </select>
    </div>
    <div class='col-sm-2 input-group pull-left'>
        <span class="input-group-addon">{% trans "月份" %}</span>
        <select id='month'  class='form-control'>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
        </select>
    </div>

<!--<div class="col-sm-2 panel panel-default " style="background: #f5f5f5;">-->
<!--  <div class="panel-body" style="padding: 9px;">-->
<!--    ABC-->
<!--  </div>-->
<!--</div>-->
<div class="btn-group col-sm-3" role="group" aria-label="">
  <button type="button"  class="btn btn-primary btn-last-month">< 上个月</button>
  <button type="button" class="btn btn-primary btn-next-month" style="margin-left: 0.5rem;">下个月 ></button>
</div>
<div class="col-sm-4 panel panel-default pull-right" style="background: #f5f5f5;box-shadow: inset 1px 1px 1px #d5d5d5;">
  <div class="" style="padding: 9px;display: flex;justify-content: space-between;">
    <div>
        月销售总量: <b style="color: blue;">{{ total }}</b>
    </div>
    <span id="trend"></span>
  </div>
</div>

</form>
<div class="detail-box">
    <div id="detailBoxCloseWrapper">
        <div id="detailBoxClose">关闭</div>
    </div> 
    <div class="detail-box-topbar">
        <div class="detail-box-title"></div>
    </div>
    <div class="detail-box-table">
        <div class="table-responsive">
             <table id='tb' class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
                 <thead>
                     <tr>
                         <th>品名</th>
                         <th>数量</th>
                     </tr>
                 </thead>
                 <tbody></tbody>
             </table>
         </div>
     </div>
</div>
<div class="clearfix"></div>
<div class="charts"> 
    <div style="display:grid;grid-template-columns: 2fr 1fr;grid-auto-flow: row dense;">
        <div>
            <div id='qty' class="panel-like"></div>
            <div class="row-charts">
                <div class='pie-charts'>
                    <div id="col-chart" class="panel-like"></div>
                </div>  
            </div>
            
        </div>
        <div>
            <div id="ranking" class="panel-like">
                <div class="rank-wrapper">
                    <ul id="ranking-list">
                    <p class="rank-title">销量排名前20经销商</p>
                        {% for i in agents.data %}
                            <li class="ranking-list-item" data-type="agent" data-id="{{i.index}}" data-comp_to_id="{{i.company_to_id}}" 
                            title="{{ i.name }}: {{ i.value }}">{{ i.name }}
                                <span class="pull-right rank-number">{{ i.value }}</span>
                            </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
            <div id="ranking2" class="panel-like">
                <div class="rank-wrapper">
                    <ul id="ranking-list2">
                    <p class="rank-title">按系列查看</p>
                        {% for i in series.data %}
                            <li class="ranking-list-item" data-type="series" data-id="{{i.series}}" data-name="{{i.name}}">{{ i.name }}
                                <span class="pull-right rank-number">{{ i.count }}</span>
                            </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>


    </div>




    <!-- <div style="display: flex;">
        <div id='qty' class="panel-like"></div>
        <div id="ranking" class="panel-like">
            <div class="rank-wrapper">
                <ul id="ranking-list">
                <p class="rank-title">销量排名前10的经销商</p>
                    {% for i in agents.data %}
                        <li class="ranking-list-item">{{ i.name }}
                            <span class="pull-right rank-number">{{ i.value }}</span>
                        </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>   -->


    <div style="height: 650px;width: 1px;"></div>

</div>



