
$(document).ready(function () {
    LoadBranch();
    LoadCompany_Name();
    LoadVisit_Type();
})

function LoadBranch() {

    var subdepartment = {

        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            $('#SelBranch').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;

                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var Branch;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Branch = Branch + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#SelBranch').append(default_opt + Branch);
                    $('#SelBranch').attr('disabled', true);


                    //if ($('#hiddenRole_id').val() != 2) {
                    //    $('#SelBranch').val($('#HospitalBranchID').val());
                    //    $('#SelBranch').attr('disabled', true);
                    //}
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

function LoadCompany_Name() {

    var subdepartment = {

        Dml_Indicator: "TCN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Tally/Tally_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            $('#ddCompanyName').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;

                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var Company_Name;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Company_Name = Company_Name + '<option value="' + emp.company_name + '" data-id="' + emp.tallycompany_id + '" data-value="' + emp.branchid + '">' + emp.company_name + '</option>';
                    });
                    $('#ddCompanyName').append(default_opt + Company_Name);

                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

$('#ddCompanyName').change(function () {
    var branchid = $('#ddCompanyName option:selected').attr("data-value");

    if (parseInt($('#ddCompanyName').val()) == 0) {

        $('#SelBranch').val('0');
    }
    else {
        $('#SelBranch').val(branchid);
    }
})

function LoadVisit_Type() {

    var subdepartment = {

        Dml_Indicator: "HVT"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Tally/Tally_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            $('#ddVisit').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;

                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var Visit;
                    var default_opt = '<option value="0">All Visit</option>';
                    $.each(data1.Table, function (i, emp) {
                        Visit = Visit + '<option value="' + emp.visit_typeid + '">' + emp.visit_type_name + '</option>';
                    });
                    $('#ddVisit').append(default_opt + Visit);

                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

$('#Btn_View').click(function () {

    ShowTally();
});

function ShowTally() {
    debugger;
    $('#Btn_View').prop('disabled', true);
    if ($.trim($('#ddCompanyName').val()) == 0) {
        $('#PddCompanyName').show();
        $('#PddCompanyName').fadeOut(8000);
        $('#PddCompanyName').html('Select Company Name');
        $('#ddCompanyName').focus();
        return false;
    }

    if ($.trim($('#SelBranch').val()) == 0) {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Select Branch Name');
        $('#SelBranch').focus();
        return false;
    }

    if ($.trim($('#ddType').val()) == 0) {
        $('#PddType').show();
        $('#PddType').fadeOut(8000);
        $('#PddType').html('Select Type');
        $('#ddType').focus();
        return false;
    }

    if ($.trim($('#Tally_fromdate').val()) == "") {
        $('#PTally_fromdate').show();
        $('#PTally_fromdate').fadeOut(8000);
        $('#PTally_fromdate').html('Select From');
        $('#Tally_fromdate').focus();
        return false;
    }

    var from_date = '', to_date = '', dml = '';
    if ($('#Tally_fromdate').val() != '') {

        from_date = $('#Tally_fromdate').val();
        from_date = from_date.split('/');
        from_date = from_date[2] + "-" + from_date[1] + "-" + from_date[0];

    }

    if ($('#Tally_todate').val() != '') {

        to_date = $('#Tally_todate').val();
        to_date = to_date.split('/');
        to_date = to_date[2] + "-" + to_date[1] + "-" + to_date[0];
    }

    if (parseInt($('#ddType').val()) == 1) {
        dml = 'TSL';
    }
    else if (parseInt($('#ddType').val()) == 2) {
        dml = 'TCOS';
    }
    else if (parseInt($('#ddType').val()) == 3) {
        dml = 'TPAS';
    }
    $('#shade_slot').show();

    var RefundTbldata = {

        //Dml_Indicator: 'TSL',
        Dml_Indicator: dml,
        branch_id: $('#SelBranch').val(),
        from_date: from_date,
        to_date: to_date,
        type: $('#SelBranch').val(),
        visit_type: $('#ddVisit').val(),
        company_name: $('#ddCompanyName option:selected').data('id'),
        company_id: $('#ddCompanyName option:selected').attr("data-id"),
        voucher_typeid: $('#ddType').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Tally/Tally_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundTbldata),
        success: function (data) {
            $('#Tbl_tally_body').empty();
            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject(data)) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var row_data = "", Voucherno = '', count = 1;

                    $('#Tbl_tally').dataTable().fnClearTable();
                    $('#Tbl_tally').dataTable().fnDraw();
                    $('#Tbl_tally').dataTable().fnDestroy();

                    $.each(data1.Table, function (i, emp) {
                        debugger;
                        if (parseInt($('#ddType').val()) == 1) {

                            if (emp.Debit > 0) {
                                Voucherno = count++;
                            }

                        } else {

                            if (parseInt(emp.Credit) > 0) {
                                Voucherno = count++;
                            }

                        }

                        row_data = row_data + "<tr><input type='hidden' id='visit_type_" + i + "' value='" + emp.visit_type + "' /><input type='hidden' id='is_posting_" + i + "' value='" + emp.is_posting + "' /><td id='sno_" + i + "'>" + (i + 1) + "</td><td id='Voucherno_" + i + "'>" + Voucherno + "</td><td id='BillDate_" + i + "'>" + emp.BillDate + "</td><td id='Particulars_" + i + "'>" + emp.Type + "</td><td id='Debit_" + i + "'>" + emp.Debit + "</td><td id='Credit_" + i + "'>" + emp.Credit + "</td><td id='VoucherType_" + i + "'>" + emp.VoucherType + "</td><td id='Narration_" + i + "'>" + emp.Narration + "</td><td id='RefNo_" + i + "'>" + emp.Ref_Code + "</td><input type='hidden' id='ParentLedger_" + i + "' value='" + emp.Parent + "' /></tr>";
                        //<td id='Primary_CostCentre_" + i + "'>" + emp.PrimaryCostCentre + "</td><td id='SPCostCentre_" + i + "'>" + emp.SecondaryCostCentre + "</td>

                    });
                    $('#Tbl_tally_body').append(row_data);
                    //datatable('Tbl_tally', 'Bill_Refund', 'Legal');
                    $('#Tbl_tally').DataTable();
                    $('#shade_slot').hide();
                    $('#Btn_View').prop('disabled', false);
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}

$('#Btn_Posting').click(function () {

    debugger;
    $('#Btn_Posting').prop('disabled', true);
    var Dtable = $('#Tbl_tally').DataTable();

    // If DataTable is already initialized, destroy it
    $('#Tbl_tally').dataTable().fnDestroy();

    // Initialize DataTable with desired settings
    $('#Tbl_tally').DataTable({
        "paging": false,
        "info": false
    });

    $('#shade_slot').show();

    var TallyArray = [];



    var table = $('#Tbl_tally').DataTable();
    var TableCount = table.rows().count();

    var data = table.rows().data().toArray();


    //var TableCount = $('#Tbl_tally >tbody >tr').length;



    if (TableCount > 0) {

        $(data).each(function (rowIndex, rowData) {
            //    debugger;

            var Tallylist = {};

            Tallylist.SNo = rowData[0];
            Tallylist.VoucherNo = rowData[1];

            var Bill_date = rowData[2];
            var a = Bill_date.split('/');
            ADT = a[2] + a[1] + a[0];
            var tally_date = a[2] + '-' + a[1] + '-' + a[0];

            Tallylist.Date = ADT;
            Tallylist.Particulars = rowData[3];
            Tallylist.Debit = rowData[4];
            Tallylist.Credit = rowData[5];
            Tallylist.VoucherType = rowData[6];
            Tallylist.Narration = rowData[7];
            Tallylist.RefNo = rowData[8];
            //Tallylist.PrimaryCostCentre = rowData[9];
            //Tallylist.SubPrimaryCostCentre = rowData[10];
            Tallylist.Company_name = $('#ddCompanyName').val();

            Tallylist.voucher_typeid = $('#ddType').val();
            Tallylist.visit_typeid = $('#visit_type_' + rowIndex).val();
            Tallylist.company_id = $('#ddCompanyName option:selected').attr("data-id");
            Tallylist.tally_date = tally_date;
            Tallylist.hospital_id = $('#HospitalId').val();
            Tallylist.branch_id = $('#SelBranch').val();
            Tallylist.created_by = $('#hiddenUser_id').val();
            Tallylist.is_posting = $('#is_posting_' + rowIndex).val();
            Tallylist.Parent = $('#ParentLedger_' + rowIndex).val();
            TallyArray.push(Tallylist);
        });
    }
    else {
        return false;
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Tally/TallyXML',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(TallyArray),
        success: function (data) {
            debugger;
            $('#shade_slot').hide();
            $('#Btn_Posting').prop('disabled', false);
            if (data.Error_Message == "") {
                toastr.success('Tally Posting Successfully');

            }
            else if (data.Error_Message == "Already Exists") {
                toastr.warning('Already Exists');
            }
            else {
                toastr.warning('Something went wrong.Tally Not Posting');
            }
            $('#Tbl_tally_body').empty();
            $('#Tbl_tally').dataTable().fnClearTable();

        },
        error: function (data) {

        }
    });
})