/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.siso.horario.MySqlDAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import pe.siso.horario.Beans.Merito;
import pe.siso.horario.DAO.MeritoDAO;

/**
 *
 * @author sistem02user
 */
public class MySqlMeritoDAO implements MeritoDAO {

    @Override
    public Merito consultarFichaEvaluacion(String codigoDocente, String codigoPeriodo, String codigoPeriodoAcademico) throws Exception {
        String base = "horario";

        Merito merito = new Merito();
        Connection cnx = null;
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            String query = "SELECT "
                    + "fe.cal_enc, "
                    + "fe.cal_asi, "
                    + "fe.cal_exa, "
                    + "fe.cal_mat, "
                    + "fe.cal_prom "
                    + "FROM "
                    + "ficha_evaluacion AS fe "
                    + "WHERE "
                    + "fe.cod_per = '" + codigoPeriodo + "' AND "
                    + "fe.cod_per_acad = '" + codigoPeriodoAcademico + "' AND fe.cod_prof ='" + codigoDocente + "' ";
            ResultSet rs = st.executeQuery(query);
            if (rs.next()) {
                merito.setPuntajeEncuesta(rs.getString("cal_enc"));
                merito.setPuntajeAsistencia(rs.getString("cal_asi"));
                merito.setPuntajeExamen(rs.getString("cal_exa"));
                merito.setPuntajeMateriales(rs.getString("cal_mat"));
                merito.setPromedio(rs.getString("cal_prom"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return merito;
    }

    @Override
    public int cantidad(String codigoPeriodo, String codigoPeriodoAcademico) throws Exception {
        int cantidad = 0;
        String base = "horario";
        Connection cnx = null;
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();

            String query = "SELECT COUNT(*) as cantidad "
                    + "FROM "
                    + "ficha_evaluacion AS fe "
                    + "WHERE "
                    + "fe.cod_per ='" + codigoPeriodo + "' AND "
                    + "fe.cod_per_acad ='" + codigoPeriodoAcademico + "'";
            ResultSet rs = st.executeQuery(query);
            if (rs.next()) {
                cantidad = rs.getInt("cantidad");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return cantidad;

    }

    @Override
    public ArrayList<Merito> listaColumnaPeriodo(String codigoPeriodoAcademico) throws Exception {
        ArrayList<Merito> lista = new ArrayList<Merito>();
        String base = "horario";
        Connection cnx = null;
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            String query = "SELECT enc.nom_enc, feva.cod_per FROM ficha_evaluacion AS feva "
                    + "INNER JOIN encuesta_docente.encuesta AS enc ON enc.cod_per = feva.cod_per "
                    + "WHERE feva.cod_per_acad = '" + codigoPeriodoAcademico + "'"
                    + "GROUP BY feva.cod_per";
            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {
                Merito merito = new Merito();
                merito.setCodigoPeriodo(rs.getString("cod_per"));
                merito.setNombrePeriodo(rs.getString("nom_enc"));
                lista.add(merito);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return lista;
    }

    @Override
    public ArrayList<Merito> listaTablaMerito(String codigoPeriodoAcademico) throws Exception {
        ArrayList<Merito> lista = new ArrayList<Merito>();
        String base = "horario";
        Connection cnx = null;
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            String query = "SELECT feva.cod_per FROM ficha_evaluacion AS feva "
                    + "WHERE feva.cod_per_acad = '" + codigoPeriodoAcademico + "'"
                    + "GROUP BY feva.cod_per";
            ResultSet rs = st.executeQuery(query);
            String codigoPeriodo = "";
            while (rs.next()) {
                if (codigoPeriodo.equals("")) {
                    codigoPeriodo = rs.getString("cod_per");
                } else {
                    codigoPeriodo += "," + rs.getString("cod_per");
                }
            }

            String query2 = "SELECT fev1.cod_prof, "
                    + "fev1.nom_prof ";
            if (!codigoPeriodo.equals("")) {
                String[] Array1 = codigoPeriodo.split(",");
                int cont = 1;
                String suma = "";
                String exam = "";
                String enc = "";
                String cadena = "";
                for (int a = 0; a < Array1.length; a++) {
                    String codPer = Array1[a];

                    if (exam.equals("")) {
                        exam = "Examen" + cont + "";
                    } else {
                        exam += ",'#'," + "Examen" + cont + "";
                    }

                    if (enc.equals("")) {
                        enc = "Encuesta" + cont + "";
                    } else {
                        enc += ",'#'," + "Encuesta" + cont + "";
                    }

                    if (suma.equals("")) {
                        suma = "Examen" + cont + "+Encuesta" + cont + "";
                    } else {
                        suma += "+" + "Examen" + cont + "+Encuesta" + cont + "";
                    }

                    if (cadena.equals("")) {
                        cadena = " INNER JOIN (SELECT cal_exa AS 'Examen" + cont + "' , "
                                + "cod_prof FROM ficha_evaluacion WHERE cod_per='" + codPer + "' AND "
                                + "cod_per_acad='" + codigoPeriodoAcademico + "') AS tbExamen" + cont + " ON fev1.cod_prof = tbExamen" + cont + ".cod_prof "
                                + "INNER JOIN (SELECT cal_enc AS 'Encuesta" + cont + "' , "
                                + "cod_prof FROM ficha_evaluacion WHERE cod_per='" + codPer + "' AND "
                                + " cod_per_acad='" + codigoPeriodoAcademico + "') AS tbEncuesta" + cont + " ON fev1.cod_prof = tbEncuesta" + cont + ".cod_prof ";

                    } else {
                        cadena += " INNER JOIN (SELECT cal_exa AS 'Examen" + cont + "' , "
                                + "cod_prof FROM ficha_evaluacion WHERE cod_per='" + codPer + "' AND "
                                + "cod_per_acad='" + codigoPeriodoAcademico + "') AS tbExamen" + cont + " ON fev1.cod_prof = tbExamen" + cont + ".cod_prof "
                                + "INNER JOIN (SELECT cal_enc AS 'Encuesta" + cont + "' , "
                                + "cod_prof FROM ficha_evaluacion WHERE cod_per='" + codPer + "' AND "
                                + " cod_per_acad='" + codigoPeriodoAcademico + "') AS tbEncuesta" + cont + " ON fev1.cod_prof = tbEncuesta" + cont + ".cod_prof ";
                    }

                    cont++;
                }
                query2 += ",CONCAT(" + exam + ",'#'," + enc + ") AS cadena";
                query2 += ",IF(ROUND(((" + suma + ")/cantidad),2)IS NULL,'-',ROUND(((" + suma + ")/cantidad),2)) AS Promedio  "
                        + "FROM ficha_evaluacion AS fev1 "
                        + "" + cadena + " "
                        + "INNER JOIN (SELECT cod_prof, (COUNT(IF(cal_exa='vacio',NULL,cal_exa))+COUNT(IF(cal_enc='Sin puntaje',NULL,cal_enc))) AS 'cantidad' "
                        + "FROM ficha_evaluacion WHERE cod_per_acad='" + codigoPeriodoAcademico + "' GROUP BY cod_prof) AS tbdivision "
                        + "ON fev1.cod_prof = tbdivision.cod_prof "
                        + "WHERE fev1.cod_per_acad='" + codigoPeriodoAcademico + "' "
                        + "GROUP BY fev1.cod_prof "
                        + "ORDER BY   "
                        + "IF(fev1.cod_prof NOT LIKE 'P%',Promedio,'') DESC, "
                        + "IF(fev1.cod_prof LIKE 'P%',Promedio,'') DESC";
                System.out.println("listaTablaMerito ==========>" + query2);
                ResultSet rs2 = st.executeQuery(query2);
                while (rs2.next()) {
                    Merito merito = new Merito();
                    merito.setCodigoProfesor(rs2.getString("cod_prof"));
                    merito.setNombreProfesor(rs2.getString("nom_prof"));
                    merito.setCadena(rs2.getString("cadena"));
                    merito.setPromedio(rs2.getString("Promedio"));
                    lista.add(merito);
                }
            } else {
                String query3 = "SELECT feva.cod_prof FROM ficha_evaluacion AS feva "
                        + "WHERE feva.cod_per_acad = '" + codigoPeriodoAcademico + "'"
                        + "GROUP BY feva.cod_prof";
                ResultSet rs3 = st.executeQuery(query3);
                while (rs3.next()) {
                    Merito merito = new Merito();
                    merito.setCodigoProfesor(rs.getString("cod_prof"));
                    lista.add(merito);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return lista;
    }

    @Override
    public ArrayList<Merito> listaTablaEvaluacionDocente(String codigoPlana, String codigoPeriodo, String codigoEncuesta) throws Exception {
        ArrayList<Merito> lista = new ArrayList<Merito>();
        String base = "horario";
        Connection cnx = null;
        String query = "";
        int dato = 0;
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();

            System.out.println("codigoPeriodo" + codigoPeriodo);

            String queryValidaPeriodoActivo = "SELECT est_per  FROM periodo_academico WHERE cod_per = '" + codigoPeriodo + "'";
            System.out.println("queryValidaPeriodoActivo=> " + queryValidaPeriodoActivo);

            ResultSet rs1 = st.executeQuery(queryValidaPeriodoActivo);

            if (rs1.next()) {
                dato = rs1.getInt("est_per");
            }

            if (dato == 0) {
                query = "SELECT \n"
                        + "				  m.cod_pro, \n"
                        + "				  m.nom_pro,\n"
                        + "          m.cod_cur, \n"
                        + "				  m.pun_mig, \n"
                        + "          TE.cod_enc,\n"
                        + "				  IFNULL(TE.pro_pla,'') as pro_pla, \n"
                        + "				  IFNULL(TE.exa,'') as exa, \n"
                        + "				  IFNULL(TE.not_enc,m.pun_mig) as not_enc, \n"
                        + "				  ROUND(((IF(IFNULL(TE.pro_pla,'') = '',0.00,TE.pro_pla)+IF(IFNULL(TE.exa,'') = '',0.00,TE.exa)+IF(IFNULL(TE.not_enc,m.pun_mig) = '',0.00,m.pun_mig))/ \n"
                        + "				  (IF(IFNULL(TE.pro_pla,'') = '',0,1)+IF(IFNULL(TE.exa,'') = '',0,1)+IF(IFNULL(TE.not_enc,m.pun_mig) = '',0,1))),2) \n"
                        + "				  as promedio, \n"
                        + "				  TE.prom, \n"
                        + "				  -- AVG(pro_pla,exa,not_enc) a \n"
                        + "				  TE.fec, \n"
                        + "				  TE.est_tab_eva,\n"
                        + "          IFNULL(TE.puesto,'') as puesto,\n"
                        + "          IFNULL(TE.observacion,'') as observacion \n"
                        + "				  FROM \n"
                        + "				  migracion AS m \n"
                        + "	        INNER JOIN curso ce ON ce.cod_cur=m.cod_cur\n"
                        + "				  left JOIN tabla_evaluacion TE ON TE.cod_doc = m.cod_pro AND TE.cod_enc = '" + codigoEncuesta + "' AND TE.cod_per_gen = (SELECT cod_per_gen FROM periodo_academico WHERE cod_per = '" + codigoPeriodo + "') \n"
                        + "          \n"
                        + "				  WHERE \n"
                        + "         ce.cod_cur \n"
                        + "\n"
                        + "             IN (\n"
                        + "\n"
                        + "							SELECT\n"
                        + "								c.cod_cur\n"
                        + "								\n"
                        + "							 FROM\n"
                        + "							 curso c where  c.cod_pla in (ce.cod_pla) -- m.cod_cur\n"
                        + "							\n"
                        + ") and \n"
                        + " ce.cod_pla = '" + codigoPlana + "'\n"
                        + " and TE.cod_pla = ce.cod_pla";

            } else {
                query = "SELECT \n"
                        + "				  m.cod_pro, \n"
                        + "				  m.nom_pro,\n"
                        + "          m.cod_cur, \n"
                        + "				  m.pun_mig, \n"
                        + "          TE.cod_enc,\n"
                        + "				  IFNULL(TE.pro_pla,'') as pro_pla, \n"
                        + "				  IFNULL(TE.exa,'') as exa, \n"
                        + "				  IFNULL(TE.not_enc,m.pun_mig) as not_enc, \n"
                        + "				  ROUND(((IF(IFNULL(TE.pro_pla,'') = '',0.00,TE.pro_pla)+IF(IFNULL(TE.exa,'') = '',0.00,TE.exa)+IF(IFNULL(TE.not_enc,m.pun_mig) = '',0.00,m.pun_mig))/ \n"
                        + "				  (IF(IFNULL(TE.pro_pla,'') = '',0,1)+IF(IFNULL(TE.exa,'') = '',0,1)+IF(IFNULL(TE.not_enc,m.pun_mig) = '',0,1))),2) \n"
                        + "				  as promedio, \n"
                        + "				  TE.prom, \n"
                        + "				  -- AVG(pro_pla,exa,not_enc) a \n"
                        + "				  TE.fec, \n"
                        + "				  TE.est_tab_eva,\n"
                        + "          IFNULL(TE.puesto,'') as puesto,\n"
                        + "          IFNULL(TE.observacion,'') as observacion \n"
                        + "				  FROM \n"
                        + "				  migracion AS m \n"
                        + "	        INNER JOIN curso ce ON ce.cod_cur=m.cod_cur\n"
                        + "				  left JOIN tabla_evaluacion TE ON TE.cod_doc = m.cod_pro AND TE.cod_enc = '" + codigoEncuesta + "' AND TE.cod_per_gen = (SELECT cod_per_gen FROM periodo_academico WHERE cod_per = '" + codigoPeriodo + "') \n"
                        + "          \n"
                        + "				  WHERE \n"
                        + "         ce.cod_cur \n"
                        + "\n"
                        + "             IN (\n"
                        + "\n"
                        + "	SELECT\n"
                        + "	c.cod_cur\n"
                        + "		\n"
                        + "	 FROM\n"
                        + "	curso c where  c.cod_pla in (ce.cod_pla) -- m.cod_cur\n"
                        + "	\n"
                        + ") and \n"
                        + " ce.cod_pla = '" + codigoPlana + "'\n";

            }

//				+ "cod_cur IN (SELECT\n"
//				+ "curso.cod_cur\n"
//				+ "FROM\n"
//				+ "curso\n"
//				+ "WHERE curso.cod_pla = '" + codigoPlana + "')";
            System.out.println("listaTablaEvaluacionDocente=> " + query);
            ResultSet rs = st.executeQuery(query);

            while (rs.next()) {
                Merito merito = new Merito();
                merito.setCodigoProfesor(rs.getString("cod_pro"));
                merito.setNombreProfesor(rs.getString("nom_pro"));
                merito.setPuntajeEncuesta(rs.getString("pun_mig"));
                merito.setPuntajeExamen(rs.getString("exa"));
                merito.setPuntajePlana(rs.getString("pro_pla"));
                merito.setPromedio(rs.getString("promedio"));
                merito.setPuesto(rs.getString("puesto"));
                merito.setObservacion(rs.getString("observacion"));

                lista.add(merito);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return lista;
    }

    @Override
    public Merito consultarNotas(String codigoDocente, String codigoPeriodo) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int registrarNotaTablaEvaluacion(String codigoDocente, String nombreDocente, String codigoPlana, String codigoPeriodoAcademico, String notaEncuesta, String notaPlana, String notaExamen, String promedio, String codigoEncuesta,String puesto,String observacion) throws Exception {
        int dato = 0;
        String base = "horario";
        Connection cnx = null;
        String codigoTablaEvaluacion = "";
        try {
            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            Statement st2 = cnx.createStatement();

            String consultar = "SELECT\n"
                    + "TE.cod_tabla_evaluacion\n"
                    + "FROM\n"
                    + "tabla_evaluacion AS TE\n"
                    + "WHERE\n"
                    + "TE.cod_per_gen = (SELECT	cod_per_gen FROM periodo_academico WHERE	cod_per = '" + codigoPeriodoAcademico + "' )\n"
                    + "AND cod_doc = '" + codigoDocente + "' AND cod_pla='" + codigoPlana + "' AND cod_enc='" + codigoEncuesta + "'";
            ResultSet rs = st2.executeQuery(consultar);
            if (rs.next()) {
                codigoTablaEvaluacion = rs.getString("cod_tabla_evaluacion");
            }

            if (!codigoTablaEvaluacion.equals("")) {
                String update = "UPDATE tabla_evaluacion\n"
                        + "SET \n"
                        + " cod_per_gen = (SELECT cod_per_gen FROM periodo_academico WHERE cod_per = '" + codigoPeriodoAcademico + "' ), ";

                if (notaPlana.equals("vacio")) {
                    update += "pro_pla = NULL,";
                } else {
                    update += "pro_pla = '" + notaPlana + "',";
                }

                if (notaExamen.equals("vacio")) {
                    update += "exa = NULL,";
                } else {
                    update += "exa = '" + notaExamen + "',";
                }
                
                
                if (puesto.equals("vacio")) {
                    update += "puesto = NULL,";
                } else {
                    update += "puesto = '" + puesto + "',";
                }
                
                if (observacion.equals("vacio")) {
                    update += "observacion = NULL,";
                } else {
                    update += "observacion = '" + observacion + "',";
                }
                
                
                
                

                update += " not_enc = '" + notaEncuesta + "',\n"
                        + " prom = '" + promedio + "',\n"
                        + " fec = CURDATE(),\n"
                        + " est_tab_eva = '2' \n"
                        + "WHERE\n"
                        + "(cod_tabla_evaluacion = '" + codigoTablaEvaluacion + "');";
                System.out.println("registrarNotaTablaEvaluacion UPDATE ====> " + update);
                dato = st.executeUpdate(update);
                
                
                
            } else {
                String query = "INSERT INTO tabla_evaluacion (\n"
                        + "	 cod_per_gen ,\n"
                        + "	 cod_enc ,\n"
                        + "	 cod_doc ,\n"
                        + "	 cod_pla ,\n"
                        + "	 nom_doc ,\n"
                        + "	 pro_pla ,\n"
                        + "	 exa ,puesto,observacion,\n"
                        + "	 not_enc ,\n"
                        + "	 prom ,\n"
                        + "	 fec ,\n"
                        + "	 est_tab_eva\n"
                        + "	)\n"
                        + "VALUES\n"
                        + "	(\n"
                        + "		(SELECT	cod_per_gen FROM 	periodo_academico WHERE	cod_per = '" + codigoPeriodoAcademico + "' ),\n"
                        + "		'" + codigoEncuesta + "',\n"
                        + "		'" + codigoDocente + "',\n"
                        + "		'" + codigoPlana + "',\n"
                        + "		'" + nombreDocente + "',";

                if (notaPlana.equals("vacio")) {
                    query += "NULL,";
                } else {
                    query += "'" + notaPlana + "',";
                }

                if (notaExamen.equals("vacio")) {
                    query += "NULL,";
                } else {
                    query += "'" + notaExamen + "',";
                }
                
                if (puesto.equals("vacio")) {
                    query += "NULL,";
                } else {
                    query += "'" + puesto + "',";
                }
                
                 if (observacion.equals("vacio")) {
                    query += "NULL,";
                } else {
                    query += "'" + observacion + "',";
                }
                
                
                

                query += "		'" + notaEncuesta + "',\n"
                        + "		'" + promedio + "',\n"
                        + "		CURDATE(),\n"
                        + "		'1'\n"
                        + "	);";

                System.out.println("registrarNotaTablaEvaluacion ====> " + query);
                dato = st.executeUpdate(query);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cnx.close();
        }
        return dato;
    }

    @Override
    public int registrarPuesto(String codDoc, String codPlana, String codEncuesta, String puesto) {
        int dato = 0;
        String base = "horario";
        Connection cnx = null;

        try {

            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            String query = "UPDATE tabla_evaluacion set puesto='" + puesto + "' where cod_doc='" + codDoc + "' and cod_pla='" + codPlana + "' and cod_enc='" + codEncuesta + "' ";
            dato = st.executeUpdate(query);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return dato;
    }

    @Override
    public int registrarObservacion(String codDoc, String codPlana, String codEncuesta, String observacion) {
        int dato = 0;
        String base = "horario";
        Connection cnx = null;

        try {

            cnx = MySqlDAOFactory.obtenerConexion(base);
            Statement st = cnx.createStatement();
            String query = "UPDATE tabla_evaluacion set observacion='" + observacion + "' where cod_doc='" + codDoc + "' and cod_pla='" + codPlana + "' and cod_enc='" + codEncuesta + "' ";
            System.out.println("QUERY UPDATE --->" + query);
            dato = st.executeUpdate(query);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return dato;
    }

}
