package kr.co.kihyun.beans.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NullValue;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import kr.co.kihyun.beans.entity.ecross.NeisParty;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;

import kr.co.kihyun.beans.entity.util.QueryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class MDept extends AbstractOrganization<String> implements HandySync {
 
	/**
	 * 
	 **/
	private static final long serialVersionUID = 8631163175960917370L;
    private static final Logger LOG = LoggerFactory.getLogger(MDept.class);
	@Persistent       
	private String id;

	@Persistent
	private String handyId;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private String name;

	@Persistent
	private String address;

	@Persistent
	private String phone;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private String passcode;

	@Persistent
	private String recoImg;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private SysAuth sysAuth = SysAuth.TOTPER;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private Long priority = 0L;

	@Persistent
	private String upperDept;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private String rootDept;

	@Persistent
	private String organ;

	@Persistent
	private String secId;

	@Persistent
	private String seqnum;

	@Persistent(nullValue = NullValue.EXCEPTION)
	private boolean isDocUnit = true; // COLUMN: sel_type

	@Persistent(nullValue = NullValue.EXCEPTION)
	private boolean isOut = false; // COLUMN: is_out

	@Persistent
	private String location;

	@Persistent
	private Grade grade;

	@Persistent
	private Foundation foundation;


	public MDept() {
	}

	public MDept(String passcode, String name) {
//		this.setPasscode(passcode);
//		this.setName(name);
	}

	public MDept(String passcode, String name, MDept upperDept) {
//		this.setPasscode(passcode);
//		this.setName(name);
//		this.setUpperDept(upperDept);
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

//	public void setHandyId(String handyId) {
//		this.handyId = handyId;
//	}

	public String getHandyId() {
		return handyId;
	}

	public String getName() {
		return this.name;
	}

//	public void setName(String name) {
//		this.name = name;
//	}

	public String getAddress() {
		return this.address;
	}

//	public void setAddress(String address) {
//		this.address = address;
//	}

	public String getPhone() {
		return this.phone;
	}

//	public void setPhone(String phone) {
//		this.phone = phone;
//	}

	public String getPasscode() {
		return this.passcode;
	}

//	public void setPasscode(String passcode) {
//		this.passcode = passcode;
//	}

	public String getRecoImg() {
		return this.recoImg;
	}

//	public void setRecoImg(String img) {
//		this.recoImg = img;
//	}

	public SysAuth getSysAuth() {
		return this.sysAuth;
	}

//	public void setSysAuth(SysAuth sysAuth) {
//		this.sysAuth = sysAuth;
//	}

	public Long getPriority() {
		return this.priority;
	}

//	public void setPriority(int priority) {
//		this.priority = priority;
//	}


	public MDept getUpperDept(PersistenceManager pm) {
		try {
			pm = new MPersistenceManager(pm);
            if(this.upperDept == null)
                this.upperDept = "";
            else
                this.upperDept = upperDept;
			return pm.getObjectById(MDept.class, this.upperDept);
		} catch (JDOObjectNotFoundException jonfe) {
			return null;
		}
	}

    public void setUpperDept(MDept upperDept) {
		if (upperDept == null)
			this.upperDept = null;
		else
			this.upperDept = upperDept.getId();
	}

	@Override
	public MDept getRootDept(PersistenceManager pm) {
		try {
			pm = new MPersistenceManager(pm);
			return pm.getObjectById(MDept.class, this.rootDept);
		} catch (JDOObjectNotFoundException jonfe) {
			return null;
		}
	}

	@Override
	public NeisParty getNeisParty(PersistenceManager pm) {
		return NeisParty.valueOf(this.rootDept.substring(0, 1) + (this.rootDept.startsWith("A") ? "00" : "10"));
	}

	

	public MDept getOrgan(PersistenceManager pm) {
		try {
			pm = new MPersistenceManager(pm);
			return pm.getObjectById(MDept.class, this.organ);
		} catch (JDOObjectNotFoundException jonfe) {
			return null;
		}
	}

//	public void setOrgan(MDept organ) {
//		if (organ == null)
//			this.organ = null;
//		else
//			this.organ = organ.getId();
//	}

	@Deprecated
	public String getSecId() {
		return this.secId;
	}

//	public void setSecId(String sectionId) {
//		this.secId = sectionId;
//	}

	public String getSeqnum() {
		return this.seqnum;
	}

//	public void setSeqnum(String num) {
//		this.seqnum = num;
//	}

	public static enum SEL_TYPE {
		INVALID, VALID;
	}

	public boolean isDocUnit() {
		return this.isDocUnit;
	}

//	public void setDocUnit(boolean isDocUnit) {
//		this.isDocUnit = isDocUnit;
//	}

	public boolean isOut() {
		return this.isOut;
	}

//	public void setOut(boolean isOut) {
//		this.isOut = isOut;
//	}

	public String getLocation() {
		return this.location;
	}

//	public void setLocation(String location) {
//		this.location = location;
//	}

	public Grade getGrade() {
		if (this.grade == null)
			return Grade.NULL;
		return this.grade;
	}

//	@Deprecated
//	public void setGrade(String grade) {
//		this.grade = grade;
//	}

	public Foundation getFoundation() {
		if (this.foundation == null)
			return Foundation.NULL;
		return this.foundation;
	}

	public List<TotReport> getCompReports(PersistenceManager pm) {
		return this.getCompReports(pm, null);
	}

	public List<TotReport> getCompReports(PersistenceManager pm, String filterKey, Object filterValue) {
		Map<String, Object> filterMap = new HashMap<String, Object>(1);
		filterMap.put(filterKey, filterValue);
		return this.getCompReports(pm, filterMap);
	}

	@SuppressWarnings("unchecked")
	public List<TotReport> getCompReports(PersistenceManager pm, Map<String, Object> filterMap) {
		QueryImpl q = new QueryImpl(pm, TotReport.class);
		StringBuilder filter = new StringBuilder(300).append("isDeleted == false && type == TYPE_REPORT")
				.append(" && (process == PROCESS_COMP || process == PROCESS_END").append(" || process == PROCESS_NOT)")
				.append(" && totDoc.isDeleted == false && mDept == dept");

    List tmpList=null;
    String findWord=null;
    for (Iterator<String> keyIterator = filterMap.keySet().iterator(); keyIterator.hasNext();)
    {
        String filterKey = keyIterator.next();
        Object filterValue = filterMap.get(filterKey);
        if(filterKey == null || filterKey.length() <= 0) continue;
        if(filterKey.equals("totDoc.mUser.name")) findWord=(String)filterValue;
    }

            q.setFilter(filter.toString());
            q.setSearchFilter(filterMap);
            q.declareParameters("String dept");
            q.setOrdering("totDoc.id DESC");

                    //return (List<TotReport>) q.execute(this.getId());

                    List<TotReport> totReports = new ArrayList<TotReport>();
                    totReports=(List<TotReport>) q.execute(this.getId());
                    List<TotReport> result = new ArrayList<TotReport>();

                    for (TotReport totReport : totReports)
                    {

                                if(findWord!=null)
                                {
                                    String tmp=totReport.getTotDoc().getOwnerName(pm);
                                    if(tmp==null) continue;
                                    if(tmp.indexOf(findWord)>=0) result.add(totReport);


                                }
                                else result.add(totReport);

            }

            return result;

        }

        //제출진행-담당부서 제출현황 모두 보이게
        public List<TotReport> getDeptSavedReports(PersistenceManager pm, String filterKey, Object filterValue){
            Map<String, Object> filterMap = new HashMap<String, Object>(1);
		filterMap.put(filterKey, filterValue);
		return this.getDeptSavedReports(pm, filterMap);
        }
        
        @SuppressWarnings("unchecked")
        public List<TotReport> getDeptSavedReports(PersistenceManager pm, Map<String, Object> filterMap){
            QueryImpl q = new QueryImpl(pm, TotReport.class);
            StringBuilder filter = new StringBuilder(110).append("isDeleted == false && type == TotReportType.REPORT")
				.append(" && (process == TotReportProcess.TEMP || process == TotReportProcess.APPROVE)")
				.append(" && mDept == user");
		q.setFilter(filter.toString());
		q.declareImports("import kr.co.kihyun.beans.entity.*");
		q.declareParameters("String user");
		q = new QueryImpl(pm, TotReport.class, (List<TotReport>) q.execute(this.getId()));

       List tmpList=null;
       String findWord=null;
       for (Iterator<String> keyIterator = filterMap.keySet().iterator(); keyIterator.hasNext();)
       {
         String filterKey = keyIterator.next();
         Object filterValue = filterMap.get(filterKey);
         if(filterKey == null || filterKey.length() <= 0) continue;
         if(filterKey.equals("totDoc.mUser.name")) findWord=(String)filterValue;
       }

		filter = new StringBuilder(300).append("totDoc.isDeleted == false");
		q.setFilter(filter.toString());
		q.setSearchFilter(filterMap);
		q.declareParameters("java.util.Date sysdate");
		q.setOrdering("totDoc.id DESC");
                //return (List<TotReport>) q.execute(new Date());

                List<TotReport> totReports = new ArrayList<TotReport>();
                totReports=(List<TotReport>) q.execute(new Date());
                List<TotReport> result = new ArrayList<TotReport>();

                for (TotReport totReport : totReports)
                {
                            if(findWord!=null)
                            {
                                String tmp=totReport.getTotDoc().getOwnerName(pm);
                                if(tmp==null) continue;
                                if(tmp.indexOf(findWord)>=0) result.add(totReport);
                            }
                   else result.add(totReport);
		       }


		return result;

      }
/********************************** Leejiho **********************/
        public String getOrgan()
        {
            return organ;
        }

        public String getUpper()
        {
            return upperDept;
        }
/********************************** Leejiho **********************/
}
