package jp.co.y_net.amm.dao;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import jp.co.y_net.amm.common.AppLogger;
import jp.co.y_net.amm.common.AppUtils;
import jp.co.y_net.amm.common.ChoiceElement;
import jp.co.y_net.amm.common.ResourceReader;

import org.apache.commons.lang.StringUtils;


public class Org extends AppDto implements Serializable {
	private static final long serialVersionUID = 1L;
	
	/** 申請日に使用するDateFormat */
	final DateFormat DF_YYYYMMDDHHMM = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	
	public static final int KIND_PERSONAL = 9; // 個人会員
	public static final String KIND_PERSONAL_STR = "9"; // 個人会員
	
	public static final int KIND_運営管理 = 999;
	
	public static final int LIMITNUM_未指定 = -1;
	
    private Integer orgid;
    private Integer kind;
    private String name;
    private String adminname;
    private String adminnamekana;
    private String postnum;
    private String address;
    private String telnum;
    private String mail;
    private Integer fromdate;
    private Integer todate;
    private Integer limitnum;
    private Long entrydate;
    private Long approvaldate;
    private Long rejectdate;
    private String note;
    private Long joindate;
    private Integer status;
    
    /** 状態 */
    public static final int STATUS_未処理 = 0;
    public static final int STATUS_承認済み = 1;
    public static final int STATUS_拒否済み = 2;
    public static final int STATUS_本登録済み = 3;
    
    public static Map<String, String> getStatusMap() {
        Map<String, String> map = new TreeMap<String, String>();
        map.put("0", "未処理");
        map.put("1", "承認済み");
        map.put("2", "拒否済み");
        map.put("3", "本登録済み");
        return map;
    }
    
    /**
     * @return 状態の名称
     */
    public String getStatus_Disp() {
        if(status == null) {
            return null;
        }
        switch (status) {
        case STATUS_未処理:
            return "未処理";
        case STATUS_承認済み:
            return "承認済み";
        case STATUS_拒否済み:
            return "拒否済み";
        case STATUS_本登録済み:
            return "本登録済み";
        default:
            return String.valueOf(status);
        }
    }
    
