<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">


<style>
    table {
        border-collapse: collapse;
    }

    thead>tr>td {
        font-weight: bold;
    }

    tbody>tr>td {
        font-weight: bold;
    }

    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
        opacity: 1;
    }

    /* Center the loader  */
    #loader {
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 1;
        width: 150px;
        height: 150px;
        margin: -75px 0 0 -75px;
        border: 16px solid #f3f3f3;
        border-radius: 50%;
        border-top: 16px solid #34B4DB;
        width: 120px;
        height: 120px;
        -webkit-animation: spin 2s linear infinite;
        animation: spin 2s linear infinite;
    }

    @-webkit-keyframes spin {
        0% {
            -webkit-transform: rotate(0deg);
        }

        100% {
            -webkit-transform: rotate(360deg);
        }
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* Add animation to "page content" */

    .animate-bottom {
        position: relative;
        -webkit-animation-name: animatebottom;
        -webkit-animation-duration: 1s;
        animation-name: animatebottom;
        animation-duration: 1s
    }

    @-webkit-keyframes animatebottom {
        from {
            bottom: -100px;
            opacity: 0
        }

        to {
            bottom: 0px;
            opacity: 1
        }
    }

    @keyframes animatebottom {
        from {
            bottom: -100px;
            opacity: 0
        }

        to {
            bottom: 0;
            opacity: 1
        }
    }

    #printing {

        text-align: center;
    }
</style>

<a id="dlink" style="display:none;"></a>

<button type="button" id="btnBack" class="btn brn-default btn-sm" style="vertical-align: middle; cursor:pointer"
    onclick="location.href='../dhis-web-reports-app/index.html#/generate-report'">
    <span class="glyphicon glyphicon-chevron-left" style="font-size: 15px;"></span>&nbsp; Goto Report Selection Page
</button>

<button type="button" class="btn btn-primary btn-sm" style="vertical-align: middle; cursor:pointer"
    onclick="printContent('printing')"><span class="glyphicon glyphicon-print" style="font-size: 15px;"></span> &nbsp;
    Print
</button>

<button type="button" class="btn btn-success btn-sm" style="vertical-align: middle; cursor:pointer" id="btnExport"
    onclick="tableToExcel('dataTable', 'Mental Health Programme-Duration of Stay', 'Mental Health Programme-Duration of Stay.xls')"><span
        class="glyphicon glyphicon-download-alt" style="font-size: 15px;"></span>Download As Excel</button>


<div id="loader"></div>
<div id="printing" class="animate-bottom">
    <div id='state'>
        <table border="1" id="dataTable" class="table  table-hover text-center" cellspacing="6" cellpadding="4"
            style="border-collapse: collapse; visibility:hidden">
            <thead id="tableHead">
                <tr style="font-weight:800; text-align:center;">
                    <td colspan="28" style="border:1px solid black;background:#ADD8E6;">Mental Health Programme-Duration
                        of Stay</td>
                </tr>
                <tr style="font-weight:800; text-align:center;">
                    <td id="facility" colspan="28" style="border:1px solid black;background:#ADD8E6;"></td>
                </tr>
                <tr style="font-weight:800; text-align:center;">
                    <td rowspan="3" style="border:1px solid black;background:#ADD8E6;">Reporting Units</td>
                    <td colspan="24" style="border:1px solid black;background:#ADD8E6;">Duration of Stay</td>
                    <td colspan="3" style="border:1px solid black;background:#ADD8E6;">Services availed during stay</td>
                </tr>
                <tr style="font-weight:800; text-align:center;">
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">Up to 6 months</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">6 to 12 months</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">1 to 2 years</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">2 to 5 years</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">5 to 10 years</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">10 to 20 years</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">Above 20 years</td>
                    <td style="border:1px solid black;background:#ADD8E6;" colspan="3">Total</td>
                    <td style="border:1px solid black;background:#ADD8E6;" rowspan="2">Cases availed services at day care centre
                    </td>
                    <td style="border:1px solid black;background:#ADD8E6;" rowspan="2">Cases availed services at residential CC
                        centre</td>
                    <td style="border:1px solid black;background:#ADD8E6;" rowspan="2">Cases availed services at at long term CC
                        centre</td>
                </tr>
                <tr style="font-weight:800; text-align:center;">
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Male</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Female</td>
                    <td style="border:1px solid black;background:#ADD8E6;">Child</td>
                </tr>
            </thead>
            <tbody id="tableBody"></tbody>
        </table>
    </div>
