package sikd;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.BarChartModel;
import org.primefaces.model.chart.LegendPlacement;
import org.primefaces.model.chart.BarChartSeries;
import org.primefaces.model.chart.LineChartSeries;
import sikd.sikd5.model.combo.MonthYearCombo;
import sikd.sikd5.model.combo.PemdaCombo;
import sikd.sikd5.security.LoginMB;
import sikd.sikd5.sikd5bean.DashboardChartValue;
import sikd.sikd5.sikd5bean.laporan.Lampiran1Apbd;
import sikd.sikd5.sikd5bean.tabel.Pemda;
import sikd.sikd5.sikd5bean.tabel.TahunAnggaran;
import sikd.sikd5.sikd5bean.tabel.mgr.TUserAccount;
import sikd.sikd5.sikd5ejb.session.HomeSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.LaporanSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.SettingsSessionBeanRemote;

/**
 *
 * @author soraturaes
 */
@ManagedBean(name = "dashboardMBean")
@ViewScoped
public class DashboardMBean implements Serializable {

    protected MonthYearCombo monthYearCombo;
    @EJB
    SettingsSessionBeanRemote settingSession;
    @EJB
    protected HomeSessionBeanRemote homeSession;

    String titleYear, titleBulan, colTitle;
    PemdaCombo pemdaCombo;
    double nilai4 = 0, persen4 = 0;
    double nilai41 = 0, persen41 = 0;
    double nilai42 = 0, persen42 = 0;
    double nilai44 = 0, persen44 = 0;
    double nilai5 = 0, persen5 = 0;
    double nilai51 = 0, persen51 = 0;
    double nilai52 = 0, persen52 = 0;
    double nilai6 = 0, persen6 = 0;

    private BarChartModel chartModel;
    @EJB
    LaporanSessionBeanRemote laporanSession;
    
    @ManagedProperty(value="#{loginMB}")
    LoginMB loginMB;
    
    int maxTahun;
    int pengirimApbd=0, pengirimLra=0, pengirimDth=0;
    
    List<DashboardChartValue> topRanks, lowerRanks;
    
