$(function(e){
    $('#flob').select2({
        allowClear:true
    });

    $('#fcabang').select2({
        allowClear:true
    });

    $('#fbulan').select2({
        allowClear:true
    });

    /*---- Pencapaian Sales Table ----*/
    $('#sales-per-kn-table').DataTable({
            lengthMenu: [7, 14, 21, 28], // Set the available page lengths
            pageLength: 7,
            language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
            lengthMenu: '_MENU_',
            }
        });

    $('#sales-per-cabang-table').DataTable({
            lengthMenu: [5, 10, 15, 20], // Set the available page lengths
            pageLength: 5,
            language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
            lengthMenu: '_MENU_',
            }
        });

    /*----- Perform Sales By Distributor -----*/
    // var dataSalesByDistributor= {
    //     title: {
    //     text: 'Perform Sales by Distributor'
    //     },
    //     tooltip: {
    //     trigger: 'item'
    //     },
    //     // legend: {
    //     // orient: 'vertical',
    //     // left: 'left'
    //     // },
    //     series: [
    //     {
    //         name: 'Perform Sales by Distributor',
    //         type: 'pie',
    //         radius: '60%',
    //         data: [
    //         { value: 264814945326.53, name: 'KND' },
    //         { value: 264418598191.11, name: 'KMMD B' },
    //         { value: 136718359089.62, name: 'BEVEREGE' },
    //         { value: 172947268926, name: 'KMMD C' }
    //         ],
    //         label: {
    //             show: true,
    //             formatter: '{b} : {d}%'
    //         },
    //         percentPrecision: 2 ,
    //         emphasis: {
    //         itemStyle: {
    //             shadowBlur: 10,
    //             shadowOffsetX: 0,
    //             shadowColor: 'rgba(0, 0, 0, 0.5)'
    //         }
    //         }
    //     }
    //     ],
    //     color: ['#a4dfdf', '#9ad0f5', '#ffcf9f', '#ffb0c1']
    // };
    var dataSalesByDistributor = [
        { category: 'KND', percentage_ach: 20, percentage_gwt: 80 },
        { category: 'BEVERAGE', percentage_ach: 40, percentage_gwt: 60 },
        { category: 'KMMD B', percentage_ach: 60, percentage_gwt: 40 },
        { category: 'KMMD C', percentage_ach: 80, percentage_gwt: 20 }
      ];

    var optionSalesByDistributor = {
        title: {
          text: 'Perform Sales by Distributor',
          margin:20
        },
        series: [{
          type: 'pie',
          radius: '40%',
          label: {
            formatter: '{b}: {d}%'
          },
          data: dataSalesByDistributor.map(item => ({
            name: `${item.category} - ACH`,
            value: item.percentage_ach
          })),
          emphasis: {
            focus: 'data',
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          }
        },
        {
          type: 'pie',
          radius: ['50%', '70%'],
          label: {
            formatter: '{b}: {d}%'
          },
          data: dataSalesByDistributor.map(item => ({
            name: `${item.category} - GWT`,
            value: item.percentage_gwt
          })),
          emphasis: {
            focus: 'data',
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          }
        }]
      };
    var psDistributor = document.getElementById('pd-distributor');
    var psDistributorChart = echarts.init(psDistributor);


    var obPsDistributor = new IntersectionObserver(function(entries) {
        // Check if the element is intersecting
            entries.forEach(entry => {
                if(entry.isIntersecting) {
                    psDistributorChart.clear();
                    psDistributorChart.setOption(optionSalesByDistributor);
                    // Optional: Disconnect the observer if you don't need it anymore
                    //obsEC.disconnect();
                }
            });
        }, { threshold: [0.5] });

    obPsDistributor.observe(psDistributor);

    var dataAchCabang = [19325, 23438, 31000, 121594, 134141];
    var dataGwtCabang = [18325, 22438, 30000, 111594, 124141];

    // Calculate the percentage values
    var totalAchCabang = dataAchCabang.reduce((sum, value) => sum + value, 0);
    var percentagesAchCabang = dataAchCabang.map(value => (value / totalAchCabang) * 100);
    var totalGwtCabang = dataGwtCabang.reduce((sum, value) => sum + value, 0);
    var percentagesGwtCabang = dataGwtCabang.map(value => (value / totalGwtCabang) * 100);


    var dataSalesByCabang = {
        title: {
          text: 'Perform Sales by Cabang'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: ['Kediri', 'Jember', 'Malang', 'Surabaya 2', 'Surabaya 1'],
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (params) {
                var dataIndex = params[0].dataIndex;
                return `Category: ${params[0].name}<br/>ACH %: ${dataAchCabang[dataIndex]} (${percentagesAchCabang[dataIndex].toFixed(2)}%)<br/>GWT %: ${dataGwtCabang[dataIndex]} (${percentagesGwtCabang[dataIndex].toFixed(2)}%)`;
            }
          },
        series: [
          {
            name: 'ACH%',
            type: 'bar',
            data: dataAchCabang
          },
          {
            name: 'GWT%',
            type: 'bar',
            data: dataGwtCabang
          }
        ]
      };
    var psCabang = document.getElementById('pd-cabang');
    var psCabangChart = echarts.init(psCabang);


    var obPsCabangChart = new IntersectionObserver(function(entries) {
        // Check if the element is intersecting
            entries.forEach(entry => {
                if(entry.isIntersecting) {
                    psCabangChart.clear();
                    psCabangChart.setOption(dataSalesByCabang);
                    // Optional: Disconnect the observer if you don't need it anymore
                    //obsEC.disconnect();
                }
            });
        }, { threshold: [0.5] });

    obPsCabangChart.observe(psCabang);

    /*----- Sales Perform by Cabang -----*/
    $('#pareto-table').DataTable({
            lengthMenu: [5, 10, 15, 20], // Set the available page lengths
            pageLength: 5,
            language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
            lengthMenu: '_MENU_',
            }
    });

    $('#perform-sales-cabang-pareto-modal').on('shown.bs.modal', function () {
        const colorsServiceLvl = ['#5470C6', '#91CC75', '#EE6666'];
        var optionServiceLvl = {
        color: colorsServiceLvl,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            type: 'cross'
            }
        },
        grid: {
            right: '20%'
        },
        toolbox: {
            feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['IVC', 'PO', 'SLA']
        },
        xAxis: [
            {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['KN1','KN2','KN3','KN4','KN5','KN6','KN7',]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: 'IVC',
                position: 'right',
                alignTicks: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                    color: colorsServiceLvl[0]
                    }
                },
                axisLabel: {
                    formatter: '{value}',
                }
            },
            {
            type: 'value',
            name: 'PO',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsServiceLvl[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'SLA',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsServiceLvl[2]
                }
            },
            axisLabel: {
                formatter: '{value} %'
            }
            }
        ],
        series: [
            {
            name: 'IVC',
            type: 'bar',
            data: [
                34826294441,156844951446,35998886609,26990095092,20662091099,31613718281,46633241430
            ]
            },
            {
            name: 'PO',
            type: 'bar',
            yAxisIndex: 1,
            data: [
                36326335924,175191270753,37142572810,30908916737,23673710381,33469977164,58680076594
            ]
            },
            {
            name: 'SLA',
            type: 'line',
            yAxisIndex: 2,
            data: [96,90,97,87,87,94,79]
            }
        ]};

        var serviceLvl= document.getElementById('service-lvl');
        var serviceLvlChart = echarts.init(serviceLvl);
        serviceLvlChart.setOption(optionServiceLvl);

        const colorsRetur = ['#5470C6', '#91CC75', '#EE6666'];
        var optionRetur = {
        color: colorsRetur,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            type: 'cross'
            }
        },
        grid: {
            right: '20%'
        },
        toolbox: {
            feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['GROSS', 'RETURN', 'RATIO']
        },
        xAxis: [
            {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['KN1','KN2','KN3','KN4','KN5','KN6','KN7',]
            }
        ],
        yAxis: [
            {
            type: 'value',
            name: 'GROSS',
            position: 'right',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[0]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'RETURN',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'RATIO',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[2]
                }
            },
            axisLabel: {
                formatter: '{value} %'
            }
            }
        ],
        series: [
            {
            name: 'GROSS',
            type: 'bar',
            data: [
                910454268205,132051654489,71008492993,110854828988,119651412377,81737125351,93051478900
            ]
            },
            {
            name: 'RETURN',
            type: 'bar',
            yAxisIndex: 1,
            data: [
                18694388212,3655534472,2765006488,4111286223,2494669143,4660710879,2753578603
            ]
            },
            {
            name: 'RATIO',
            type: 'line',
            yAxisIndex: 2,
            data: [2.1,2.8,3.9,3.7,2.1,5.7,3.0,2.6]
            }
        ]
        };

        var retur= document.getElementById('retur');
        var returChart = echarts.init(retur);
        returChart.setOption(optionRetur);
    });

    $('#perform-sales-cabang-service-lvl-modal').on('shown.bs.modal', function () {
        const colorsServiceLvl = ['#5470C6', '#91CC75', '#EE6666'];
        var optionServiceLvl = {
        color: colorsServiceLvl,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            type: 'cross'
            }
        },
        grid: {
            right: '20%'
        },
        toolbox: {
            feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['IVC', 'PO', 'SLA']
        },
        xAxis: [
            {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['KN1','KN2','KN3','KN4','KN5','KN6','KN7',]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: 'IVC',
                position: 'right',
                alignTicks: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                    color: colorsServiceLvl[0]
                    }
                },
                axisLabel: {
                    formatter: '{value}',
                }
            },
            {
            type: 'value',
            name: 'PO',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsServiceLvl[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'SLA',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsServiceLvl[2]
                }
            },
            axisLabel: {
                formatter: '{value} %'
            }
            }
        ],
        series: [
            {
            name: 'IVC',
            type: 'bar',
            data: [
                34826294441,156844951446,35998886609,26990095092,20662091099,31613718281,46633241430
            ]
            },
            {
            name: 'PO',
            type: 'bar',
            yAxisIndex: 1,
            data: [
                36326335924,175191270753,37142572810,30908916737,23673710381,33469977164,58680076594
            ]
            },
            {
            name: 'SLA',
            type: 'line',
            yAxisIndex: 2,
            data: [96,90,97,87,87,94,79]
            }
        ]
        };

        var serviceLvl= document.getElementById('service-lvl-btn');
        var serviceLvlChart = echarts.init(serviceLvl);
        serviceLvlChart.setOption(optionServiceLvl);
    });

    $('#perform-sales-cabang-retur-modal').on('shown.bs.modal', function () {
        const colorsRetur = ['#5470C6', '#91CC75', '#EE6666'];
        var optionRetur = {
        color: colorsRetur,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            type: 'cross'
            }
        },
        grid: {
            right: '20%'
        },
        toolbox: {
            feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['GROSS', 'RETURN', 'RATIO']
        },
        xAxis: [
            {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['KN1','KN2','KN3','KN4','KN5','KN6','KN7',]
            }
        ],
        yAxis: [
            {
            type: 'value',
            name: 'GROSS',
            position: 'right',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[0]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'RETURN',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'RATIO',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsRetur[2]
                }
            },
            axisLabel: {
                formatter: '{value} %'
            }
            }
        ],
        series: [
            {
            name: 'GROSS',
            type: 'bar',
            data: [
                910454268205,132051654489,71008492993,110854828988,119651412377,81737125351,93051478900
            ]
            },
            {
            name: 'RETURN',
            type: 'bar',
            yAxisIndex: 1,
            data: [
                18694388212,3655534472,2765006488,4111286223,2494669143,4660710879,2753578603
            ]
            },
            {
            name: 'RATIO',
            type: 'line',
            yAxisIndex: 2,
            data: [2.1,2.8,3.9,3.7,2.1,5.7,3.0,2.6]
            }
        ]
        };

        var retur= document.getElementById('retur-btn');
        var returChart = echarts.init(retur);
        returChart.setOption(optionRetur);
    });

    $('#effectivecall-ea-modal').on('shown.bs.modal', function () {
        var optionEA = {
        title: {
            text: 'Effective Account'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [6623,6454,6810,5641,7456,7421,7629,7399,7713,7914,8170,1683]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [10083,10633,10764,9520,11326,11018,11587,11340,12356,12424,12667,2578]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [7816,7114,7848,6038,7820,6941,7774,8012,8174,8452,8837,1559]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [11651,10971,11319,9598,11576,10365,10610,10684,11194,11636,11573,1740]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [7729,7178,7710,6135,8393,7476,7990,7789,8500,8345,8413,1575]
            }
        ]};

        var ecEA = document.getElementById('ec-ea');
        var ecEAChart = echarts.init(ecEA);
        ecEAChart.setOption(optionEA);
    });

    $('#effectivecall-ipt-modal').on('shown.bs.modal', function () {
        var optionIPT = {
        title: {
            text: 'Item Per Transaction'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [2.3,2.3,2.3,2.2,2.2,2.3,2.2,2.3,2.1,2.1,2.2,2.0]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [2.4,2.6,2.6,2.6,2.6,2.5,2.5,2.5,2.5,2.5,2.5,2.3]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [2.4,2.5,2.5,2.5,2.6,2.5,2.5,2.4,2.4,2.4,2.5,2.3]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [2.7,2.7,2.8,2.7,2.9,2.9,2.8,2.8,2.7,2.8,2.8,2.8]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [2.5,2.7,2.6,2.6,2.7,2.6,2.6,2.6,2.5,2.5,2.5,2.4]
            }
        ]};

        var ecIPT = document.getElementById('ec-ipt');
        var ecIPTChart = echarts.init(ecIPT);
        ecIPTChart.setOption(optionIPT);
    });

    $('#mea-modal').on('shown.bs.modal', function () {
        var optionIPT = {
        title: {
            text: 'Item Per Customer'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang'],
            left: 'right'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [2.7,2.7,2.7,2.6,2.7,2.6,2.6,2.7,2.5,2.5,2.6,2.0]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [2.8,2.9,2.9,2.8,3.0,2.8,2.9,2.9,2.8,2.9,2.9,2.3]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [2.6,2.7,2.7,2.7,2.8,2.8,2.7,2.7,2.6,2.6,2.7,2.3]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [3.1,3.1,3.2,2.9,3.3,3.3,3.2,3.2,3.1,3.1,3.2,2.8]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [2.9,2.9,3.0,2.8,3.1,2.9,2.9,3.0,2.9,2.9,2.8,2.4]
            }
        ]};

        var meaIPT = document.getElementById('mea-ipt');
        var meaIPTChart = echarts.init(meaIPT);
        meaIPTChart.setOption(optionIPT);
    });

    $('#perform-data-jabatan-modal').on('shown.bs.modal', function () {
        var cabang = ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang'];
        var jabatan = ["AR","BR","MAE","NUTRITIONIST","PM","SPG","AGENT 002","AGENT MIMOO","FPE KN3","MD MIDDLE UP","SPG EVENT","MD PRENALOVA","NHC","SPG PGH","FPE KN36","APE"];

        var slcabPCab = $('#slcab-pcab').select2({
            minimumResultsForSearch: '',
            // width: '100%'
        });

        var slcabPCabJab = $('#slcab-pcabjab').select2({
            minimumResultsForSearch: '',
            // width: '100%'
        });

        var sljabPCabJab = $('#sljab-pcabjab').select2({
            minimumResultsForSearch: '',
            // width: '100%'
        });

        slcabPCab.empty();
        cabang.forEach(function(item) {
            slcabPCab.append(new Option("Semua","semua"));
            var option = new Option(item, item);
            slcabPCab.append(option);
        });

        slcabPCab.on("change",function(){
            slcabPCabJab.val(slcabPCab.val()).trigger("change");
        });

        slcabPCabJab.empty();
        cabang.forEach(function(item) {
            slcabPCabJab.append(new Option("Semua","semua"));
            var option = new Option(item, item);
            slcabPCabJab.append(option);
        });

        sljabPCabJab.empty();
        jabatan.forEach(function(item) {
            sljabPCabJab.append(new Option("Semua","semua"));
            var option = new Option(item, item);
            sljabPCabJab.append(option);
        });

        var ncCabangOption = {
            title: {
                text: 'NC Per Cabang'
            },
            legend: {
            orient: 'horizontal',
            left: 'right'
            },
            grid: {
                top: '6',
                right: '0',
                bottom: '17',
                left: '25',
            },
            xAxis: {
                data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'],
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            tooltip: {
                show: true,
                showContent: true,
                alwaysShowContent: false,
                triggerOn: 'mousemove',
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: false,
                    }
                }
            },
            yAxis: {
                splitLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            series: [{
                name: 'Data Entry',
                type: 'bar',
                data: [13363,17117,15856,11284,8619,11065,10314,10258,12942,10978,15225,12814]
            }, {
                name: 'NCLCO',
                type: 'bar',
                data: [6814,7164,7372,4138,2733,3906,2931,3806,4062,3249,3971,3510]
            }],
            color: ['#b7dd88', '#9ad0f5', '#ffb0c1', ]
        };

        var ncCabang = document.getElementById('nc-cabang');
        var ncCabangChart = echarts.init(ncCabang);
        ncCabangChart.setOption(ncCabangOption);

        var ncCabJabOption = {
            title: {
                text: 'NC Per Cabang & Jabatan'
            },
            legend: {
            orient: 'horizontal',
            left: 'right'
            },
            grid: {
                top: '6',
                right: '0',
                bottom: '17',
                left: '25',
            },
            xAxis: {
                data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'],
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            tooltip: {
                show: true,
                showContent: true,
                alwaysShowContent: false,
                triggerOn: 'mousemove',
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: false,
                    }
                }
            },
            yAxis: {
                splitLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            series: [{
                name: 'Data Entry',
                type: 'bar',
                data: [208,621,374,317,289,253,176,388,526,541,571,559]
            }, {
                name: 'NCLCO',
                type: 'bar',
                data: [3,5,16,8,9,14,6,4,4,5,7,2]
            }],
            color: ['#b7dd88', '#9ad0f5', '#ffb0c1', ]
        };

        var ncCabJab = document.getElementById('nc-cabjab');
        var ncCabJabChart = echarts.init(ncCabJab);
        ncCabJabChart.setOption(ncCabJabOption);

    });


    /*----- Effective Call -----*/
    var dataECDay = [{
        name: 'actual',
        type: 'bar',
        data: [1426, 172, 298, 861]},
        {
        name: 'target',
        type: 'bar',
        data: [1260, 168, 280, 782]
    }];

    var dataECMonth = [{
        name: 'actual',
        type: 'bar',
        data: [1426, 172, 298, 861]
    }, {
        name: 'target',
        type: 'bar',
        data: [1260, 168, 280, 782]
    }];

    var ecDay = document.getElementById('effective-call-day');
    var ecDayOption = {
        legend: {
        orient: 'horizontal',
        left: 'center'
        },
        grid: {
            top: '6',
            right: '0',
            bottom: '17',
            left: '25',
        },
        xAxis: {
            data: ['KMMD B', 'KMMD C', 'BEVERAGE', 'KND'],
            axisLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLabel: {
                fontSize: 10,
                color: '#9ba6b5'
            }
        },
        tooltip: {
            show: true,
            showContent: true,
            alwaysShowContent: false,
            triggerOn: 'mousemove',
            trigger: 'axis',
            axisPointer: {
                label: {
                    show: false,
                }
            }
        },
        yAxis: {
            splitLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLabel: {
                fontSize: 10,
                color: '#9ba6b5'
            }
        },
        series: dataECDay,
        color: ['#b7dd88', '#9ad0f5', '#ffb0c1', ]
    };
    var ecMonthOption = {
        legend: {
        orient: 'horizontal',
        left: 'center'
        },
        grid: {
            top: '6',
            right: '0',
            bottom: '17',
            left: '25',
        },
        xAxis: {
            data: ['KMMD B', 'KMMD C', 'BEVERAGE', 'KND'],
            axisLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLabel: {
                fontSize: 10,
                color: '#9ba6b5'
            }
        },
        tooltip: {
            show: true,
            showContent: true,
            alwaysShowContent: false,
            triggerOn: 'mousemove',
            trigger: 'axis',
            axisPointer: {
                label: {
                    show: false,
                }
            }
        },
        yAxis: {
            splitLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(119, 119, 142, 0.2)'
                }
            },
            axisLabel: {
                fontSize: 10,
                color: '#9ba6b5'
            }
        },
        series: dataECMonth,
        color: ['#b7dd88', '#9ad0f5', '#ffb0c1', ]
    };


    var ecChart = echarts.init(ecDay);

    $("#btnradio1").on("click",function(){
        ecChart.setOption(ecDayOption);
    });

    $("#btnradio2").on("click",function(){
        ecChart.setOption(ecMonthOption);
    });

    /*----- Effective Call -----*/

    // window.addEventListener('resize',function(){
    //     psCabangChart.resize();
    // });

    window.addEventListener('resize',function(){
        ecChart.resize();
    });

    psCabangChart.on('click', function (params) {
        console.log(params.name);
        //alert('Clicked on ' + params.data.name);
        var psCabangModal = new bootstrap.Modal(document.getElementById('perform-sales-cabang-pareto-modal'), {
            keyboard: false
        });
        $("#psc-modal-title").text(params.name);
        psCabangModal.toggle();
    });

    ecChart.on('click', function (params) {
        //console.log(params.name);
        //alert('Clicked on ' + params.data.name);
        var ecModal = new bootstrap.Modal(document.getElementById('effectivecall-modal'), {
            keyboard: false
        });
        $("#ec-modal-title").text(params.name);
        ecModal.toggle();
    });

    var optionEA = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [6623,6454,6810,5641,7456,7421,7629,7399,7713,7914,8170,1683]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [10083,10633,10764,9520,11326,11018,11587,11340,12356,12424,12667,2578]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [7816,7114,7848,6038,7820,6941,7774,8012,8174,8452,8837,1559]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [11651,10971,11319,9598,11576,10365,10610,10684,11194,11636,11573,1740]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [7729,7178,7710,6135,8393,7476,7990,7789,8500,8345,8413,1575]
            }
    ]};
    var ecEA = document.getElementById('ec-ea');
    var ecEAChart = echarts.init(ecEA);


    var optionIPT = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [2.3,2.3,2.3,2.2,2.2,2.3,2.2,2.3,2.1,2.1,2.2,2.0]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [2.4,2.6,2.6,2.6,2.6,2.5,2.5,2.5,2.5,2.5,2.5,2.3]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [2.4,2.5,2.5,2.5,2.6,2.5,2.5,2.4,2.4,2.4,2.5,2.3]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [2.7,2.7,2.8,2.7,2.9,2.9,2.8,2.8,2.7,2.8,2.8,2.8]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [2.5,2.7,2.6,2.6,2.7,2.6,2.6,2.6,2.5,2.5,2.5,2.4]
            }
    ]};
    var ecIPT = document.getElementById('ec-ipt');
    var ecIPTChart = echarts.init(ecIPT);

    function renderECChart() {
        ecChart.clear();
        ecChart.setOption(ecDayOption);
        ecEAChart.clear();
        ecEAChart.setOption(optionEA);
        ecIPTChart.clear();
        ecIPTChart.setOption(optionIPT);
    }

    var ecContainer = document.getElementById('effective-call-day');
    var obsEC = new IntersectionObserver(function(entries) {
    // Check if the element is intersecting
        entries.forEach(entry => {
            if(entry.isIntersecting) {
                renderECChart();
                //console.log('obs');
                // Optional: Disconnect the observer if you don't need it anymore
                //obsEC.disconnect();
            }
        });
    }, { threshold: [0.5] });

    obsEC.observe(ecContainer);

    /*---- Perform Data by Jabatan -----*/
    var jabatan = ["AR","BR","MAE","NUTRITIONIST","PM","SPG","AGENT 002","AGENT MIMOO","FPE KN3","MD MIDDLE UP","SPG EVENT","MD PRENALOVA","NHC","SPG PGH","FPE KN36","APE"];
    var jabatanSelect = $('#select-jabatan').select2({
        minimumResultsForSearch: '',
        // width: '100%'
    });

    jabatan.forEach(function(item) {
        var option = new Option(item, item);
        jabatanSelect.append(option);
    });

    //jabatanSelect.on("change",function(){
        var pdJabatanOption = {
            legend: {
            orient: 'horizontal',
            left: 'center'
            },
            grid: {
                top: '6',
                right: '0',
                bottom: '17',
                left: '25',
            },
            xAxis: {
                data: ['KN1', 'KN2', 'KN3', 'KN4', 'KN5', 'KN6', 'KN7'],
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            tooltip: {
                show: true,
                showContent: true,
                alwaysShowContent: false,
                triggerOn: 'mousemove',
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: false,
                    }
                }
            },
            yAxis: {
                splitLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(119, 119, 142, 0.2)'
                    }
                },
                axisLabel: {
                    fontSize: 10,
                    color: '#9ba6b5'
                }
            },
            series: [{
                name: 'Data Entry',
                type: 'bar',
                data: getDataEntry()
            }, {
                name: 'NCLCO',
                type: 'bar',
                data: getNCLCO()
            }],
            color: ['#b7dd88', '#9ad0f5', '#ffb0c1', ]
        };

        var pdJabatan = document.getElementById('pd-kn');
        var pdJabatanChart = echarts.init(pdJabatan);

    //});

    function getDataEntry(){
        if(jabatanSelect.val() == 'AR'){
            return [1490,4608,2747,1140,1691,1634,1652,1254,1477,1234,1387,1417];
        }else if(jabatanSelect.val() == 'BR'){
            return [3354,6401,5602,3611,3424,4788,4675,5212,6551,6255,6349,7235];
        }else if(jabatanSelect.val() == 'MAE'){
            return [3172,4890,5241,3876,4037,4573,6255,4013,6292,4603,7768,4210];
        }else if(jabatanSelect.val() == 'NUTRITIONIST'){
            return [0,148,84,0,20,33,85,105,148,113,292,390];
        }else if(jabatanSelect.val() == 'PM'){
            return [0,0,0,0,0,0,0,0,0,299,0,0];
        }else if(jabatanSelect.val() == 'SPG'){
            return [36482,38189,33602,26318,15602,20954,17580,19428,17609,15411,17233,17511];
        }else{
            //return [0,0,0,0,0,0,0,0,0,0,0,0];
            return [1490,4608,2747,1140,1691,1634,1652,1254,1477,1234,1387,1417];
        }
    }

    function getNCLCO(){
        if(jabatanSelect.val() == 'AR'){
            return [18,41,88,23,51,67,78,45,47,30,40,46];
        }else if(jabatanSelect.val() == 'BR'){
            return [40,77,100,91,97,127,121,175,194,167,152,147];
        }else if(jabatanSelect.val() == 'MAE'){
            return [52,107,169,124,112,142,196,120,188,113,176,146];
        }else if(jabatanSelect.val() == 'NUTRITIONIST'){
            return [0,7,1,0,0,1,1,6,2,2,4,15];
        }else if(jabatanSelect.val() == 'PM'){
            return [0,0,0,0,0,0,0,0,0,16,0,0];
        }else if(jabatanSelect.val() == 'SPG'){
            return [27427,29386,28089,18208,11886,16951,14102,15594,13601,11492,12460,11827];
        }else{
            //return [0,0,0,0,0,0,0,0,0,0,0,0];
            return [18,41,88,23,51,67,78,45,47,30,40,46];
        }
    }

    var observerJab = new IntersectionObserver(function(entries) {
    // Check if the element is intersecting
    if(entries[0].isIntersecting) {
        pdJabatanChart.clear();
        pdJabatanChart.setOption(pdJabatanOption);
        // Optional: Disconnect the observer if you don't need it anymore
        //observerJab.disconnect();
    }
    }, { threshold: [0.5] });

    observerJab.observe(document.getElementById('pd-kn'));

    /*---- Activity -----*/
    const colorsActivity = ['#5470C6', '#91CC75', '#EE6666'];
    var optionActivity = {
        color: colorsActivity,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            type: 'cross'
            }
        },
        grid: {
            right: '20%'
        },
        toolbox: {
            feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['Target', 'Actual', 'ACH']
        },
        xAxis: [
            {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['KN1','KN2','KN3','KN4','KN5','KN6','KN7',]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: 'Target',
                position: 'right',
                alignTicks: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                    color: colorsActivity[0]
                    }
                },
                axisLabel: {
                    formatter: '{value}',
                }
            },
            {
            type: 'value',
            name: 'Actual',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsActivity[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
            },
            {
            type: 'value',
            name: 'ACH',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                color: colorsActivity[2]
                }
            },
            axisLabel: {
                formatter: '{value} %'
            }
            }
        ],
        series: [
            {
            name: 'Target',
            type: 'bar',
            data: [
                256,300000851,501725,114,800216,250520,1290
            ]
            },
            {
            name: 'Actual',
            type: 'bar',
            yAxisIndex: 1,
            data: [
                256,300000851,501725,114,800216,250520,1290
            ]
            },
            {
            name: 'ACH',
            type: 'line',
            yAxisIndex: 2,
            data: [100,100,100,100,100,100,100]
            }
        ]};

        var activity = document.getElementById('activity');
        var activityChart = echarts.init(activity);

        var observerAct = new IntersectionObserver(function(entries) {
        // Check if the element is intersecting
        if(entries[0].isIntersecting) {
            activityChart.clear();
            activityChart.setOption(optionActivity);
            // Optional: Disconnect the observer if you don't need it anymore
            //observerAct.disconnect();
        }
        }, { threshold: [0.5] });

        observerAct.observe(document.getElementById('activity-data'));

        $('#activity-medis-table').DataTable({
            lengthMenu: [5, 10, 15, 20], // Set the available page lengths
            pageLength: 5,
            language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
            lengthMenu: '_MENU_',
            }
        });

        $('#activity-nonmedis-table').DataTable({
            lengthMenu: [5, 10, 15, 20], // Set the available page lengths
            pageLength: 5,
            language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
            lengthMenu: '_MENU_',
            }
        });

    /*---- Map Perform Sales -----*/
    // var vmap = $(".mapcontainer").mapael({
    //     map: {
    //         name: "indonesia"
    //         // Enable zoom on the map
    //         , zoom: {
    //             enabled: false,
    //             maxLevel: 25
    //         }
    //         // Set default plots and areas style
    //         , defaultPlot: {
    //             attrs: {
    //                 fill: "#ffb0c1"
    //                 , opacity: 0.6
    //             }
    //             , attrsHover: {
    //                 fill: "#ffb0c1",
    //                 opacity: 1,
    //                 "stroke-width": 0,
    //                 r:10
    //             }
    //             , text: {
    //                 attrs: {
    //                     fill: "#ffb0c1"
    //                     , opacity: 0.8
    //                 }
    //                 , attrsHover: {
    //                     fill: "#ffb0c1"
    //                     , opacity: 1
    //                 }
    //             }
    //         }
    //         , defaultArea: {
    //             attrs: {
    //                 fill: "#8fbd56"
    //                 , stroke: "#fff"
    //             }
    //             , attrsHover: {
    //                 fill: "#ffe6aa",
    //                 opacity: 0.8
    //             }
    //             , text: {
    //                 attrs: {
    //                     fill: "#7673e6"
    //                 }
    //                 , attrsHover: {
    //                     fill: "#000"
    //                 }
    //             },
    //             eventHandlers: {
    //                 click: function (e, id) {
    //                     if(id === 'ID-JI'){
    //                         vmap.trigger('zoom', {
    //                             area: id,
    //                             areaMargin: 10
    //                         });
    //                     }
    //                 }
    //             }
    //         }
    //     },

    //     // Customize some areas of the map
    //     areas: {
    //         "ID-JI": {
    //             attrs: {
    //                 fill: "#8fbd56"
    //                 , stroke: "#fff"
    //             }
    //             , attrsHover: {
    //                 fill: "#ffe6aa",
    //                 opacity: 0.8
    //             },
    //             text: {
    //                 content: "Jawa Timur",
    //                 attrs: {
    //                     fill: "#000000",
    //                     "font-size": 8
    //                 }
    //             },
    //             tooltip: {content: "Kalbe Reg IV Jawa Timur"}
    //         }
    //     },

    //     // Add some plots on the map
    //     plots: {
    //         // Plot positioned by x and y instead of latitude, longitude
    //         'surabaya1': {
    //             x: 295,
    //             y: 256,
    //             attrs: {
    //                 fill: "#a4dfdf",
    //                 opacity: 0.6
    //             }
    //             , attrsHover: {
    //                 fill: "#a4dfdf",
    //                 opacity: 1,
    //                 "stroke-width": 0,
    //                 r:10
    //             },
    //             tooltip: {content: "<span style=\"font-weight:bold;\">Sales Surabaya 1 : </span>  264.814.945.327 <br> "+$('#content-surabaya1').html()},
    //             text: {
    //                 content: "Surabaya 1"
    //                 , position: "bottom"
    //                 , attrs: {"font-size": 5, fill: "#a4dfdf", opacity: 0.8}
    //                 , attrsHover: {fill: "#a4dfdf", opacity: 1}
    //             },
    //         },
    //         'surabaya2': {
    //             x: 300,
    //             y: 258,
    //             attrs: {
    //                 fill: "#9ad0f5",
    //                 opacity: 0.6,
    //                 "stroke-width": 0,
    //                 r:10
    //             }
    //             , attrsHover: {
    //                 fill: "#9ad0f5",
    //                 opacity: 1
    //             },
    //             tooltip: {content: "<span style=\"font-weight:bold;\">Sales Surabaya 2 :</span>  264.418.598.191 <br> "+$('#content-surabaya2').html()},
    //             text: {
    //                 content: "Surabaya 2"
    //                 , position: "bottom"
    //                 , attrs: {"font-size": 5, fill: "#9ad0f5", opacity: 0.8}
    //                 , attrsHover: {fill: "#9ad0f5", opacity: 1}
    //             },
    //         },
    //         'jember': {
    //             x: 320,
    //             y: 266,
    //             attrs: {
    //                 fill: "#ffcf9f",
    //                 opacity: 0.6,
    //                 "stroke-width": 0,
    //                 r:9
    //             }
    //             , attrsHover: {
    //                 fill: "#ffcf9f",
    //                 opacity: 1
    //             },
    //             tooltip: {content: "<span style=\"font-weight:bold;\">Sales Jember :</span>  136.718.359.090 <br> "+$('#content-jember').html()},
    //             text: {
    //                 content: "Jember"
    //                 , position: "bottom"
    //                 , attrs: {"font-size": 5, fill: "#ffcf9f", opacity: 0.8}
    //                 , attrsHover: {fill: "#ffcf9f", opacity: 1}
    //             },
    //         },
    //         'kediri': {
    //             x: 285,
    //             y: 263,
    //             attrs: {
    //                 fill: "#ffb0c1",
    //                 opacity: 0.6,
    //                 "stroke-width": 0,
    //                 r:10
    //             }
    //             , attrsHover: {
    //                 fill: "#ffb0c1",
    //                 opacity: 1
    //             },
    //             tooltip: {content: "<span style=\"font-weight:bold;\">Sales Kediri :</span>  172.947.268.926 <br> "+$('#content-kediri').html()},
    //             text: {
    //                 content: "Kediri"
    //                 , position: "bottom"
    //                 , attrs: {"font-size": 5, fill: "#ffb0c1", opacity: 0.8}
    //                 , attrsHover: {fill: "#ffb0c1", opacity: 1}
    //             },
    //         },
    //         'malang': {
    //             x: 300,
    //             y: 266,
    //             attrs: {
    //                 fill: "#ffe6aa",
    //                 opacity: 0.6,
    //                 "stroke-width": 0,
    //                 r:10
    //             }
    //             , attrsHover: {
    //                 fill: "#ffe6aa",
    //                 opacity: 1
    //             },
    //             tooltip: {content: "<span style=\"font-weight:bold;\">Sales Malang :</span>  225.860.245.924 <br> "+$('#content-malang').html()},
    //             text: {
    //                 content: "Malang"
    //                 , position: "bottom"
    //                 , attrs: {"font-size": 5, fill: "#ffe6aa", opacity: 0.8}
    //                 , attrsHover: {fill: "#ffe6aa", opacity: 1}
    //             },
    //         },
    //     }
    // });

    // Set the zoom level and center the map on the specific area
    // var specificAreaZoomLevel = 25; // Adjust this value as needed
    // $(".mapcontainer").trigger('zoom', {
    //     level: specificAreaZoomLevel,
    //     area:'ID-JI'
    // });

    /* ---- Loyal Customer ----*/
    var optionLC = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Surabaya 1', 'Surabaya 2', 'Jember', 'Kediri', 'Malang'],
            left: 'right'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Surabaya 1',
            type: 'line',
            stack: 'Total',
            data: [2.7,2.7,2.7,2.6,2.7,2.6,2.6,2.7,2.5,2.5,2.6,2.0]
            },
            {
            name: 'Surabaya 2',
            type: 'line',
            stack: 'Total',
            data: [2.8,2.9,2.9,2.8,3.0,2.8,2.9,2.9,2.8,2.9,2.9,2.3]
            },
            {
            name: 'Jember',
            type: 'line',
            stack: 'Total',
            data: [2.6,2.7,2.7,2.7,2.8,2.8,2.7,2.7,2.6,2.6,2.7,2.3]
            },
            {
            name: 'Kediri',
            type: 'line',
            stack: 'Total',
            data: [3.1,3.1,3.2,2.9,3.3,3.3,3.2,3.2,3.1,3.1,3.2,2.8]
            },
            {
            name: 'Malang',
            type: 'line',
            stack: 'Total',
            data: [2.9,2.9,3.0,2.8,3.1,2.9,2.9,3.0,2.9,2.9,2.8,2.4]
            }
        ]};

        var loyalCustomer = document.getElementById('loyal-customer');
        var loyalCustomerChart = echarts.init(loyalCustomer);


        var observerLC = new IntersectionObserver(function(entries) {
            // Check if the element is intersecting
            if(entries[0].isIntersecting) {
                loyalCustomerChart.clear();
                loyalCustomerChart.setOption(optionLC);
                // Optional: Disconnect the observer if you don't need it anymore
                //observerAct.disconnect();
            }
         }, { threshold: [0.5] });

         observerLC.observe(document.getElementById('loyal-customer'));

        var observerSales = new IntersectionObserver(function(entries) {
            // Check if the element is intersecting
            if(entries[0].isIntersecting) {
                setTimeout(() => {
                    var dataSales = [
                        [new Date('2023-12-01').getTime(),1503310315],
                        [new Date('2023-12-02').getTime(),2179688435],
                        [new Date('2023-12-03').getTime(),1349118],
                        [new Date('2023-12-04').getTime(),3813624382],
                        [new Date('2023-12-05').getTime(),2446390578],
                        [new Date('2023-12-06').getTime(),3604818354],
                        [new Date('2023-12-07').getTime(),2809353329],
                        [new Date('2023-12-08').getTime(),3319300336],
                        [new Date('2023-12-09').getTime(),1559114766],
                        [new Date('2023-12-11').getTime(),4115053363],
                        [new Date('2023-12-12').getTime(),5795539507],
                        [new Date('2023-12-13').getTime(),2686267975],
                        [new Date('2023-12-14').getTime(),3487890335],
                        [new Date('2023-12-15').getTime(),4744727620],
                        [new Date('2023-12-16').getTime(),3300439519],
                        [new Date('2023-12-17').getTime(),294237744],
                        [new Date('2023-12-18').getTime(),2906417248],
                        [new Date('2023-12-19').getTime(),2504983949],
                        [new Date('2023-12-20').getTime(),2890489034],
                        [new Date('2023-12-21').getTime(),4157229237],
                        [new Date('2023-12-22').getTime(),4666936588],
                        [new Date('2023-12-23').getTime(),4694070914],
                        [new Date('2023-12-25').getTime(),452892602],
                        [new Date('2023-12-26').getTime(),4712975405],
                        [new Date('2023-12-27').getTime(),5689671528],
                        [new Date('2023-12-28').getTime(),4899498956],
                        [new Date('2023-12-29').getTime(),10104401594],
                        [new Date('2023-12-30').getTime(),5133002885],
                        [new Date('2023-12-31').getTime(),-1749910102]
                    ];
                    var options = {
                      series: [
                        {
                          name: 'Sales',
                          data: dataSales
                        },

                      ],
                      chart: {
                        id: 'chartD',
                        type: 'area',
                        height: 345,
                        zoom: {
                          autoScaleYaxis: false
                        }
                      },

                      colors: [myVarVal],
                      dataLabels: {
                        enabled: false
                      },
                      markers: {
                        size: 0,
                        style: 'hollow',
                      },
                      grid: {
                        borderColor: '#f7f9fa',
                      },
                      xaxis: {
                        type: 'datetime',
                        min: new Date('01 Dec 2023').getTime(),
                        axisBorder: {
                          show: true,
                          color: 'rgba(119, 119, 142, 0.05)',
                          offsetX: 0,
                          offsetY: 0,
                        },
                        axisTicks: {
                          show: true,
                          borderType: 'solid',
                          color: 'rgba(119, 119, 142, 0.05)',
                          width: 6,
                          offsetX: 0,
                          offsetY: 0
                        },
                        labels: {
                          show: true,
                          rotate: -90,
                          style: {
                            fontSize: '11px',
                            fontFamily: 'Helvetica, Arial, sans-serif',
                            fontWeight: 400,
                            cssClass: 'apexcharts-xaxis-label',
                          },
                        },
                        tooltip: {
                          enabled: false
                        }
                      },
                      yaxis: {
                        title: {
                          text: 'Growth',
                          style: {
                            color: '#adb5be',
                            fontSize: '14px',
                            fontFamily: 'poppins, sans-serif',
                            fontWeight: 600,
                            cssClass: 'apexcharts-yaxis-label',
                          },
                        },
                        labels: {
                          formatter: function (y) {
                            var formatter = new Intl.NumberFormat('id-ID');
                            return formatter.format(y.toFixed(0)).toLocaleString();
                          }
                        }
                      },
                      tooltip: {
                        x: {
                          format: 'dd MMM yyyy'
                        }
                      },
                      stroke: {
                        show: true,
                        curve: 'smooth',
                        lineCap: 'butt',
                        colors: undefined,
                        width: 1,
                        dashArray: 0,
                      },
                      fill: {
                        type: 'gradient',
                        gradient: {
                          shadeIntensity: 1,
                          opacityFrom: 0.75,
                          opacityTo: 0.5,
                          stops: [0, 200]
                        }
                      },

                      legend: {
                        position: "top",
                        show: true
                      }
                    };
                    document.getElementById('chartD').innerHTML = '';
                    var chart = new ApexCharts(document.querySelector("#chartD"), options);
                    chart.render();
                  }, 100);
                // Optional: Disconnect the observer if you don't need it anymore
                //observerAct.disconnect();
            }
         }, { threshold: [0.5] });

         observerSales.observe(document.getElementById('chartD'));
});
