var ADVANCE_AND_ADJUSTMENT_DASHBORD_RESPONSE;

$("#getAdvanceAndAdjustmentDashBoard_form  select.year").html(getFinancialYear_yearDropDownUI_optionTags()); // in advanceAmount.js
// $("#getAdvanceAndAdjustmentDashBoard_form  select.year").on('change', function(){
//     let selected_financialYear=$(this).val();
//     let optionTags=getFinancialYear_monthDropDownUI_optionTags(selected_financialYear);
//     $("#getAdvanceAndAdjustmentDashBoard_form  select.month").html(optionTags);
// });

$(".advanceAndAdjustmentsDiv .employeeAdvanceAndAdjustmentsDashBoardTabBtn").on('click', function(){
    let tabContent= $(this).attr("data-id");
    $(".employeeAdvanceAndAdjustmentsDashBoardTabBtn").addClass("active");
    onclickAdvanceAndAdjustmentTabButton_uichanges(tabContent, ".employeeAdvanceAndAdjustmentsDashBoardTabBtn"); // in advanceAmount.js
});
$("html").on('click', '.subTabs_popover.advanceAndAdjustmentsPopoverContent .employeeAdvanceAndAdjustmentsDashBoardTabBtn',function(){
    let tabContent= $(this).attr("data-id");
    $(".employeeAdvanceAndAdjustmentsDashBoardTabBtn").addClass("active");
    onclickAdvanceAndAdjustmentTabButton_uichanges(tabContent, ".employeeAdvanceAndAdjustmentsDashBoardTabBtn"); // in advanceAmount.js
});