    @PostConstruct
    public void init() {
        try {            
            pemdaCombo = new PemdaCombo(true, false, ":contentoutput", "");
            pemdaCombo.setLabelStyle("padding: 5px;");
            pemdaCombo.setAlign("left");
            chartModel = new BarChartModel();
            monthYearCombo = new MonthYearCombo("idPanel", true, "idComboPeriode", null, false, null, "", "idComboYear", null, new ArrayList());
            monthYearCombo.setYears(settingSession.getTahuns());
            Date dd = new Date();            
            GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
            gc.setTime(dd);
            short yy = (short) gc.get(Calendar.YEAR);
            
            if(monthYearCombo.getYears()!=null && !monthYearCombo.getYears().isEmpty()){
                short ii = monthYearCombo.getYears().get(0).getTahun();
                while(ii < yy){
                    ii+=1;
                    monthYearCombo.getYears().add(0, new TahunAnggaran((short)ii, (short)0));
                }
                monthYearCombo.setSelectedYear(monthYearCombo.getYears().get(0));
            }
            else monthYearCombo.setSelectedYear(new TahunAnggaran(yy, (short)0));
            
            titleYear = monthYearCombo.getSelectedYear().getTahunAsString();
            titleBulan = monthYearCombo.getSelectedPeriode().getBulanString();
            colTitle = "SKPD";
            topRanks = new ArrayList();
            lowerRanks = new ArrayList();
            TUserAccount uac = loginMB.getTuserAccount();
            if (uac != null && uac.getPemda() != null) {
                pemdaCombo.setSelectedPemda(uac.getPemda());
                pemdaCombo.setView(false);
            }
            
            if (pemdaCombo.isView()) {
                pemdaCombo.setPemdas(loginMB.getPemdaByTahuns(monthYearCombo.getSelectedYear().getTahun()));
                Pemda p = new Pemda(0, "", "", "", "Nasional", "", (short) 0);
                int ii = monthYearCombo.getYears().size()-1;
                while(pemdaCombo.getPemdas() == null || pemdaCombo.getPemdas().isEmpty()){
                    if( ii >= 0)
                        pemdaCombo.setPemdas(loginMB.getPemdaByTahuns(monthYearCombo.getYears().get(ii--).getTahun()));
                    else break;
                }
                if (pemdaCombo.getPemdas() != null && !pemdaCombo.getPemdas().isEmpty()) {
                    pemdaCombo.getPemdas().add(0, p);
                    pemdaCombo.setSelectedPemda(pemdaCombo.getPemdas().get(0));
                } else {
                    pemdaCombo.addPemda(p);
                    pemdaCombo.setSelectedPemda(p);
                }
            }

//            onYearChange();
//            onRefresh();
        } catch (Exception ex) {
            Logger.getLogger(DashboardMBean.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }

    public MonthYearCombo getMonthYearCombo() {
        return monthYearCombo;
    }

    public void setMonthYearCombo(MonthYearCombo monthYearCombo) {
        this.monthYearCombo = monthYearCombo;
    }

    public void onYearChange() { }

    public void onPeriodeChange() {
        titleBulan = monthYearCombo.getSelectedPeriode().getBulanString();
    }

    public void onPemdaChange() { }
    public void onRefresh() {
        colTitle = "SKPD";
        pengirimApbd=0; pengirimLra=0; pengirimDth=0;
        List<Lampiran1Apbd> lras = new ArrayList();
        List<Lampiran1Apbd> apbds = new ArrayList();
        nilai4 = 0;        persen4 = 0;
        nilai41 = 0;        persen41 = 0;
        nilai42 = 0;        persen42 = 0;
        nilai44 = 0;        persen44 = 0;
        nilai5 = 0;        persen5 = 0;
        nilai51 = 0;        persen51 = 0;
        nilai52 = 0;        persen52 = 0;
        nilai6 = 0;        persen6 = 0;
        if (pemdaCombo.getSelectedPemda() != null && pemdaCombo.getSelectedPemda().getKodeSatker() != null) {
            titleYear = monthYearCombo.getSelectedYear().getTahunAsString();
            if(pemdaCombo.getSelectedPemda().getId()==0) colTitle = "Pemda";
            try {                
                List<DashboardChartValue> values = new ArrayList();
                if(pemdaCombo.getSelectedPemda().getId()==0){
                    values = homeSession.getDashboardNasionalValue(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort());
                }
                else{
                    values = homeSession.getDashboardPemdaValue(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort(), pemdaCombo.getSelectedPemda().getKodeSatker());
                }
                
                if( !values.isEmpty() ){
                    for (DashboardChartValue vv : values) {
                        if(vv.getBulan().trim().equals("4") ){
                            persen4= vv.getBelanja();
                            nilai4= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("4.1") ){
                            persen41= vv.getBelanja();
                            nilai41= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("4.2") ){
                            persen42= vv.getBelanja();
                            nilai42= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("4.3") ){
                            persen44= vv.getBelanja();
                            nilai44= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("5") ){
                            persen5= vv.getBelanja();
                            nilai5= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("5.1") ){
                            persen51= vv.getBelanja();
                            nilai51= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("5.2") ){
                            persen52= vv.getBelanja();
                            nilai52= vv.getPendapatan()/1000000000000.0;
                        }
                        else if(vv.getBulan().trim().equals("6") ){
                            persen6= vv.getBelanja();
                            nilai6= vv.getPendapatan()/1000000000000.0;
                        }
                    }
                }
                                
                List<Lampiran1Apbd> jums = laporanSession.getLaporanJumlahPemdaPengirim(monthYearCombo.getSelectedYear().getTahun());
                if( jums!=null && !jums.isEmpty()){
                    pengirimLra = (int)Math.round(jums.get(0).getNilai());
                    pengirimApbd = (int)Math.round(jums.get(1).getNilai());
                    pengirimDth = (int)Math.round(jums.get(2).getNilai());
                }
                
            } catch (Exception ex) {
                Logger.getLogger(DashboardMBean.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }
        }
        
            initChart();
            initTabel();
    }

    protected void initChart() {
        try {
            LineChartSeries lineSeries = new LineChartSeries();
            LineChartSeries lineSeries2 = new LineChartSeries();
            BarChartSeries barSeries = new BarChartSeries();
            BarChartSeries barSeries2 = new BarChartSeries();

            chartModel = new BarChartModel();
            chartModel.setShowPointLabels(false);
            chartModel.setShowDatatip(true);
            chartModel.setExtender("removeLegend");
            chartModel.setAnimate(true);
            String[] bs = new String[]{"Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sept", "Okt", "Nov", "Des"};
            Integer[] is = new Integer[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            for (int i = 0; i < is.length; i++) {
                lineSeries.set(bs[i], is[i]);
                lineSeries2.set(bs[i], is[i]);
                barSeries.set(bs[i], is[i]);
                barSeries2.set(bs[i], is[i]);
                
            }
            List<DashboardChartValue> sd = new ArrayList();
            if( monthYearCombo.getSelectedYear()!=null && pemdaCombo.getSelectedPemda() != null ){
                if(pemdaCombo.getSelectedPemda().getId() > 0 ){
                    sd = homeSession.getDashboardChartValue(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort(), pemdaCombo.getSelectedPemda().getKodeSatker());
                }
                else
                    sd = homeSession.getDashboardNasionalChartValue(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort());
            }
            if( sd!=null && !sd.isEmpty()){
                lineSeries = new LineChartSeries();
                lineSeries2 = new LineChartSeries();
                barSeries = new BarChartSeries();
                barSeries2 = new BarChartSeries();
            }
                
            long max = 0;
            
            
            if( sd!=null)
            for (int i = 0; i < sd.size(); i++) {
                lineSeries.set(sd.get(i).getBulan(), sd.get(i).getPendapatan());
                barSeries.set(sd.get(i).getBulan(), sd.get(i).getPendapatan());
                if (max < sd.get(i).getPendapatan()) {
                    max = Math.round(Math.ceil(sd.get(i).getPendapatan()));
                }
            }
            if( sd!=null)
            for (int i = 0; i < sd.size(); i++) {
                lineSeries2.set(sd.get(i).getBulan(), sd.get(i).getBelanja());
                barSeries2.set(sd.get(i).getBulan(), sd.get(i).getBelanja());
                if (max < sd.get(i).getBelanja()) {
                    max = Math.round(Math.ceil(sd.get(i).getBelanja()));
                }
            }
String strm = ""+max;
if( max>0 ){
    int pa = strm.trim().length()-1;
    long kal = 1;
    for (int i = 0; i < pa; i++) {
        kal = kal * 10;
    }
    if(max%kal != 0){
        long ll = Long.valueOf(strm.trim().charAt(0)+"");
        max = (ll+1)*kal;
    }
}

//            lineSeries.setLabel("Pendapatan");
//            lineSeries2.setLabel("Belanja");
            barSeries.setLabel("Pendapatan");
            barSeries2.setLabel("Belanja");

            chartModel.addSeries(lineSeries);
            chartModel.addSeries(lineSeries2);
            chartModel.addSeries(barSeries);
            chartModel.addSeries(barSeries2);
            chartModel.setLegendPosition("w");
            chartModel.setLegendPlacement(LegendPlacement.INSIDE);
            chartModel.setExtender("removeLegend");
            chartModel.setSeriesColors("00C0EF, F39C12");

            Axis yAxis = chartModel.getAxis(AxisType.Y);
            yAxis.setMin(0);
            yAxis.setMax(max);
            yAxis.setTickCount(11);

            Axis xAxis = chartModel.getAxis(AxisType.X);
            xAxis.setMin(0);
            xAxis.setMax(12);
            xAxis.setTickCount(1);
//            xAxis.setTickInterval("10");
            xAxis.setTickAngle(50);
        } catch (Exception ex) {
            Logger.getLogger(DashboardMBean.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }
    protected void initTabel() {
        try {
            topRanks = new ArrayList();
            lowerRanks = new ArrayList();
            List<DashboardChartValue> sd = new ArrayList();
            if( monthYearCombo.getSelectedYear()!=null && pemdaCombo.getSelectedPemda() != null ){
                if(pemdaCombo.getSelectedPemda().getId() > 0 ){
                    sd = homeSession.getRangkingBelanjaPemda(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort(), pemdaCombo.getSelectedPemda().getKodeSatker());
                }
                else
                    sd = homeSession.getRangkingBelanjaNasional(monthYearCombo.getSelectedYear().getTahun(), monthYearCombo.getSelectedPeriode().getBulanShort());
            }
            if( sd!=null && !sd.isEmpty()){
                for (int i = 0; i < sd.size(); i++) {
                    lowerRanks.add(new DashboardChartValue(sd.get(i)));
                    topRanks.add(new DashboardChartValue(sd.get(sd.size()-(i+1))));
                    lowerRanks.get(i).setPer((short)(i+1));
                    topRanks.get(i).setPer((short)(i+1));
                    if(i==9) break;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(DashboardMBean.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }

    public String getTitleYear() {
        return titleYear;
    }

    public String getTitleBulan() {
        return titleBulan;
    }

    public PemdaCombo getPemdaCombo() {
        return pemdaCombo;
    }

    public void setPemdaCombo(PemdaCombo pemdaCombo) {
        this.pemdaCombo = pemdaCombo;
    }

    public BarChartModel getChartModel() {
        return chartModel;
    }

    public void setChartModel(BarChartModel chartModel) {
        this.chartModel = chartModel;
    }

    public String getColTitle() {
        return colTitle;
    }

    public LoginMB getLoginMB() {
        return loginMB;
    }

    public void setLoginMB(LoginMB loginMB) {
        this.loginMB = loginMB;
    }

    public double getNilai4() {
        return nilai4;
    }

    public void setNilai4(double nilai4) {
        this.nilai4 = nilai4;
    }

    public double getPersen4() {
        return persen4;
    }

    public void setPersen4(double persen4) {
        this.persen4 = persen4;
    }

    public double getNilai41() {
        return nilai41;
    }

    public void setNilai41(double nilai41) {
        this.nilai41 = nilai41;
    }

    public double getPersen41() {
        return persen41;
    }

    public void setPersen41(double persen41) {
        this.persen41 = persen41;
    }

    public double getNilai42() {
        return nilai42;
    }

    public void setNilai42(double nilai42) {
        this.nilai42 = nilai42;
    }

    public double getPersen42() {
        return persen42;
    }

    public void setPersen42(double persen42) {
        this.persen42 = persen42;
    }

    public double getNilai44() {
        return nilai44;
    }

    public void setNilai44(double nilai44) {
        this.nilai44 = nilai44;
    }

    public double getPersen44() {
        return persen44;
    }

    public void setPersen44(double persen44) {
        this.persen44 = persen44;
    }

    public double getNilai5() {
        return nilai5;
    }

    public void setNilai5(double nilai5) {
        this.nilai5 = nilai5;
    }

    public double getPersen5() {
        return persen5;
    }

    public void setPersen5(double persen5) {
        this.persen5 = persen5;
    }

    public double getNilai51() {
        return nilai51;
    }

    public void setNilai51(double nilai51) {
        this.nilai51 = nilai51;
    }

    public double getPersen51() {
        return persen51;
    }

    public void setPersen51(double persen51) {
        this.persen51 = persen51;
    }

    public double getNilai52() {
        return nilai52;
    }

    public void setNilai52(double nilai52) {
        this.nilai52 = nilai52;
    }

    public double getPersen52() {
        return persen52;
    }

    public void setPersen52(double persen52) {
        this.persen52 = persen52;
    }

    public double getNilai6() {
        return nilai6;
    }

    public void setNilai6(double nilai6) {
        this.nilai6 = nilai6;
    }

    public double getPersen6() {
        return persen6;
    }

    public void setPersen6(double persen6) {
        this.persen6 = persen6;
    }

    public int getPengirimApbd() {
        return pengirimApbd;
    }

    public int getPengirimLra() {
        return pengirimLra;
    }

    public int getPengirimDth() {
        return pengirimDth;
    }

    public List<DashboardChartValue> getTopRanks() {
        return topRanks;
    }

    public void setTopRanks(List<DashboardChartValue> topRanks) {
        this.topRanks = topRanks;
    }

    public List<DashboardChartValue> getLowerRanks() {
        return lowerRanks;
    }

    public void setLowerRanks(List<DashboardChartValue> lowerRanks) {
        this.lowerRanks = lowerRanks;
    }
    
}
