package com.ym.mec.util.idcard;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.ym.mec.util.exception.UtilException;

public class IdcardInfoExtractor {
	// 省份
	private String province;

	private String provinceCode;

	// 城市
	private String cityCode;

	private String city;

	// 区县
	private String regionCode;

	private String region;

	// 性别(1,男 0,女)
	private int gender;

	// 出生日期
	private Date birthday;

	private static Properties idCardCodeTable;

	static {
		if (idCardCodeTable == null) {
			idCardCodeTable = new Properties();
		}
		try {
			idCardCodeTable.load(IdcardInfoExtractor.class.getClassLoader().getResourceAsStream("idcard/idcardCodeTable.properties"));
		} catch (IOException e) {
			throw new UtilException("银行卡信息查询接口异常", e);
		}
	}

	private IdcardValidator validator = null;

	/**  
	 * 通过构造方法初始化各个成员属性  
	 */
	public IdcardInfoExtractor(String idcard, boolean isCheck) {
		validator = new IdcardValidator();
		if (isCheck) {
			if (validator.isValidatedAllIdcard(idcard) == false) {
				return;
			}
		}
		if (idcard.length() == 15) {
			idcard = validator.convertIdcarBy15bit(idcard);
		}
		// 获取省份
		provinceCode = idcard.substring(0, 2) + "0000";
		province = idCardCodeTable.getProperty(provinceCode);

		cityCode = idcard.substring(0, 4) + "00";
		city = idCardCodeTable.getProperty(cityCode);

		regionCode = idcard.substring(0, 6);
		region = idCardCodeTable.getProperty(regionCode);

		// 获取性别
		String id17 = idcard.substring(16, 17);
		if (Integer.parseInt(id17) % 2 == 0) {
			this.gender = 0;
		} else {
			this.gender = 1;
		}

		// 获取出生日期
		String birthday = idcard.substring(6, 14);
		Date birthdate = null;
		try {
			birthdate = new SimpleDateFormat("yyyyMMdd").parse(birthday);
		} catch (ParseException e) {
			throw new RuntimeException("身份证信息错误");
		}
		this.birthday = birthdate;

	}

	/**  
	 * @return the province  
	 */
	public String getProvince() {
		return province;
	}

	public String getProvinceCode() {
		return provinceCode;
	}

	public String getCityCode() {
		return cityCode;
	}

	public String getRegionCode() {
		return regionCode;
	}

	public int getGender() {
		return gender;
	}

	/**  
	 * @return the birthday  
	 */
	public Date getBirthday() {
		return birthday;
	}

	public String getCity() {
		return city;
	}

	public String getRegion() {
		return region;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public static void main(String[] args) {
		IdcardInfoExtractor extractor = new IdcardInfoExtractor("421125198708123013", true);
		System.out.println(extractor);
	}

}
