window.addEventListener('load', () => {
    getLatestOrderCount();
    getTotalSales();
    getMonthlyOrders();
});

$('#total_sales_date').daterangepicker({
    locale: { cancelLabel: 'Sil', customRangeLabel: "Özel seçim" },
    buttonClasses: ' btn',
    applyClass: 'btn-primary',
    cancelClass: 'btn-secondary',
    ranges: {
        'Bugün': [moment(), moment()],
        'Dün': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Son 7 Gün': [moment().subtract(6, 'days'), moment()],
        'Son 30 Gün': [moment().subtract(29, 'days'), moment()],
        'Bu Ay': [moment().startOf('month'), moment().endOf('month')],
        'Geçen Ay': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    }
}, function (start, end, label) {
    $('#total_sales_date .js-daterangepicker-predefined-preview').html(start.format('MMM D') + ' - ' + end.format('MMM D, YYYY'));
    document.getElementById('total_sales_date_start').value = start.format('YYYY-MM-DD');
    document.getElementById('total_sales_date_end').value = end.format('YYYY-MM-DD');
    getTotalSales();
});

$('#date').on('cancel.daterangepicker', function (ev, picker) {
    $('#total_sales_date .js-daterangepicker-predefined-preview').html(start.format('MMM D') + ' - ' + end.format('MMM D, YYYY'));
    document.getElementById('total_sales_date_start').value = "";
    document.getElementById('total_sales_date_end').value = "";
    getTotalSales();
});

function getLatestOrderCount() {
    var formData = new FormData();
    request('/admin/common/api/order/latest-orders-count', formData, function (data) {
        try {
            data = JSON.parse(data);
            if (!(data instanceof Object)) {
                console.log('bad data');
            } else {
                if (data['status']) {
                    var line_chart_options = {
                        xAxis: {
                            type: 'category',
                            data: data['result']['labels']
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                data: data['result']['data'],
                                type: 'line',
                                symbol: 'none',
                                hoverAnimation: true,
                                areaStyle: {
                                    color: {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [{
                                            offset: 0,
                                            color: 'rgba(0, 77, 157, 0.2)'
                                        }, {
                                            offset: 1,
                                            color: 'rgba(0, 77, 157, 0)'
                                        }]
                                    }
                                }
                            }
                        ],
                        animationDuration: 2000
                    };

                    var lineChart = echarts.init(document.getElementById('daily-order-counts'));
                    line_chart_options && lineChart.setOption(line_chart_options);
                }
            }
        } catch (e) {
            console.log(e);
        }
    });
}

function getTotalSales() {
    var date_start = document.getElementById('total_sales_date_start').value;
    var date_end = document.getElementById('total_sales_date_end').value;
    var formData = new FormData();
    formData.append("date_start", date_start);
    formData.append("date_end", date_end);
    request('/admin/common/api/order/total-sales', formData, function (data) {
        try {
            data = JSON.parse(data);
            if (!(data instanceof Object)) {
                console.log('bad data');
            } else {
                if (data['status']) {
                    document.getElementById('total-sale-price').innerText = data['result']['grand_total'];
                    var line_chart_options = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross',
                                label: {
                                    backgroundColor: '#6a7985'
                                }
                            }
                        },
                        legend: {
                            data: ['Satış', 'İptal/İade']
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: data['result']['sale']['labels']
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: 'İptal/İade',
                                type: 'line',
                                stack: 'Total',
                                color: '#f44336',
                                areaStyle: {},
                                emphasis: {
                                    focus: 'series'
                                },
                                data: data['result']['cancelled']['data']
                            },
                            {
                                name: 'Satış',
                                type: 'line',
                                stack: 'Total',
                                color: '#8bc34a',
                                areaStyle: {},
                                emphasis: {
                                    focus: 'series'
                                },
                                data: data['result']['sale']['data']
                            }
                        ],
                        animationDuration: 3000
                    };

                    var lineChart = echarts.init(document.getElementById('sales-chart'));
                    line_chart_options && lineChart.setOption(line_chart_options);
                }
            }
        } catch (e) {
            console.log(e);
        }
    });
}

function getMonthlyOrders() {
    var formData = new FormData();
    request('/admin/common/api/order/orders-per-month', formData, function (data) {
        try {
            data = JSON.parse(data);
            if (!(data instanceof Object)) {
                console.log('bad data');
            } else {
                if (data['status']) {
                    var line_chart_options = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross',
                                label: {
                                    backgroundColor: '#6a7985'
                                }
                            }
                        },
                        legend: {
                            data: ['Satışlar', 'İptal/İade']
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: data['result']['sale']['labels']
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: 'İptal/İade',
                                type: 'bar',
                                stack: 'Total',
                                color: '#f44336',
                                areaStyle: {},
                                emphasis: {
                                    focus: 'series'
                                },
                                data: data['result']['cancelled']['data']
                            },
                            {
                                name: 'Satışlar',
                                type: 'bar',
                                stack: 'Total',
                                color: '#8bc34a',
                                areaStyle: {},
                                emphasis: {
                                    focus: 'series'
                                },
                                data: data['result']['sale']['data']
                            }
                        ]
                    };

                    var lineChart = echarts.init(document.getElementById('monthy-orders-chart'));
                    line_chart_options && lineChart.setOption(line_chart_options);
                }
            }
        } catch (e) {
            console.log(e);
        }
    });
}