</div>
<script type="text/javascript">

    document.getElementsByClassName("hideInPrint")["0"].style.display = "none"
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    var selectedOrgUnit = dhis2.report.organisationUnit;
    var orgUnit = dhis2.report.organisationUnitChildren;
    var organisationUnitChildren = orgUnit.sort((a, b) => a.name.localeCompare(b.name));
    var level = dhis2.report.organisationUnitHierarchy.length;

    var orgUnitData = [];
    var printTotalValue = [];
    var totalCells = 27; //Number of Cells
    
    for (var j = 6; j >= level; j--) {
        for (var i = 0; i < totalCells; i++) {
            printTotalValue[j + "totalValue" + i] = "";
        }
    }


    var startMonth = location.href.split("&sd=")["1"].slice(0, 10);;
    var endMonth = location.href.split("&ed=")["1"].slice(0, 10);
    var monthArr = [startMonth, endMonth]
    if (startMonth.split("-").join("") > endMonth.split("-").join("")) {
        alert("Please select  dates correctly");
    } else {
        document.getElementById("facility").innerHTML = selectedOrgUnit.name + " (" + months[startMonth.split("-")["1"] - 1] + " " + startMonth.split("-")["0"] + " to " + months[endMonth.split("-")["1"] - 1] + " " + endMonth.split("-")["0"] + ")";

        document.getElementById("dataTable").style.visibility = "hidden";
        document.getElementById("tableBody").innerHTML = "";
        $('#loader').show();
        setTimeout(function () {
            getData(monthArr);
        }, 1000);
    }


    function getData(smToem) {

        var includedOrgUnitGroups = [];
        var dataElementIds = ["N6CJcOyuxAy", "QbASRWUEl6u", "maHAFWjjPc0", "gnJPJVN7Pg0",
            "fq4iAtxLYxv", "QWQdlCKAjTC", "FuolxTeqvy5", "totalDurationOfStay", "nT5DpQZddyO", "Z5YGli00IWD",
            "mhK7Mzra0XI"];
        var GenderAndChild = ["fuHpuDFQete", "eX5Q0ax217M","HVM7JYYdMDa"];

        var getBetweenDates = function (startDate, endDate) {
            var arr = [], lastDay, start, end;
            var startYear = startDate.split("-");
            var endYear = endDate.split("-");

            for (var i = parseInt(startYear["0"]); i <= parseInt(endYear["0"]); i++) {

                startMonth = (i > parseInt(startYear["0"])) ? 1 : parseInt(startYear["1"]);
                endMonth = (i == endYear["0"]) ? endYear["1"] : 12;

                for (var j = startMonth; j <= endMonth; j++) {
                    let value = j < 10 ? i + "0" + j : i + "" + j;
                    arr.push(value);
                }
            }

            return arr;
        }

        //getting between dates
        var smToEm = getBetweenDates(monthArr["0"], monthArr["1"]);


        $.when(
            $.get("../api/27/organisationUnitGroups/S0CHG7msf7i.json?fields=id,name,organisationUnits&paging=false"),
            $.get("../api/27/organisationUnitGroups/k5pG961XOGC.json?fields=id,name,organisationUnits&paging=false"),
            $.get("../api/27/organisationUnitGroups/CXswpFTMKVB.json?fields=id,name,organisationUnits&paging=false"),
            $.get("../api/27/organisationUnitGroups/La50Y17pBGN.json?fields=id,name,organisationUnits&paging=false")

        ).done(function (state, circle, group, dmhu) {
            var rows = [];
            rows = [].concat(state[0].organisationUnits).concat(circle[0].organisationUnits).concat(group[0].organisationUnits).concat(dmhu[0].organisationUnits)
            var dimensionDE = rows.map(row => row.id).join(";");
          
            
            $.ajax({
                type: "GET",
                async: false,
                url:  "../api/26/analytics.json?dimension=dx:N6CJcOyuxAy;QbASRWUEl6u;maHAFWjjPc0;gnJPJVN7Pg0;fq4iAtxLYxv;QWQdlCKAjTC;FuolxTeqvy5&dimension=I3X3hss5geT:fuHpuDFQete;eX5Q0ax217M;HVM7JYYdMDa&dimension=ou:fU0PPhAypN8;OU_GROUP-La50Y17pBGN&filter=pe:" + smToEm.join(";") + "&displayProperty=NAME&paging=false",
                data: JSON,
                success: function (data, status) {
                    data.rows.forEach(data => {
                        if (!orgUnitData[data["2"]]) {
                            orgUnitData[data["2"]] = []
                            orgUnitData[data["2"]][data["0"]] = []
                            orgUnitData[data["2"]][data["0"]][data["1"]] = data["3"];
                        } else {
                                if(!orgUnitData[data["2"]][data["0"]]) {
                                    orgUnitData[data["2"]][data["0"]] = []
                                }
                                orgUnitData[data["2"]][data["0"]][data["1"]]  = data["3"];                            
                        }
                    })
                }
            });
                       
          
            $.ajax({
                type: "GET",
                async: false,
                url: "../api/26/analytics.json?dimension=dx:nT5DpQZddyO;Z5YGli00IWD;mhK7Mzra0XI&dimension=ou:fU0PPhAypN8;OU_GROUP-La50Y17pBGN&filter=pe:" + smToEm.join(";") + "&displayProperty=NAME&paging=false",
                data: JSON,
                success: function (data, status) {
                    data.rows.forEach(data => {
                        if (!orgUnitData[data["1"]]) {
                            orgUnitData[data["1"]] = []
                            orgUnitData[data["1"]][data["0"]] = data["2"];
                        } else {
                            orgUnitData[data["1"]][data["0"]] = data["2"];
                        }
                    })
                }
            });


            rows.forEach(data => {
                includedOrgUnitGroups[data.id] = true;
            });
            getData();
        });

        function getData() {
            var url = '../api/organisationUnits/' + selectedOrgUnit.id + '.json?paging=false&fields=id,name,level,dataSets[id]';
            $.ajax({
                type: "GET",
                async: false,
                url: '../api/organisationUnitLevels.json',
                data: JSON,
                success: function (data, status) {

                    for (let i = 0; i < data.organisationUnitLevels.length; i++) {
                        url += ',children[id,name,level,dataSets[id]';
                    }
                    url += ']';
                }
            });


            $.ajax({
                type: "GET",
                async: false,
                url: url,
                data: JSON,
                success: function (data, status) {
                    var levelColor = [];
                    levelColor["2"] = "#89CFF0"; //State level
                    levelColor["3"] = "#A0D6B4"; //Cricle level
                    levelColor["4"] = "#B2BEB5"; //District level
                    levelColor["6"] = "#FFCC99"; //Block level
                    treeDown(data, levelColor);

                    document.getElementById("dataTable").style.visibility = "visible";
                    $('#loader').hide();
                    document.getElementById("printing").style.display = "block";
                }
            });
            function treeDown(arr, color) {
                var key = arr;
                var obj = {}

                if (key.children.length && key.level != 7) {
                    key.children.sort((a, b) => a.name.localeCompare(b.name))
                    for (let i = 0; i < key.children.length; i++) {
                        treeDown(key.children[i], color);
                    }
                }


                if (includedOrgUnitGroups[key.id]) {
                    obj["id"] = key.id;
                    obj["name"] = key.name;
                    obj["level"] = key.level;
                    if (key.children.length) obj["color"] = color[key.level];
                    runAPI(obj.id, obj.name, obj.color, obj.level);
                }
            }


            function runAPI(orgUnitId, orgUnit, levelColor, orgUnitLevel) {
                var printValue = [];
                var addRow = "";
                for (var i = 0; i < totalCells; i++) {
                    printValue["value" + i] = "";
                }


                if (orgUnitData[orgUnitId]) {
                    let count = 0;
                    dataElementIds.forEach((de, index) => {
                        
                        if(index == 7) {
                            GenderAndChild.forEach((de, index)=> {
                            if(index == 0)printValue["value" + count]  = Number(printValue["value0"])  +  Number(printValue["value3"])  +  Number(printValue["value6"])  +  Number(printValue["value9"])  +  Number(printValue["value12"])  +  Number(printValue["value15"])  +  Number(printValue["value18"]);
                            else if(index == 1)printValue["value" + count]  = Number(printValue["value1"])  +  Number(printValue["value4"])  +  Number(printValue["value7"])  +  Number(printValue["value10"])  +  Number(printValue["value13"])  +  Number(printValue["value16"])  +  Number(printValue["value19"]);
                            else if(index == 2)printValue["value" + count]  = Number(printValue["value2"])  +  Number(printValue["value5"])  +  Number(printValue["value8"])  +  Number(printValue["value11"])  +  Number(printValue["value14"])  +  Number(printValue["value17"])  +  Number(printValue["value20"]);
                            if (orgUnitLevel >= 6) printTotalValue["4totalValue" + count] = Number(printTotalValue["4totalValue" + count]) + Number(printValue["value" + count]);
                            count += 1
                            })
                        }
                        else if(index<7) {
                            GenderAndChild.forEach(id => {
                                printValue["value" + count] = orgUnitData[orgUnitId][de][id] ? Number(orgUnitData[orgUnitId][de][id])  : "";
                                if (orgUnitLevel >= 6) printTotalValue["4totalValue" + count] = Number(printTotalValue["4totalValue" + count]) + Number(printValue["value" + count]);
                                count += 1
                            })                           
                        } 
                        else {
                            printValue["value" + count] = orgUnitData[orgUnitId][de] ? Number(orgUnitData[orgUnitId][de]) : "";
                            if (orgUnitLevel >= 6) printTotalValue["4totalValue" + count] = Number(printTotalValue["4totalValue" + count]) + Number(printValue["value" + count]);
                            count += 1
                        }
                        
                        // if (orgUnitLevel >= 6) printTotalValue["4totalValue" + count] = Number(printTotalValue["4totalValue" + index]) + Number(printValue["value" + index]);
                       
                    });
                }



                if (orgUnitLevel <= 6 && orgUnitLevel >= 2) {

                    if (orgUnitLevel != 5) {
                        addRow = ""
                        if (orgUnitLevel != 3 && orgUnitLevel != 2 && orgUnitLevel != 4) {

                            addRow += '<tr><td  style="font:bold;">' + orgUnit + '</td>';
                            for (let i = 0; i < totalCells; i++) {
                                addRow += '<td>' + printValue["value" + i] + '</td>'
                            }
                            addRow += '</tr>'
                        }
                        if (orgUnitLevel != 6) {
                            addRow += '<tr><td  style="font:bold;background:' + levelColor + ';">' + orgUnit + ' Total </td>';
                            for (let i = 0; i < totalCells; i++) {
                                addRow += '<td  style="font:bold;background:' + levelColor + ';">' + printTotalValue[orgUnitLevel + "totalValue" + i] + '</td>'
                            }
                            addRow += '</tr>'
                        }

                    }
                    for (let i = 0; i < totalCells; i++) {
                        printTotalValue[orgUnitLevel - 1 + "totalValue" + i] = Number(printTotalValue[orgUnitLevel - 1 + "totalValue" + i]) + Number(printTotalValue[orgUnitLevel + "totalValue" + i]);
                        printTotalValue[orgUnitLevel + "totalValue" + i] = "";
                    }

                } else {
                    addRow = '<tr><td  style="font:bold;">' + orgUnit + '</td>';
                    for (let i = 0; i < totalCells; i++) {
                        addRow += '<td>' + printValue["value" + i] + '</td>'
                    }
                    addRow += '</tr>'
                }
                document.getElementById("tableBody").innerHTML += addRow;

            }
        }

    }




    var tableToExcel = (function () {
        var uri = 'data:application/vnd.ms-excel;base64,'
            , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
            , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
            , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
        return function (table, name, filename) {
            if (!table.nodeType) table = document.getElementById(table)
            var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();
        }
    })()

</script>


<!-- printing script -->
<script type="text/javascript">
    function printContent(el) {
        var restorepage = document.body.innerHTML;
        var printcontent = document.getElementById(el).innerHTML;
        document.body.innerHTML = printcontent;
        window.print();
        document.body.innerHTML = restorepage;
    }

</script>