package kr.co.kihyun.beans.totsys.report;

import javax.jdo.PersistenceManager;
//import javax.jdo.Transaction;
//import kr.co.kihyun.beans.entity.MUser;
//import kr.co.kihyun.beans.entity.Repoadm;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
//import kr.co.kihyun.beans.entity.util.*;
//import kr.co.kihyun.beans.totsys.report.ReportUpdate;
//import kr.co.kihyun.beans.user.GroupView;
//import kr.co.kihyun.lang.Encoder;
//import kr.co.kihyun.lang.MLong;
//import kr.co.kihyun.lang.MString;
//import kr.co.kihyun.moumi.MoumiConfig;
//import kr.co.kihyun.text.html.ServletUtil;
//import org.datanucleus.ObjectManager;
//import org.datanucleus.jdo.JDOPersistenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.sql.SQLException;
import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.beans.entity.TotTable;
//import java.util.List;
import kr.co.kihyun.beans.entity.TotReportType;
import kr.co.kihyun.beans.entity.AssignType;
import kr.co.kihyun.beans.entity.MDept;
import java.util.Set;
import java.util.ArrayList;
//import javax.jdo.Transaction;
//import java.util.Date;
import kr.co.kihyun.beans.entity.MoumiEntity;
import kr.co.kihyun.beans.entity.Recog;
import kr.co.kihyun.beans.entity.TotReportProcess;

public class ReportUpdate2 extends DBManager {

    private static final Logger LOG = LoggerFactory.getLogger(ReportUpdate.class);
    private ResultSet rs = null;

    public int deptUserUpdate(PersistenceManager pm, TotDoc totDoc, String[] insertDeptList) throws Exception {
        int succNum = 0;
        int ii = 0;
        String[] insertDeptList2 = new String[insertDeptList.length + 1];
        for (ii = 0; ii < insertDeptList.length; ii++) {
            insertDeptList2[ii] = insertDeptList[ii];
        }
        insertDeptList2[ii] = insertDeptList[ii - 1];

        //2014.12.02 Update by KWON,HAN : 기존의 처리는 1개이면 업데이트 처리를 하지 않는다.
        //                                개선하여 처리할 대상이 없으면 리턴한다.
        //if (insertDeptList.length < 2) {
        if (insertDeptList.length < 1) {
            return 0;
        }
        //===============================

        succNum = deptUserInsert(pm, totDoc, totDoc.getTotTables().iterator().next(), insertDeptList2);
        return succNum;
    }

    public int deptUserInsert(PersistenceManager pm, TotDoc totDoc, TotTable totTable, String[] deptIDList) throws Exception {
        int succNum = 0, ii = 0, jj = 0;
        try {
        //제출자료를 전부 사용하지 않는 것으로 초기화한다.
        Set<TotReport> reports = totDoc.getTotReports();
        for (TotReport report : reports) {
            report.setDeleted("Y");
        }

        //==============================================
        //일괄변경을 일단 주석처리함.
//        StringBuilder sql = new StringBuilder(120);
//        ArrayList<Object> paramList = new ArrayList<Object>();
//
//        int i = 0;
//        try {
//            sql.append("UPDATE MOUMI_TOT_REPORT SET DEL_TYPE = ? WHERE DOC_ID = ?");
//            paramList.add("Y");
//            paramList.add(totDoc.getId());
//
////LOG.debug("ReportUpdate2.deptUserMerge.1 ======================\nquery=\n{}\n===============================", sql.toString());
////LOG.debug("paramList={}", paramList);
//
//            i = execUpdate(sql.toString(), paramList.toArray());
//        } catch (SQLException sqlEx) {
//            execClose();
//            sqlEx.printStackTrace();
//            //return succNum;
//            LOG.error("ERROR.");
//            throw sqlEx;
//        } catch (Exception ex) {
//            execClose();
//            ex.printStackTrace();
//            //return succNum;
//            LOG.error("ERROR.");
//            throw ex;
//        } finally {
//             execClose();
//        }
        //==============================================


            if (deptIDList != null) {
                for (ii = 0; ii < deptIDList.length; ii++) {


                    Long id = getID(totDoc.getId(), deptIDList[ii], null);
                    if (id == null) {
                        if (ii > 0 && (ii + 1 == deptIDList.length && deptIDList[ii - 1] == deptIDList[ii])) {
                            break;
                        }
                        MDept dept = pm.getObjectById(MDept.class, deptIDList[ii]);
                        TotReport totReport = new TotReport(totDoc, dept);
                        totReport.setTableNum(totTable.getNum());
                        totReport.setAssignType(AssignType.ASSIGN_TO_DEPT);
                        pm.makePersistent(totReport);
                    } else {
//                        LOG.debug("**************************************************************** id=" + id);z
                        TotReport totReport = pm.getObjectById(TotReport.class, id);
                        totReport.setDeleted("N");
                        totReport.setType(TotReportType.REPORT);
                        totReport.setAssignType(AssignType.ASSIGN_TO_DEPT);
                        pm.makePersistent(totReport);
                    }
                    succNum = 1;
                }
                pm.flush();
            }
            return succNum;
        } catch (Exception ex) {
            LOG.error("ERROR.");
            throw ex;
        }
    }