    /** @return 機関会員の種類の名称 */
    public String getKind_Disp() {
        String key = getKind().toString();
        return getOrgkindMap().get(key);
    }
    /**
     * @return 個人会員であれば true
     */
    public boolean isPersonalOrg() {
        if(this.kind != null && this.kind == KIND_PERSONAL) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return 郵便番号のハイフン付き表記
     */
    public String getPostnum_Disp() {
        String tmp = getPostnum();
        if(tmp != null && tmp.length() > 4) {
            StringBuilder sb = new StringBuilder(tmp);
            sb.insert(3, "-");
            tmp = sb.toString();
        }
        return tmp;
    }
    
    /**
     * @return 機関・団体であればその名称。個人会員であれば代表者名。
     */
    public String getNameOrAdminname() {
        String name;
        if(this.isPersonalOrg()) {
            name = this.getAdminname();
        } else {
            name = this.getName();
        }
//        if(StringUtils.isEmpty(this.getName()) == false) {
//            name = this.getName();
//        } else if(StringUtils.isEmpty(this.getAdminname()) == false) {
//            name = this.getAdminname();
//        } else {
//            name = "";
//        }
        
        
        String str = StringUtils.abbreviate(name, 100);
        return str;
    }
    


//    public static void main(String[] args) {
////      Map<String, String> map = getKindMap();
////      for(Entry<String, String> e: map.entrySet()) {
////          System.out.println(e.getKey() + "=" + e.getValue());
////      }
////      System.out.println(ResourceReader.getText("message/termsofuse"));
//        Org org = new Org();
//        org.setPostnum("123");
//        System.out.println(org.getPostnum_Disp());
//        org.setPostnum("1234");
//        System.out.println(org.getPostnum_Disp());
//        org.setPostnum("12345");
//        System.out.println(org.getPostnum_Disp());
//        org.setPostnum("123456");
//        System.out.println(org.getPostnum_Disp());
//        org.setPostnum("1234567");
//        System.out.println(org.getPostnum_Disp());
//        org.setPostnum(null);
//        System.out.println(org.getPostnum_Disp());
//  }
    
    public static TreeMap<String, String> getOrgkindMap() {
        String orgkinds = ResourceReader.getStringQuick("orgkinds");
        String[] orgkindArray = orgkinds.split(",");
        TreeMap<String, String> map = new TreeMap<String, String>();
        for(String kind: orgkindArray) {
            kind = kind.trim();
            String key;
            String value;
            int index = kind.indexOf(".");
            if(index != -1) {
                key = kind.split("\\.")[0];
                value = kind.split("\\.")[1];
            } else {
                key = kind;
                value = "";
            }
            map.put(key, value);
        }
        return map;
    }
    
    /**
     * @return 申請日時（書式：yyyy/MM/dd HH:mm）
     */
    public String getEntrydate_Disp() {
        String entrydate;
        try {
            Date d = AppUtils.toDate(this.getEntrydate());
            if(d != null) {
                entrydate = DF_YYYYMMDDHHMM.format(d);
            } else {
                entrydate = "";
            }
        } catch (Exception e) {
            AppLogger.error(e);
            if (this.getEntrydate() != null) {
                entrydate = String.valueOf(this.getEntrydate());
            } else {
                entrydate = "";
            };
        }
        return entrydate;
    }
    
    /**
     * 申請日付のソートに用いるComparator
     */
    public static class EntryDateComparator implements Comparator<Org>{
        /** trueに変更すると 申請日時の新しい順 */
        private boolean desc = false; 
        
        public EntryDateComparator(boolean desc) {
            this.desc = desc;
        }
        
        @Override
        public int compare(Org o1, Org o2) {
            int reverse = 1;
            //if(sortModel.getObject().getId().equals("1")) {
            if(desc) {
                reverse = -1;
            }
            
            Long n1 = 0L;
            Long n2 = 0L;
            if(o1 != null && o1.getEntrydate() != null) n1 = o1.getEntrydate();
            if(o2 != null && o2.getEntrydate() != null) n2 = o2.getEntrydate();
            
            return Long.compare(n1, n2) * reverse;
        }
    }
    
    /** 登録可能会員数の選択肢 */
    public static List<ChoiceElement> createLimitChices(String limitnumValue) {
        List<Integer> limitnumList = new ArrayList<Integer>();
        limitnumList.add(LIMITNUM_未指定); // 未指定
        /* 設定ファイルより選択肢を取得 */
        String str = ResourceReader.getStringQuick("limitnums");
        String[] array = str.split(",");
        for (int i = 0; i < array.length; i++) {
            int num;
            try {
                num = Integer.parseInt(array[i].trim());
                limitnumList.add(num);
            } catch (NumberFormatException e) {
                AppLogger.info("設定値 limitnums に数値に変換できない値があります。", e);
            }
        }
        String existValue = String.valueOf(limitnumValue);
        if(StringUtils.isEmpty(existValue) == false) {
            int iExistValue;
            try {
                iExistValue = Integer.parseInt(existValue);
                if(limitnumList.contains(iExistValue) == false) {
                    limitnumList.add(iExistValue); // 現在の値が選択肢になければ追加する
                }
            } catch (NumberFormatException e1) {
                // 処理なし
            }
        }
        Collections.sort(limitnumList);
        List<ChoiceElement> choiceLimitnum = new ArrayList<ChoiceElement>();
        for (Integer num: limitnumList) {
            String label;
            if(num == LIMITNUM_未指定) {
                label = "指定なし";
            } else {
                label = num + "人";
            }
            choiceLimitnum.add(new ChoiceElement(String.valueOf(num), label));
        }
        return choiceLimitnum;
    }
    
    public boolean is利用可能期間内() {
        return betweenNow(this.fromdate, this.todate);
    }

    private static boolean betweenNow(Integer from, Integer to) {
        if(from == null || from == -1) from = Integer.MIN_VALUE;
        if(to == null || to == -1) to = Integer.MAX_VALUE;
        Integer now = AppUtils.createNowShort();
        return from <= now && now <= to;
    }
//    public static void main(String[] args) {
//        System.out.println(betweenNow(-1, -1));
//        System.out.println(betweenNow(null, null));
//        System.out.println(betweenNow(20150803, 20150831));
//        System.out.println(betweenNow(20150804, 20150831));
//        System.out.println(betweenNow(20150801, 20150802));
//        System.out.println(betweenNow(20150801, 20150803));
//    }

    /**
     * @return 利用期間（表示用）
     */
    public String getFromTodate_Disp() {
        String fromdate = AppUtils.toStrYyyyMMdd(this.getFromdate());
        if(is利用期間未指定(this.getFromdate())) {
            fromdate = "";
        }
        String todate = AppUtils.toStrYyyyMMdd(this.getTodate());
        if(is利用期間未指定(this.getTodate())) {
            todate = "";
        }
        String fromtodateStr;
        if(StringUtils.isEmpty(fromdate) && StringUtils.isEmpty(todate)) {
            fromtodateStr = "";
        } else if (StringUtils.isEmpty(fromdate) == false && StringUtils.isEmpty(todate) == true) {
            fromtodateStr = fromdate + "～";
        } else if (StringUtils.isEmpty(fromdate) == true && StringUtils.isEmpty(todate) == false) {
            fromtodateStr = "～" + todate;
        } else {
            fromtodateStr = fromdate + "～" + todate;
        }
        if("～".equals(fromtodateStr)) {
            return "";
        }
        return fromtodateStr;
    }
    
    private boolean is利用期間未指定(Integer fromOrTo) {
        if(fromOrTo == null) {
            return true;
        }
        if(LIMITNUM_未指定 == fromOrTo) {
            return true;
        }
        return false;
    }
    public boolean isLimitnum指定なし() {
        return limitnum == null || LIMITNUM_未指定 == limitnum;
    }

    public static void main(String[] args) {
        Org org = new Org();
        System.out.println(org.getFromTodate_Disp());
        org.setFromdate(-1);
        System.out.println(org.getFromTodate_Disp());
        org.setTodate(-1);
        System.out.println(org.getFromTodate_Disp());
        org.setFromdate(20150101);
        System.out.println(org.getFromTodate_Disp());
        org.setTodate(20151212);
        System.out.println(org.getFromTodate_Disp());
        
    }

    /* -- 以下、自動生成 --*/
    
//    public Integer getId() {
//        return id;
//    }
//    public void setId(Integer id) {
//        this.id = id;
//    }
//    public Integer getUpdatedate() {
//        return updatedate;
//    }
//    public void setUpdatedate(Integer updatedate) {
//        this.updatedate = updatedate;
//    }
//    public Integer getDeleted() {
//        return deleted;
//    }
//    public void setDeleted(Integer deleted) {
//        this.deleted = deleted;
//    }
    public Integer getOrgid() {
        return orgid;
    }
    public void setOrgid(Integer orgid) {
        this.orgid = orgid;
    }
    public Integer getKind() {
        return kind;
    }
    public void setKind(Integer kind) {
        this.kind = kind;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAdminname() {
        return adminname;
    }
    public void setAdminname(String adminname) {
        this.adminname = adminname;
    }
    public String getAdminnamekana() {
        return adminnamekana;
    }
    public void setAdminnamekana(String adminnamekana) {
        this.adminnamekana = adminnamekana;
    }
    public String getPostnum() {
        return postnum;
    }
    public void setPostnum(String postnum) {
        this.postnum = postnum;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getTelnum() {
        return telnum;
    }
    public void setTelnum(String telnum) {
        this.telnum = telnum;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public Integer getFromdate() {
        return fromdate;
    }
    public void setFromdate(Integer fromdate) {
        this.fromdate = fromdate;
    }
    public Integer getTodate() {
        return todate;
    }
    public void setTodate(Integer todate) {
        this.todate = todate;
    }

    public Long getEntrydate() {
        return entrydate;
    }
    public void setEntrydate(Long entrydate) {
        this.entrydate = entrydate;
    }
    public Long getApprovaldate() {
        return approvaldate;
    }
    public void setApprovaldate(Long approvaldate) {
        this.approvaldate = approvaldate;
    }
    public Long getRejectdate() {
        return rejectdate;
    }
    public void setRejectdate(Long rejectdate) {
        this.rejectdate = rejectdate;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
    public Long getJoindate() {
        return joindate;
    }
    public void setJoindate(Long joindate) {
        this.joindate = joindate;
    }
    public Integer getLimitnum() {
        return limitnum;
    }
    public void setLimitnum(Integer limitnum) {
        this.limitnum = limitnum;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }


}