$(".sideNavtab#advanceAndAdjustmentsBtn").on('click', function(){
    if(!ADVANCE_AND_ADJUSTMENT_DASHBORD_RESPONSE){         // if already got response avoid re-request 
        // $(".advanceAndAdjustmentsDiv .subTabs button").removeClass("active");
        $(".employeeAdvanceAndAdjustmentsDashBoardTabBtn").addClass("active");
        $(".advanceAndAdjustmentsTabContent  .tabSubContent").addClass("d-none");
        $(".advanceAndAdjustmentsTabContent  .tabSubContent.advanceAndAdjustmentDashBoardTabContent").removeClass("d-none");
        $(`#getAdvanceAndAdjustmentDashBoard_form button.submitBtn`).trigger('click');
    }
});
$("#getAdvanceAndAdjustmentDashBoard_form").submit(function(e){
    e.preventDefault();
    let form=$(this);
    let obj=convertValuesToObject(form.serializeArray());// global functions in tab_Dashboard_finance.js or tab_Dashboard_TL.js 
    form.find("button.submitBtn").html(`<i class="fas fa-spinner fa-spin"></i>`);
        let postContent=JSON.stringify(obj);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        form.find("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
        alertNoInternet_connection();
    }else{
        let promiseObj=postDataHttpRequest("DashBoard/php/advanceAndAdjustments_dashboard/getAdvanceAndAdjustmentDashboardDetails.php", postContent);
        promiseObj.then((result)=>{
            ADVANCE_AND_ADJUSTMENT_DASHBORD_RESPONSE=result;
            if(result.error){
               form.find("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
            }else{
                form.find("button.submitBtn").html(`<i class="fas fa-search"></i>`);
                 constructAdvanceAndAdjustmentValuePieChart(result.responseArray.advanceAndAdjustmentValues[0]);
                 constructTotalPedingAdjustmentCountTableUI(result.responseArray.totalPendingAdjustments);
                 constructTotalYearPendingAdjustmentCountBarChart(result.responseArray.totalYearWisePendingAdjustments, obj)
            }
        }).catch((error)=>{
            form.find("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
            console.log(error);
        });
    }
});
function constructAdvanceAndAdjustmentValuePieChart(advanceAndAdjustmentValuesObj){
    let detailsArray=[];
    let objectkeysArray=Object.keys(advanceAndAdjustmentValuesObj);
    objectkeysArray.forEach(function(key){
        detailsArray.push([key, Number(advanceAndAdjustmentValuesObj[key])]);
    });
    detailsArray.unshift([`Task`,`Values`]);
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(function (){
        let data=google.visualization.arrayToDataTable(detailsArray);
        let options={
                        legend:{position:'none'},
                        colors:['#96a1ff','#c363ff','#7bc67e','#ff7373'], //,'#5664d2'
                        pieSliceBorderColor:'transparent',
                        slices:{
                            1:{offset:0.8},
                            2:{offset:0.6},
                            4:{offset:0.6}
                        },
                         pieHole: 0.4,
                        tooltip:{text:'value'}
        }
        let chart=new google.visualization.PieChart(document.getElementById("advanceAndAdjustmentValueDetailsPieChartDiv"));
        chart.draw(data, options);
    });
    $('.totalAdvanceGivenValue').text(convertToRupeesFromate(Math.floor(advanceAndAdjustmentValuesObj.TotalAdvance))); //convertToRupeesFromate() in mainFinance.js 
    $('.totalPendingAdjustmentValue').text(convertToRupeesFromate(Math.floor(advanceAndAdjustmentValuesObj.TotalPendingAdjustment)));
    $('.totalAdjustmentDoneValue').text(convertToRupeesFromate(Math.floor(advanceAndAdjustmentValuesObj.TotalAdjustments)));
    $('.overAllAdvanceAndAdjustmentValue').text(convertToRupeesFromate(Math.floor(advanceAndAdjustmentValuesObj.Overall)));
}
function constructTotalPedingAdjustmentCountTableUI(jsonDataArray){
    let tableBody='';
    jsonDataArray.forEach(function(currentLoopObj){
        tableBody+=`<tr>
                        <td>${currentLoopObj.MonthName}</td>
                        <td>${currentLoopObj.PendingAdjustment}</td>
                    </tr>`;
    });
    $("#totalPendingAdjustmentCountTable tbody").html(tableBody);
}
function constructTotalYearPendingAdjustmentCountBarChart(jsonDataArray, postContentObj){
    let obj={
        NeedToAdjust:0,
        MismatchedAdjustment:0,
        SuccesfullyAdusted:0,
        FinancialYear:postContentObj.financialYear
    };
    jsonDataArray.map(function(innerLoopObj, index){
        obj[innerLoopObj.ADJUSTMENT_STATUS]=Number(innerLoopObj.COUNT);
    });
    let BarChartDetails=[
        ['Financial Year', 'Mismatched', 'Need To Adjust' , 'Adjustment Done'],
        [obj.FinancialYear,obj.MismatchedAdjustment,obj.NeedToAdjust, obj.SuccesfullyAdusted],
        ];
    google.charts.load('current', {'packages':['corechart','bar']});
    google.charts.setOnLoadCallback(function(){
        let data= google.visualization.arrayToDataTable(BarChartDetails);
        let options={
            bars:'horizontal',
            colors:["#ff7373","#ffd65f","#7bc67e"]
        };

        let chart= new google.charts.Bar(document.getElementById('yearAdjustmentCountDetailsBarCharDiv'));
        chart.draw(data, google.charts.Bar.convertOptions(options));
    });
}

// ------------------------------------------------------------------------------ initially financial year / month  values update---------------------

// $("#getAdvanceAndAdjustmentDashBoard_form select.year").val(getfinancialYearValue()).trigger("change");// in advanceAmount.js
$("#getAdvanceAndAdjustmentDashBoard_form select.year").val(getfinancialYearValue());// in advanceAmount.js
// $(`#getAdvanceAndAdjustmentDashBoard_form select.month option[value^='${getMonthName(new Date().getMonth())}']`).attr("selected","selected"); // [ ^ ] is search for like month, getMonthName() in advanceAmount.js
//[value^='${currentMonthName}']


// ;;