    public Long getID(Long docID, String deptID, String userID) {
        StringBuilder sql = new StringBuilder(120);
        Long id = null;
        ArrayList<Object> paramList = new ArrayList<Object>();
        try {
            if (userID == null) {
                sql.append("select id from ").append(MoumiEntity.getTableName(TotReport.class)).append(" where doc_id=? and dept_id=?");
                paramList.add(docID);
                paramList.add(deptID);
            } else {
                sql.append("select id from ").append(MoumiEntity.getTableName(TotReport.class)).append(" where doc_id=? and dept_id=? and user_id=?");
                paramList.add(docID);
                paramList.add(deptID);
                paramList.add(userID);
            }
            rs = execQuery(sql.toString(), paramList.toArray());
            //System.out.println(sql.toString());
            if (rs.next()) {
                id = rs.getLong(1);
            }
            return id;
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
        } catch (SQLException sqlex) {
            id = null;
            //++++++++++++++++++++++++++++++++++++++++++++++++
        } catch (Exception ex) {
            id = null;
        } finally {
            close(rs);
            execClose();
            return id;
        }
    }

    /* 사용불가 : FOR UPDATE를 사용할 수 없으며, INSERT시에 SEQUENCE 를 사용하는 것이 아니므로 ... */
    public int deptUserMerge(PersistenceManager pm, TotDoc totDoc, String[] insertDeptList) throws Exception {
        int succNum = 0;
        int ii = 0;

        if (insertDeptList.length < 1) {
            return 0;
        }

        StringBuilder sql = new StringBuilder(1000);
        ArrayList<Object> paramList = new ArrayList<Object>();

        int i = 0;
        try {
            sql.append("UPDATE MOUMI_TOT_REPORT SET DEL_TYPE = ? WHERE DOC_ID = ?");
            paramList.add("Y");
            paramList.add(totDoc.getId());

//LOG.debug("ReportUpdate2.deptUserMerge.1 ======================\nquery=\n{}\n===============================", sql.toString());
//LOG.debug("paramList={}", paramList);

            i = execUpdate(sql.toString(), paramList.toArray());
//LOG.debug("i={}", i);
        } catch (SQLException sqlEx) {
            execClose();
            sqlEx.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw sqlEx;
        } catch (Exception ex) {
            execClose();
            ex.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw ex;
        } finally {
             execClose();
        }

/*
        Long id = null;
        sql.delete(0, sql.length());
        paramList.clear();
        try {
          //sql.append("SELECT NEXT_VAL FROM SEQUENCE_TABLE WHERE SEQUENCE_NAME='kr.co.kihyun.beans.entity.LongEntity' FOR UPDATE");
            sql.append("SELECT NEXT_VAL FROM SEQUENCE_TABLE WHERE SEQUENCE_NAME=?");
          //sql.append("SELECT NEXT_VAL FROM SEQUENCE_TABLE WHERE SEQUENCE_NAME=? FOR UPDATE");
            paramList.add("kr.co.kihyun.beans.entity.LongEntity");

//LOG.debug("ReportUpdate2.deptUserMerge.2 ======================\nquery=\n{}\n===============================", sql.toString());
//LOG.debug("paramList={}", paramList);

            rs = execQuery(sql.toString(), paramList.toArray());
            if (rs.next()) {
                id = rs.getLong(1);
            }
//LOG.debug("id={}", id);
        } catch (SQLException sqlEx) {
            close(rs);
            execClose();
            sqlEx.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw sqlEx;
        } catch (Exception ex) {
            close(rs);
            execClose();
            ex.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw ex;
        } finally {
            close(rs);
            execClose();
        }

        sql.delete(0, sql.length());
        paramList.clear();
        try {
            sql.append("UPDATE SEQUENCE_TABLE SET NEXT_VAL = TO_NUMBER(NEXT_VAL + ?) WHERE SEQUENCE_NAME=?");
            paramList.add(insertDeptList.length);
            paramList.add("kr.co.kihyun.beans.entity.LongEntity");

//LOG.debug("ReportUpdate2.deptUserMerge.3 ======================\nquery=\n{}\n===============================", sql.toString());
//LOG.debug("paramList={}", paramList);

            i = execUpdate(sql.toString(), paramList.toArray());
//LOG.debug("i={}", i);
        } catch (SQLException sqlEx) {
            execClose();
            sqlEx.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw sqlEx;
        } catch (Exception ex) {
            execClose();
            ex.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw ex;
        } finally {
             execClose();
        }
*/

        TotTable totTable = totDoc.getTotTables().iterator().next();

        try {
//            if (id != null && insertDeptList != null) {
            if (insertDeptList != null) {
                sql.delete(0, sql.length());

                sql.append("MERGE INTO MOUMI_TOT_REPORT A                      \n");
                sql.append("USING ( SELECT ?   AS DOC_ID                       \n");
                sql.append("            ,  ?   AS DEPT_ID                      \n");
                sql.append("          FROM DUAL                                \n");
                sql.append("      ) B                                          \n");
                sql.append("ON (A.DOC_ID = B.DOC_ID                            \n");
                sql.append("    AND A.DEPT_ID = B.DEPT_ID)                     \n");
                sql.append("WHEN NOT MATCHED THEN                              \n");
                sql.append("INSERT (                                           \n");
                sql.append("    A.ID                                           \n");
                sql.append("  , A.DOC_TYPE                                     \n");
                sql.append("  , A.DEL_TYPE                                     \n");
                sql.append("  , A.DEPT_ID                                      \n");
                sql.append("  , A.PRSS                                         \n");
                sql.append("  , A.RECOG                                        \n");
                sql.append("  , A.REG_DATE                                     \n");
                sql.append("  , A.TABLE_NUM                                    \n");
                sql.append("  , A.DOC_ID                                       \n");
                sql.append("  , A.TYPE                                         \n");
                sql.append("  )                                                \n");
                sql.append("VALUES (                                           \n");
                sql.append("    ( SELECT NVL(MAX(ID)+1,100000) FROM MOUMI_TOT_REPORT )       \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  , CURRENT DATE                                   \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  , ?                                              \n");
                sql.append("  )                                                \n");
                sql.append("WHEN MATCHED THEN                                  \n");
                sql.append("UPDATE SET A.DEL_TYPE  = ?                         \n");
                sql.append("         , A.TYPE      = ?                         \n");
                sql.append("         , A.DOC_TYPE  = ?                         \n");

//LOG.debug("ReportUpdate2.deptUserMerge.4 ======================\nquery=\n{}\n===============================", sql.toString());

                for (ii = 0; ii < insertDeptList.length; ii++) {
                    paramList.clear();
                    paramList.add(totDoc.getId());                        //DOC_ID
                    paramList.add(insertDeptList[ii]);                    //DEPT_ID

                  //paramList.add(id+ii);                                 //ID+ii
                    paramList.add(AssignType.ASSIGN_TO_DEPT.ordinal());   //DOC_TYPE
                    paramList.add("N");                                   //DEL_TYPE
                    paramList.add(insertDeptList[ii]);                    //DEPT_ID
                    paramList.add(TotReportProcess.ACCEPT.ordinal());     //PRSS
                    paramList.add(Recog.NOT_RECOG.ordinal());             //RECOG
                  //paramList.add("CURRENT DATE");                        //REG_DATE
                    paramList.add(totTable.getNum());                     //TABLE_NUM
                    paramList.add(totDoc.getId());                        //DOC_ID
                    paramList.add(TotReportType.REPORT.ordinal());        //TYPE

                    paramList.add("N");                                   //DEL_TYPE
                    paramList.add(TotReportType.REPORT.ordinal());        //TYPE
                    paramList.add(AssignType.ASSIGN_TO_DEPT.ordinal());   //DOC_TYPE

//LOG.debug("paramList={}", paramList);

                    i = execUpdate(sql.toString(), paramList.toArray());
//LOG.debug("i={}", i);
                    succNum = 1;
                }
            }

        } catch (Exception ex) {
            execClose();
            succNum = 0;
            ex.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw ex;
        } finally {
            execClose();
        }

        sql.delete(0, sql.length());
        paramList.clear();
        try {
            sql.append("UPDATE SEQUENCE_TABLE SET NEXT_VAL = (SELECT MAX(ID) FROM MOUMI_TOT_REPORT) WHERE SEQUENCE_NAME=?");
            paramList.add("kr.co.kihyun.beans.entity.LongEntity");

//LOG.debug("ReportUpdate2.deptUserMerge.5 ======================\nquery=\n{}\n===============================", sql.toString());
//LOG.debug("paramList={}", paramList);

            i = execUpdate(sql.toString(), paramList.toArray());
//LOG.debug("i={}", i);
        } catch (SQLException sqlEx) {
            execClose();
            sqlEx.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw sqlEx;
        } catch (Exception ex) {
            execClose();
            ex.printStackTrace();
            //return succNum;
            LOG.error("ERROR.");
            throw ex;
        } finally {
            execClose();
            return succNum;
        }

    }

}
