package com.cku.oa.statistics.service;

import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cku.oa.finance.cab.dao.CABFinanceStatisticsDao;
import com.cku.oa.finance.dao.PaymentChargingItemDao;
import com.cku.oa.finance.dao.PaymentOrderDetailDao;
import com.cku.oa.finance.dao.PaymentRecordDao;
import com.cku.oa.finance.dao.statistics.FinanceStatisticsDao;
import com.cku.oa.finance.entity.PaymentChargingItem;
import com.cku.oa.finance.entity.PaymentOrderDetail;
import com.cku.oa.finance.entity.PaymentRecord;
import com.cku.oa.finance.service.PaymentChargingItemService;
import com.cku.oa.finance.service.PaymentOrderService;
import com.cku.oa.kennel.service.KennelService;
import com.cku.oa.statistics.dao.SaPaymentDetailDao;
import com.cku.oa.statistics.entity.SaPaymentDetail;
import com.cku.oa.sys.dao.OrgDao;
import com.cku.oa.sys.entity.Org;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.service.user.MemberService;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

/**
 * 年费拆分为月费的核心方法
 * @author fanhuibin
 * @version 2017-02-21
 */
@Service
@Transactional(readOnly = true,propagation=Propagation.NEVER)
public class SaPaymentDetailService extends CrudService<SaPaymentDetailDao, SaPaymentDetail> {
	@Autowired
	private PaymentOrderService paymentOrderService;
	@Autowired
	private PaymentOrderDetailDao paymentOrderDetailDao;
	@Autowired
	private PaymentRecordDao paymentRecordDao;
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private KennelService kennelService;
	@Autowired
	private FinanceStatisticsDao financeStatisticsDao;
	@Autowired
	private CABFinanceStatisticsDao cabFinanceStatisticsDao;
	@Autowired
	private DictService dictService;
	@Autowired
	private PaymentChargingItemDao paymentChargingItemDao;


	private static String MEMBER_BASIC_CHARGE_ID = "1";
	private static String MEMBER_PRO_CHARGE_ID = "3";
	private static String KENNEL_CHARGE_ID = "6";
	private static String KENNEL_TEN_CHARGE_ID = "7"; //永久犬舍
	private static String KENNEL_STAR_CHARGE_ID = "63";//犬舍联展
	private static String KENNEL_STAR_CHARGE_2017_ID = "1111";//2017年犬舍联展
	private static String GROOMER_RESERVE_CHARGE_ID = "105"; //预备美容师会员费
	private static String GROOMER_FORMAL_CHARGE_ID = "106"; //正式美容师会员费
	private static String ORG_GROOMER_ID = "27";//美容培训单位合作年费（单项）
	private static String ORG_TRAIN_SINGLE_ID = "102";//培训单位合作年费（单项）
	private static String ORG_TRAIN_ID = "103";//培训单位合作年费（多项）
	private static String ORG_CLUB_ID = "200";//地方俱乐部
	private static String SHOW_BJ_ZB = "45"; //参赛费，北京自办
	private static String SHOW_CQ_HB = "220";//参赛费，重庆合办
	private static String SHOW_HZ_HB = "142";//参赛费，杭州合办

	private static String CAB_MEMBER_BASIC_CHARGE_ID = "cab4";
	private static BigDecimal CAB_MEMBER_BASIC_CHARGE_PRICE = new BigDecimal("90");

	private static String CAB_MEMBER_PRO_CHARGE_ID = "cab7";
	private static BigDecimal CAB_MEMBER_PRO_CHARGE_PRICE = new BigDecimal("330");

	private static String CAB_KENNEL_CHARGE_ID = "cab9";
	private static BigDecimal CAB_KENNEL_CHARGE_PRICE = new BigDecimal("480");

	private static String CAB_KENNEL_TEN_CHARGE_ID = "cab10";
	private static BigDecimal CAB_KENNEL_TEN_CHARGE_PRICE = new BigDecimal("3300");


	private static String CAB_GROOMER_RESERVE_CHARGE_ID = "cab74";
	private static BigDecimal CAB_GROOMER_RESERVE_CHARGE_PRICE = new BigDecimal("120");

	private static String CAB_GROOMER_FORMAL_CHARGE_ID = "cab75";
	private static BigDecimal CAB_GROOMER_FORMAL_CHARGE_PRICE = new BigDecimal("360");

	private static String CAB_ORG_GROOMER_ID = "cab80";
	private static BigDecimal CAB_ORG_GROOMER_PRICE = new BigDecimal("2400");

	private static String CAB_ORG_TRAIN_SINGLE_ID = "cab97";
	private static BigDecimal CAB_ORG_TRAIN_SINGLE_PRICE = new BigDecimal("1200");

	private static String CAB_ORG_TRAIN_ID = "cab98";
	private static BigDecimal CAB_ORG_TRAIN_PRICE = new BigDecimal("2000");

	private static List<SaPaymentDetail> batchRecord = new ArrayList<SaPaymentDetail>(1000);

	private static String PAYMENT_TYPE_CAB = "cab";
	private static String PAYMENT_TYPE_CKU = "cku";
	private static String PAYMENT_TYPE_ORIGINAL = "original";
	private static String PAYMENT_TYPE_FINE_CAB = "cab_fine";
	private static String PAYMENT_TYPE_FINE_CKU = "cku_fine";


	public SaPaymentDetail get(String id) {
		return super.get(id);
	}

	public List<SaPaymentDetail> findList(SaPaymentDetail saPaymentDetail) {
		return super.findList(saPaymentDetail);
	}

	public Page<SaPaymentDetail> findPage(Page<SaPaymentDetail> page, SaPaymentDetail saPaymentDetail) {
		return super.findPage(page, saPaymentDetail);
	}

	public Page<SaPaymentDetail> findCsvPage(Page<SaPaymentDetail> page, SaPaymentDetail saPaymentDetail) {
		saPaymentDetail.setPage(page);
		page.setList(dao.findCsvList(saPaymentDetail));
		return page;
	}

	/**
	 * 保持方法
	 * @param saPaymentDetail
	 */
	public void save(SaPaymentDetail saPaymentDetail) {
		saPaymentDetail.preInsert();
		if(batchRecord.size() == 1000){
			batchRecord.add(saPaymentDetail);
			this.dao.batchInsert(batchRecord);
			batchRecord = new ArrayList<SaPaymentDetail>();
		}else{
			batchRecord.add(saPaymentDetail);
		}
	}

	/**
	 * 最后小于1000提交数据
	 */
	public void lastSave(){
		if(batchRecord.size() > 0){
			this.dao.batchInsert(batchRecord);
			batchRecord.clear();
		}
	}
	public void delete(SaPaymentDetail saPaymentDetail) {
		super.delete(saPaymentDetail);
	}

	/**
	 * 统计指定时间
	 * 分拆年费生成的费用统计
	 * @param startDate
	 * @param endDate
	 */
	public Map<String,List<Map>> statistics(String startDate, String endDate) {
		Map<String,List<Map>> result = new HashMap<String,List<Map>>();

		List<Map> cku = this.dao.statisticsByType(startDate, endDate, "cku");
		List<Map> cab = this.dao.statisticsByType(startDate, endDate, "cab");
		List<Map> cku_fine = this.dao.statisticsByType(startDate, endDate, "cku_fine");//cku罚款
		List<Map> cab_fine = this.dao.statisticsByType(startDate, endDate, "cab_fine");//宠爱王国罚款

		result.put("cku", cku);
		result.put("cab", cab);
		result.put("cku_fine", cku_fine);
		result.put("cab_fine", cab_fine);
		return result;
	}

	/**
	 * 统计指定时间
	 * 分拆年费生成的费用统计
	 * @param startDate
	 * @param endDate
	 */
	public Map<String,List<Map>> statisticsCsv(String startDate, String endDate) {
		Map<String,List<Map>> result = new HashMap<String,List<Map>>();

		List<Map> csv = this.dao.statisticsCsvByType(startDate, endDate, "csv");
		List<Map> cab = this.dao.statisticsCsvByType(startDate, endDate, "cab");

		result.put("csv", csv);
		result.put("cab", cab);
		return result;
	}

	public void initSplit(String startDate,String endDate,int year) {
		//拆分会员的年费
		initMemberAnnualFee(startDate,endDate,year);
		System.out.println("会员费拆分完毕");

		//拆分外籍会员的年费(目前为止，外籍会员没有缴纳年费)
		//initForeignAnnualFee(startDate,endDate);

		//拆分犬舍的年费
		initKennelAnnualFee(startDate,endDate,year);
		System.out.println("犬舍年费拆分完毕");

		//2017-09-22 永久年费暂不分期了
		//拆分永久犬舍费到10年
//		initTenYearKennelFee(startDate,endDate);
//		System.out.println("永久犬舍费用拆分完毕");

		//拆分美容师会员年费(预备会员+正式会员)
		initGroomerFee(startDate,endDate,year);
		System.out.println("美容师会员费拆分完毕");

		//拆分美容合作单位年费
		initOrgGroomer(startDate,endDate);
		System.out.println("美容合作机构的年费拆分完毕");

		//拆分培训单项合作单位年费
		initOrgTrainSingle(startDate,endDate);
		System.out.println("培训合作单位 单项合作年费拆分完毕");

		//拆分培训多项合作单位年费
		initOrgTrain(startDate,endDate);
		System.out.println("培训合作单位多项拆分完毕");

		//拆分地方俱乐部合作单位年费
		//initOrgClub(startDate,endDate);

		//拆分星级犬舍联盟年费
		//initStarFee(startDate,endDate);

		//查询指定时间段的所有非年费类的费用，直接拆分到新的收费项上。
		try {
			initOther(startDate,endDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("拆分其他费用完成");

		//处理结束，如果有未提交的数据，要提交
		if(batchRecord.size() > 0){
			this.dao.batchInsert(batchRecord);
			batchRecord = new ArrayList<SaPaymentDetail>();
		}

		System.out.println("全部拆分结束");
	}


	public void exportBalance() throws SQLException{
		List<Member> members = memberService.findList(new Member());

	    String driver = "com.mysql.jdbc.Driver";
	    String url = "jdbc:mysql://192.168.18.152:3306/ckuoa_20171204?useUnicode=true&characterEncoding=utf-8";
	    String username = "root";
	    String password = "123456";
	    Connection conn = null;
	    try {
	        Class.forName(driver); //classLoader,加载对应驱动
	        conn = (Connection) DriverManager.getConnection(url, username, password);
	    } catch (ClassNotFoundException e) {
	        e.printStackTrace();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }

	    Map<String,BigDecimal> xiaofei = new HashMap<String,BigDecimal>();
	    Map<String,BigDecimal> chongzhi = new HashMap<String,BigDecimal>();
		String sql = "select * from payment_record where payment_time >= '2017-01-01 00:00:00' ";
		PreparedStatement pstmt = (PreparedStatement)conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()){
        	String memberCode = rs.getString("member_code");
        	String amount = rs.getString("payment_amount");
        	String paymentWay = rs.getString("payment_way");
        	String chargingItemId = rs.getString("charging_item_id");
        	if(paymentWay != null && (paymentWay.equals("cku.org")
        			||paymentWay.equals("25"))
        			){
        		BigDecimal big = new BigDecimal("0");
        		if(xiaofei.containsKey(memberCode)){
        			big = xiaofei.get(memberCode);
        		}
        		big = big.add(new BigDecimal(amount));
        		xiaofei.put(memberCode, big);
        	}

        	if(chargingItemId.equals("0")){
        		BigDecimal big = new BigDecimal("0");
        		if(chongzhi.containsKey(memberCode)){
        			big = chongzhi.get(memberCode);
        		}
        		big = big.add(new BigDecimal(amount));
        		chongzhi.put(memberCode, big);
        	}

        }

		// 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFSheet uc = wb.createSheet("用户消费充值统计");
    	HSSFCellStyle style = wb.createCellStyle();
    	style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

    	HSSFRow row = uc.createRow((int) 0);
    	HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("会员号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("余额");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("充值");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("消费");
        cell.setCellStyle(style);

        int j = 0;
        for(Member member:members){
        	if(chongzhi.containsKey(member.getMemberCode())||xiaofei.containsKey(member.getMemberCode())||Double.valueOf(member.getAccountBalance())>0){
        		row = uc.createRow((int) j + 1);
                row.createCell((short) 0).setCellValue(member.getMemberCode());
                row.createCell((short) 1).setCellValue(member.getAccountBalance());
                row.createCell((short)2).setCellValue(chongzhi.get(member.getMemberCode())==null?"0":chongzhi.get(member.getMemberCode()).toString());
                row.createCell((short)3).setCellValue(xiaofei.get(member.getMemberCode())==null?"0":xiaofei.get(member.getMemberCode()).toString());
        		j++;
        	}
        }

        // 第六步，将文件存到指定位置
        try
        {
            FileOutputStream fout = new FileOutputStream("E:/会员余额计算.xls");
            wb.write(fout);
            fout.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
	}

	public void exportExcel(String startDate,String endDate) throws ParseException{
		//查询到需要拆分的订单
		List<Map> orderList = financeStatisticsDao.orderAllList(null, null, null, null, null, null, null, null, "2", startDate, endDate);

		List<PaymentRecord> insertRecord = paymentRecordDao.findRecordByChargeItem("0", startDate, endDate);

		//查询所有的只有流水没有订单的记录
		List<PaymentRecord> recordList = paymentRecordDao.findRecordByOaCharge(startDate, endDate);
		PaymentChargingItem p = new PaymentChargingItem();
		List<PaymentChargingItem> items = paymentChargingItemDao.findAllList(p);

		// 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        for(int k=0;k<12;k++){
        	HSSFSheet uc = wb.createSheet((k+1)+"月");
        	HSSFCellStyle style = wb.createCellStyle();
        	style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        	HSSFRow row = uc.createRow((int) 0);
        	HSSFCell cell = row.createCell((short) 0);
            cell.setCellValue("会员号");
            cell.setCellStyle(style);
            cell = row.createCell((short) 1);
            cell.setCellValue("收费项");
            cell.setCellStyle(style);
            cell = row.createCell((short) 2);
            cell.setCellValue("单价");
            cell.setCellStyle(style);
            cell = row.createCell((short) 3);
            cell.setCellValue("数量");
            cell.setCellStyle(style);
            cell = row.createCell((short) 4);
            cell.setCellValue("金额");
            cell.setCellStyle(style);
            cell = row.createCell((short) 5);
            cell.setCellValue("时间");
            cell.setCellStyle(style);
            cell = row.createCell((short) 6);
            cell.setCellValue("流水号");
            cell.setCellStyle(style);

            SimpleDateFormat format = new SimpleDateFormat("MM");
            int j = 0;
            for (int i = 0; i < orderList.size(); i++)
            {

                Map order = orderList.get(i);
                String chargingItemId = (String) order.get("charging_item_id");
    			BigDecimal countNum = new BigDecimal("1");
    			if(order.get("num") != null){
    				countNum = new BigDecimal((int)order.get("num"));
    			}

    			BigDecimal countFee = (BigDecimal)order.get("total_price");
    			String memberCode = (String)order.get("member_code");
    			Date addTime = ((Timestamp)order.get("add_time"));
    			String runningNum = (String)order.get("order_code");

    			String chargingItemName = "";
    			String price = "";
    			for(PaymentChargingItem item:items){
    				if(item.getId().equals(chargingItemId)){
    					chargingItemName = item.getName();
    					price = item.getPrice();
    					break;
    				}
    			}

    			if(Integer.valueOf(format.format(addTime)) == (k+1)){
	    			row = uc.createRow((int) j + 1);
	                row.createCell((short) 0).setCellValue(memberCode);
	                row.createCell((short) 1).setCellValue(chargingItemName);
	                row.createCell((short)2).setCellValue(price);
	                row.createCell((short) 3).setCellValue(String.valueOf(countNum));
	                cell = row.createCell((short) 4);
	                cell.setCellValue(countFee.toString());
	                row.createCell(5).setCellValue(DateUtils.formatDate(addTime,"yyyy-MM-dd HH:mm:ss"));
	                row.createCell(6).setCellValue(runningNum);
	                j++;
    			}
            }

            for(int i=0;i<recordList.size();i++){
            	PaymentRecord record = recordList.get(i);


    			String chargingItemName = "";
    			String price = "";
    			for(PaymentChargingItem item:items){
    				if(item.getId().equals(record.getChargingItemId())){
    					chargingItemName = item.getName();
    					price = item.getPrice();
    					break;
    				}
    			}

    			if(Integer.valueOf(format.format(record.getPaymentTime())) == (k+1)){
    				row = uc.createRow((int) j + 1);

	            	row.createCell((short) 0).setCellValue(record.getMemberCode());
	                row.createCell((short) 1).setCellValue(chargingItemName);
	                row.createCell((short)2).setCellValue(price);
	                row.createCell((short) 3).setCellValue(record.getChargingItemNum() == null?1:record.getChargingItemNum());
	                cell = row.createCell((short) 4);
	                cell.setCellValue(record.getPaymentAmount());
	                row.createCell(5).setCellValue(DateUtil.formatDate(record.getPaymentTime(),"yyyy-MM-dd HH:mm:ss"));
	                row.createCell(6).setCellValue(record.getRunningNumber());
    				j++;
    			}
            }

            for(int i=0;i<insertRecord.size();i++){
            	PaymentRecord pay = insertRecord.get(i);


            	String chargingItemName = "";
    			String price = "";
    			for(PaymentChargingItem item:items){
    				if(item.getId().equals(pay.getChargingItemId())){
    					chargingItemName = item.getName();
    					price = item.getPrice();
    					break;
    				}
    			}

    			if(Integer.valueOf(format.format(pay.getPaymentTime())) == (k+1)){
    				row = uc.createRow((int) j + 1);
    				row.createCell((short) 0).setCellValue(pay.getMemberCode());
                    row.createCell((short) 1).setCellValue(chargingItemName);
                    row.createCell((short)2).setCellValue(price);
                    row.createCell((short) 3).setCellValue(pay.getChargingItemNum()==null?1:pay.getChargingItemNum());
                    cell = row.createCell((short) 4);
                    cell.setCellValue(pay.getPaymentAmount());
                    row.createCell(5).setCellValue(DateUtils.formatDate(pay.getPaymentTime(), "yyyy-MM-dd HH:mm:ss"));
                    row.createCell(6).setCellValue(pay.getRunningNumber());
                    if(pay.getPaymentWay().equals("10")){
                    	row.createCell(7).setCellValue("别人余额转入");
        			}
                    j++;
    			}

            }

        }



        // 第六步，将文件存到指定位置
        try
        {
        	Date start = DateUtils.parseDate(startDate,"yyyy-MM-dd HH:mm:ss");
            FileOutputStream fout = new FileOutputStream("E:/"+DateUtils.formatDate(start, "yyyy-MM")+".xls");
            wb.write(fout);
            fout.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

	}

	/**
	 * 查询指定时间内的所有用户消费，
	 * 并且拆分为SaPaymentDetail对象
	 * @param startDate
	 * @param endDate
	 * @throws ParseException
	 */
	private void initOther(String startDate,String endDate) throws ParseException{

		List<Map> chargeCABs = cabFinanceStatisticsDao.cabChargeItem();
		List<Map> chargeCKUs = cabFinanceStatisticsDao.ckuChargeItem();
		List<Map> relationShips = cabFinanceStatisticsDao.relationShip();

		//查询到需要拆分的订单
		List<Map> orderList = financeStatisticsDao.orderAllList(null, null, null, null, null, null, null, null, "2", startDate, endDate);

		//查询所有的只有流水没有订单的记录
		List<PaymentRecord> recordList = paymentRecordDao.findRecordByOaCharge(startDate, endDate);


		//拆分订单
		for(Map order:orderList){
			String chargingItemId = (String) order.get("charging_item_id");
			BigDecimal countNum = new BigDecimal("1");
			if(order.get("num") != null){
				countNum = new BigDecimal((int)order.get("num"));
			}

			BigDecimal countFee = (BigDecimal)order.get("total_price");
			String memberCode = (String)order.get("member_code");
			Date addTime = ((Timestamp)order.get("add_time"));
			String runningNum = (String)order.get("order_code");

			OriginalToSaDetail(chargeCABs, chargeCKUs, relationShips,
					chargingItemId, countNum, countFee, memberCode, addTime,
					runningNum);
		}

		//拆分流水
		for(PaymentRecord record:recordList){

			try{
			int num = record.getChargingItemNum()==null?1:record.getChargingItemNum();
			OriginalToSaDetail(chargeCABs, chargeCKUs, relationShips,record.getChargingItemId(),
					new BigDecimal(num),new BigDecimal(record.getPaymentAmount()),record.getMemberCode(),record.getPaymentTime(),record.getRunningNumber());
			}catch(Exception e){
				e.printStackTrace();

			}
			}
	}

	private void OriginalToSaDetail(List<Map> chargeCABs, List<Map> chargeCKUs,
			List<Map> relationShips, String chargingItemId,
			BigDecimal countNum, BigDecimal countFee, String memberCode,
			Date addTime, String runningNum) {
		for(Map relation:relationShips){
			String id = (String) relation.get("id");
			String cab = (String) relation.get("CAB");
			String cku = (String) relation.get("CKU");
			String dept = (String) relation.get("dept");

			//匹配成功
			if(id.equals(chargingItemId)){

				List<Map> list = new ArrayList<Map>();
				//将CKU的收费结果整理出来
				if(StringUtils.isNotEmpty(cku)){
					if(cku.contains(",")){
						String[] ckuArray = cku.split(",");
						for(String ckuCharge : ckuArray){
							Map map = new HashMap();
							map.put("type","cku" );
							map.put("id", ckuCharge);
							map.put("dept", dept);
							list.add(map);
						}
					}else{
						Map map = new HashMap();
						map.put("type", "cku");
						map.put("id", cku);
						map.put("dept", dept);
						list.add(map);
					}
				}

				//将CAB的收费结果整理出来
				if(StringUtils.isNotEmpty(cab)){
					if(cab.contains(",")){
						String[] cabArray = cab.split(",");
						for(String cabCharge : cabArray){
							Map map = new HashMap();
							map.put("type", "cab");
							map.put("id", cabCharge);
							map.put("dept", dept);
							list.add(map);
						}
					}else{
						Map map = new HashMap();
						map.put("type", "cab");
						map.put("id", cab);
						map.put("dept", dept);
						list.add(map);
					}
				}

				//赛事报名费（北京自办） 拆帐单独处理
				if(id.equals("45")){
					if(splitShow(countFee,memberCode,addTime,runningNum,"cab105","cab106","cku109")){
						//如果当前收费项被处理完成了，则跳过下面的逻辑
						continue;
					}
				}

				//赛事报名费（杭州自办） 拆帐单独处理
				if(id.equals("141")){
					if(splitShow(countFee,memberCode,addTime,runningNum,"cab107","cab108","cku109")){
						//如果当前收费项被处理完成了，则跳过下面的逻辑
						continue;
					}
				}

				//赛事报名费（重庆自办） 拆帐单独处理
				if(id.equals("219")){
					if(splitShow(countFee,memberCode,addTime,runningNum,"cab109","cab110","cku109")){
						//如果当前收费项被处理完成了，则跳过下面的逻辑
						continue;
					}
				}

				//赛事报名费（长春自办）拆分单独处理
				if(id.equals("221")){
					if(splitShow(countFee,memberCode,addTime,runningNum,"cab118","cab119","cku109")){
						continue;
					}
				}

				if(id.equals("177")){
					SaPaymentDetail saDetail = new SaPaymentDetail();
					saDetail.setPaymentNum(Integer.valueOf(countNum.toString()));
					saDetail.setMemberCode(memberCode);
					saDetail.setChargeDate(addTime);
					saDetail.setChargeItemId("cab65");
					saDetail.setRunningNumber(runningNum);
					saDetail.setPrice(countFee.toString());
					saDetail.setPaymentMoney(countFee.toString());
					saDetail.setType(PAYMENT_TYPE_CAB);
					this.save(saDetail);
					continue;
				}

				if(id.equals("189")){
					SaPaymentDetail saDetail = new SaPaymentDetail();
					saDetail.setPaymentNum(Integer.valueOf(countNum.toString()));
					saDetail.setMemberCode(memberCode);
					saDetail.setChargeDate(addTime);
					saDetail.setChargeItemId("cab66");
					saDetail.setPrice(countFee.toString());
					saDetail.setRunningNumber(runningNum);
					saDetail.setPaymentMoney(countFee.toString());
					saDetail.setType(PAYMENT_TYPE_CAB);
					this.save(saDetail);
					continue;
				}

				if(id.equals("234")){
					SaPaymentDetail saDetail = new SaPaymentDetail();
					saDetail.setPaymentNum(Integer.valueOf(countNum.toString()));
					saDetail.setMemberCode(memberCode);
					saDetail.setChargeDate(addTime);
					saDetail.setChargeItemId("cab67");
					saDetail.setPrice(countFee.toString());
					saDetail.setRunningNumber(runningNum);
					saDetail.setPaymentMoney(countFee.toString());
					saDetail.setType(PAYMENT_TYPE_CAB);
					this.save(saDetail);
					continue;
				}

				//分账功能
				BigDecimal totalMoney = new BigDecimal(0);
				for(int i=0;i<list.size();i++){
					Map map = list.get(i);
					String type = (String) map.get("type");
					String chargeId = (String) map.get("id");

					//封装数据
					SaPaymentDetail saDetail = new SaPaymentDetail();
					saDetail.setType(PAYMENT_TYPE_ORIGINAL);
					saDetail.setPaymentNum(Integer.valueOf(countNum.toString()));
					saDetail.setMemberCode(memberCode);
					saDetail.setChargeDate(addTime);
					saDetail.setChargeItemId(chargeId);
					saDetail.setRunningNumber(runningNum);

					if(list.size() == 1){
						//只有一个收费项，不需要分账
						if(type.equals("cku")){
							getChargeInfo(saDetail,countNum,countFee,dept,chargeCKUs,countFee,true,false);
						}else if(type.equals("cab")){
							getChargeInfo(saDetail,countNum,countFee,dept,chargeCABs,countFee,true,true);
						}
					}else{
						//有多个收费项，最后一个收费项的计算是减去前面的所有的收费
						BigDecimal remaining = countFee.subtract(totalMoney);
						if(i+1 == list.size()){

							if(type.equals("cku")){
								totalMoney = totalMoney.add(getChargeInfo(saDetail,countNum,countFee,dept,chargeCKUs,remaining,true,false));
							}else if(type.equals("cab")){
								totalMoney = totalMoney.add(getChargeInfo(saDetail,countNum,countFee,dept,chargeCABs,remaining,true,true));
							}
						}else{
							if(type.equals("cku")){
								totalMoney = totalMoney.add(getChargeInfo(saDetail,countNum,countFee,dept,chargeCKUs,remaining,false,false));
							}else if(type.equals("cab")){
								totalMoney = totalMoney.add(getChargeInfo(saDetail,countNum,countFee,dept,chargeCABs,remaining,false,true));
							}
						}
					}
				}
				break;
			}
		}
	}


	private boolean splitShow(BigDecimal countFee,String memberCode,Date addTime,String runningNumber,String charge280Id,String charge360Id,String chargeDaishouId) {
		boolean isSplitSucc = false;
		long feeLong = countFee.longValue();
		SaPaymentDetail sa280 = new SaPaymentDetail();
		sa280.setChargeDate(addTime);
		sa280.setChargeItemId(charge280Id);
		sa280.setMemberCode(memberCode);
		sa280.setPrice("280");
		sa280.setType("cab");
		sa280.setRunningNumber(runningNumber);

		SaPaymentDetail sa360 = new SaPaymentDetail();
		sa360.setChargeDate(addTime);
		sa360.setChargeItemId(charge360Id);
		sa360.setMemberCode(memberCode);
		sa360.setPrice("360");
		sa360.setType("cab");
		sa360.setRunningNumber(runningNumber);

		SaPaymentDetail chargeDaishou = new SaPaymentDetail();
		chargeDaishou.setChargeDate(addTime);
		chargeDaishou.setChargeItemId(chargeDaishouId);
		chargeDaishou.setMemberCode(memberCode);
		chargeDaishou.setPrice("20");
		chargeDaishou.setType("cku");
		chargeDaishou.setRunningNumber(runningNumber);


		if(feeLong!=0&&feeLong%280==0){
			int rate = (int) (feeLong/280);
			sa280.setPaymentMoney(""+rate*280);
			sa280.setPaymentMoney(""+rate*280);
			sa280.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%380==0){
			int rate = (int) (feeLong/380);
			sa360.setPaymentMoney(""+rate*360);
			sa360.setPaymentNum(rate);

			chargeDaishou.setPaymentMoney(""+rate*20);
			chargeDaishou.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%660==0){
			int rate = (int) (feeLong/660);

			sa280.setPaymentMoney(""+rate*280);
			sa280.setPaymentNum(rate);

			sa360.setPaymentMoney(""+rate*360);
			sa360.setPaymentNum(rate);

			chargeDaishou.setPaymentMoney(""+rate*20);
			chargeDaishou.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%940==0){
			int rate = (int) (feeLong/940);

			sa280.setPaymentMoney(""+(2*rate*280));
			sa280.setPaymentNum(2*rate);

			sa360.setPaymentMoney(""+rate*360);
			sa360.setPaymentNum(rate);

			chargeDaishou.setPaymentMoney(""+rate*20);
			chargeDaishou.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%1040==0){
			int rate = (int) (feeLong/1040);

			sa280.setPaymentMoney(""+(rate*280));
			sa280.setPaymentNum(rate);

			sa360.setPaymentMoney(""+2*rate*360);
			sa360.setPaymentNum(2*rate);

			chargeDaishou.setPaymentMoney(""+2*rate*20);
			chargeDaishou.setPaymentNum(2*rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%1220==0){
			int rate = (int) (feeLong/1220);

			sa280.setPaymentMoney(""+(3*rate*280));
			sa280.setPaymentNum(3*rate);

			sa360.setPaymentMoney(""+rate*360);
			sa360.setPaymentNum(rate);

			chargeDaishou.setPaymentMoney(""+rate*20);
			chargeDaishou.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%1420==0){
			int rate = (int) (feeLong/1420);

			sa280.setPaymentMoney(""+(rate*280));
			sa280.setPaymentNum(rate);

			sa360.setPaymentMoney(""+3*rate*360);
			sa360.setPaymentNum(3*rate);

			chargeDaishou.setPaymentMoney(""+3*rate*20);
			chargeDaishou.setPaymentNum(3*rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%1500==0){
			int rate = (int) (feeLong/1500);

			sa280.setPaymentMoney(""+(4*rate*280));
			sa280.setPaymentNum(4*rate);

			sa360.setPaymentMoney(""+rate*360);
			sa360.setPaymentNum(rate);

			chargeDaishou.setPaymentMoney(""+rate*20);
			chargeDaishou.setPaymentNum(rate);
			isSplitSucc = true;
		}else
		if(feeLong!=0&&feeLong%1800==0){
			int rate = (int) (feeLong/1800);

			sa280.setPaymentMoney(""+(rate*280));
			sa280.setPaymentNum(rate);

			sa360.setPaymentMoney(""+4*rate*360);
			sa360.setPaymentNum(4*rate);

			chargeDaishou.setPaymentMoney(""+4*rate*20);
			chargeDaishou.setPaymentNum(4*rate);
			isSplitSucc = true;
		}

		if(isSplitSucc){
			if(sa280.getPaymentNum()>0){
				this.save(sa280);
			}
			if(sa360.getPaymentNum()>0){
				this.save(sa360);
			}
			if(chargeDaishou.getPaymentNum()>0){
				this.save(chargeDaishou);
			}
		}

		return isSplitSucc;
	}

	/**
	 *
	 * @param oldCountNum 旧收费项的数量
	 * @param oldCountFee 旧收费项的总金额
	 * @param chargeInfoMap 新收费项的详情，分cku结合与cku集合
	 * @param remaining  当前收费项还剩余的未分配金额
	 * @return
	 */
	private BigDecimal getChargeInfo(SaPaymentDetail saDetail,BigDecimal oldCountNum,BigDecimal oldCountFee,String dept,List<Map> chargeInfoMap,BigDecimal remaining,boolean isLast,boolean isCab){
		//代码说明
		//realFee 实收金额， totalFee 应收金额，remaining  一个旧收费项被拆分为多个收费项，这个是拆分到当前收费项的时候还剩余的总金额
		//countFee  一个新收费项可能对应多个旧收费项，countFee为多个旧收费项的总合

		BigDecimal totalFee = new BigDecimal(0);
		BigDecimal fee = new BigDecimal(0);

		//封装其他收费项信息
		for(Map infoMap:chargeInfoMap){
			String infoId = (String) infoMap.get("id");
			if(infoId.equals(saDetail.getChargeItemId())){
				saDetail.setPrice((String)infoMap.get("price"));
				fee = new BigDecimal((String)infoMap.get("price"));
				if(isCab){
					saDetail.setType(PAYMENT_TYPE_CAB);
				}else{
					saDetail.setType(PAYMENT_TYPE_CKU);
				}

			}
		}


		totalFee = oldCountNum.multiply(fee);
		BigDecimal realFee = new BigDecimal(0);

		if(!isLast){
			if(totalFee.compareTo(remaining)>= 0){
				realFee = remaining;
			}else{
				realFee = totalFee;
			}
		}else{
			if(totalFee.compareTo(remaining)<0){
				//应收大于实收，多余的费用存放到扣费
				realFee = totalFee;
				BigDecimal reduceFee = remaining.subtract(totalFee);
				//addToExtreaFee(countNum,reduceFee,(String)map.get("dept"),resultMap);
				//添加到罚款里
				SaPaymentDetail extreaFee = new SaPaymentDetail();//扣款
				extreaFee.setChargeItemId(saDetail.getChargeItemId());
				extreaFee.setChargeDate(saDetail.getChargeDate());
				extreaFee.setMemberCode(saDetail.getMemberCode());
				extreaFee.setRunningNumber(saDetail.getRunningNumber());
				extreaFee.setPaymentNum(1);
				extreaFee.setPaymentMoney(reduceFee.toString());
				extreaFee.setPaymentTime(saDetail.getPaymentTime());
				extreaFee.setPrice("0");
				if(isCab){
					extreaFee.setType(PAYMENT_TYPE_FINE_CAB);
				}else{
					extreaFee.setType(PAYMENT_TYPE_FINE_CKU);
				}

				if(!(reduceFee.compareTo(new BigDecimal(0)) == 0)){
					this.save(extreaFee);
				}

			}else{
				realFee = remaining;
			}
		}

		saDetail.setPaymentMoney(realFee.toString());
		if(!(realFee.compareTo(new BigDecimal(0)) == 0)){

			//拆分的收费项，不能是需要拆分的年费
			//2017-09-22永久犬舍费不分期方案
			String chargeItem = saDetail.getChargeItemId();
			if(!(chargeItem.equals(CAB_GROOMER_FORMAL_CHARGE_ID)
					||chargeItem.equals(CAB_GROOMER_RESERVE_CHARGE_ID)
					||chargeItem.equals(CAB_KENNEL_CHARGE_ID)
					||chargeItem.equals(CAB_MEMBER_BASIC_CHARGE_ID)
					||chargeItem.equals(CAB_MEMBER_PRO_CHARGE_ID)
					||chargeItem.equals(CAB_KENNEL_TEN_CHARGE_ID)
					||chargeItem.equals(CAB_ORG_GROOMER_ID)
					||chargeItem.equals(CAB_ORG_TRAIN_ID)
					||chargeItem.equals(CAB_ORG_TRAIN_SINGLE_ID)))
			{
				this.save(saDetail);
			}
		}else{
			//拆分的收费项，不能是需要拆分的年费
			String chargeItem = saDetail.getChargeItemId();
			if(!(chargeItem.equals(CAB_GROOMER_FORMAL_CHARGE_ID)
					||chargeItem.equals(CAB_GROOMER_RESERVE_CHARGE_ID)
					||chargeItem.equals(CAB_KENNEL_CHARGE_ID)
					||chargeItem.equals(CAB_MEMBER_BASIC_CHARGE_ID)
					||chargeItem.equals(CAB_MEMBER_PRO_CHARGE_ID)
					||chargeItem.equals(CAB_KENNEL_TEN_CHARGE_ID)
					||chargeItem.equals(CAB_ORG_GROOMER_ID)
					||chargeItem.equals(CAB_ORG_TRAIN_ID)
					||chargeItem.equals(CAB_ORG_TRAIN_SINGLE_ID)))
			{
				saDetail.setPaymentMoney(""+saDetail.getPaymentNum()*Long.valueOf(saDetail.getPrice()));
				this.save(saDetail);
			}
		}
		return realFee;
	}

	private void initOrgClub(String startDate,String endDate){
		List<PaymentRecord> orgClubRecord = paymentRecordDao.findRecordByChargeItem(ORG_GROOMER_ID, startDate, endDate);
		List<PaymentOrderDetail> orgClubDetail = paymentOrderDetailDao.findDetailByChargeItem(ORG_GROOMER_ID, startDate, endDate);
		System.out.println("拆分前总记录数："+(orgClubRecord.size()+orgClubDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:orgClubRecord){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:orgClubDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			splitOnPaymentTime(maps.get(s),CAB_ORG_GROOMER_ID,CAB_ORG_GROOMER_PRICE);
		}
	}

	private void initOrgGroomer(String startDate,String endDate){
		List<PaymentRecord> orgGroomerRecord = paymentRecordDao.findRecordByChargeItem(ORG_GROOMER_ID, startDate, endDate);
		List<PaymentOrderDetail> orgGroomerDetail = paymentOrderDetailDao.findDetailByChargeItem(ORG_GROOMER_ID, startDate, endDate);
		System.out.println("拆分前总记录数："+(orgGroomerRecord.size()+orgGroomerDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:orgGroomerRecord){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:orgGroomerDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			splitOnPaymentTime(maps.get(s),CAB_ORG_GROOMER_ID,CAB_ORG_GROOMER_PRICE);
		}
	}

	private void initOrgTrain(String startDate,String endDate){
		List<PaymentRecord> orgTrainRecord = paymentRecordDao.findRecordByChargeItem(ORG_TRAIN_ID, startDate, endDate);
		List<PaymentOrderDetail> orgTrainDetail = paymentOrderDetailDao.findDetailByChargeItem(ORG_TRAIN_ID, startDate, endDate);
		System.out.println("拆分前总记录数："+(orgTrainRecord.size()+orgTrainDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:orgTrainRecord){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:orgTrainDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			splitOnPaymentTime(maps.get(s),CAB_ORG_TRAIN_ID,CAB_ORG_TRAIN_PRICE);
		}
	}

	private void initOrgTrainSingle(String startDate,String endDate){
		List<PaymentRecord> orgTrainSingleRecord = paymentRecordDao.findRecordByChargeItem(ORG_TRAIN_SINGLE_ID, startDate, endDate);
		List<PaymentOrderDetail> orgTrainSingleDetail = paymentOrderDetailDao.findDetailByChargeItem(ORG_TRAIN_SINGLE_ID, startDate, endDate);
		System.out.println("拆分前总记录数："+(orgTrainSingleRecord.size()+orgTrainSingleDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:orgTrainSingleRecord){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:orgTrainSingleDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			splitOnPaymentTime(maps.get(s),CAB_ORG_TRAIN_SINGLE_ID,CAB_ORG_TRAIN_SINGLE_PRICE);
		}
	}


	private void initGroomerFee(String startDate,String endDate,int year){
		List<PaymentRecord> reserveFee = paymentRecordDao.findRecordByChargeItem(GROOMER_RESERVE_CHARGE_ID, startDate, endDate);

		List<PaymentOrderDetail> reserveDetail = paymentOrderDetailDao.findDetailByChargeItem(GROOMER_RESERVE_CHARGE_ID, startDate, endDate);
		List<PaymentRecord> formalFee = paymentRecordDao.findRecordByChargeItem(GROOMER_FORMAL_CHARGE_ID, startDate, endDate);

		List<PaymentOrderDetail> formalDetail = paymentOrderDetailDao.findDetailByChargeItem(GROOMER_FORMAL_CHARGE_ID, startDate, endDate);

		System.out.println("拆分前总记录数："+(reserveFee.size()+reserveDetail.size()+formalFee.size()+formalDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:reserveFee){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:reserveDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentRecord paymentRecord:formalFee){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:formalDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			//判断用户的缴费是不是同时包含基础会员费与专业会员费。
			boolean isSingleFee = true;
			String firstChargeId = maps.get(s).get(0).getChargingItemId();
			List<PaymentRecord> paymentRecords = maps.get(s);
			for(PaymentRecord p:maps.get(s)){
				if(!firstChargeId.equals(p.getChargingItemId())){
					isSingleFee = false;
				}
			}


			if(isSingleFee){
				//如果会员缴费都是同一种费用，按照会员的截止时间，倒叙将年费分拆到各个月。
				//查询用户的截止时间
				Date groomerEndDate = null;
				try{
					groomerEndDate = memberService.getByMemberCode(s).getGroomerEndDate();
				}catch(Exception e){
					//默认为null,按照缴费日期计算
				}


				Calendar c = Calendar.getInstance();
				c.setTime(new Date());
				int currentYear = c.get(Calendar.YEAR);
				if(groomerEndDate == null){
					//按照缴费日期计算
					splitGroomerFeeOnPaymentTime(maps.get(s));
				}else if(groomerEndDate.getTime() > DateUtils.parseDate((currentYear+10)+"-01-01").getTime() || groomerEndDate.getTime()<DateUtils.parseDate("2015-01-01").getTime()){
					//时间过大，按照缴费日期计算
					splitGroomerFeeOnPaymentTime(maps.get(s));
				}else{
					//按照会员的截止时间推算开始时间，然后拆分
					Calendar beginC = Calendar.getInstance();
					beginC.setTime(groomerEndDate);
					beginC.add(beginC.YEAR, -maps.get(s).size());
					if(beginC.get(beginC.YEAR)<year){
						beginC.set(beginC.YEAR, year);
						beginC.set(beginC.MONTH, 1);
					}
					Date beginDate = beginC.getTime();
					splitGroomerFeeOnPaymentTime(maps.get(s));
				}
			}else{
				//如果会员缴费的内容包含俩种费用，基础会员费就按照缴费时间算
				List<PaymentRecord> reserve = new ArrayList<PaymentRecord>();
				List<PaymentRecord> formal = new ArrayList<PaymentRecord>();

				List<PaymentRecord> Fee = maps.get(s);
				Date upgradeToProDate = new Date();
				for(PaymentRecord p:Fee){
					if(p.getChargingItemId().equals(GROOMER_RESERVE_CHARGE_ID)){
						reserve.add(p);
					}

					if(p.getChargingItemId().equals(GROOMER_FORMAL_CHARGE_ID)){
						if(p.getPaymentTime().getTime()<upgradeToProDate.getTime()){
							upgradeToProDate = p.getPaymentTime();
						}
						formal.add(p);
					}
				}

				//基础会员直接按照缴费时间计算
				splitGroomerFeeOnPaymentTime(reserve);

				//专业会员费，按目前的会员截止时间倒推
				splitGroomerFeeOnPaymentTime(formal);
			}

		}
	}

//	/**
//	 * 拆分永久犬舍费
//	 * @param startDate
//	 * @param endDate
//	 */
//	private void initTenYearKennelFee(String startDate,String endDate){
//		List<PaymentRecord> kennelRecord = paymentRecordDao.findRecordByChargeItem(KENNEL_TEN_CHARGE_ID, startDate, endDate);
//		List<PaymentOrderDetail> kennelDetail = paymentOrderDetailDao.findDetailByChargeItem(KENNEL_TEN_CHARGE_ID, startDate, endDate);
//		System.out.println("拆分前总记录数："+(kennelRecord.size()+kennelDetail.size()));
//
//		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
//		for(PaymentRecord paymentRecord:kennelRecord){
//			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
//			if(maps.containsKey(paymentRecord.getMemberCode())){
//				list = maps.get(paymentRecord.getMemberCode());
//			}else{
//				maps.put(paymentRecord.getMemberCode(), list);
//			}
//
//			list.add(paymentRecord);
//		}
//
//		for(PaymentOrderDetail d:kennelDetail){
//			PaymentRecord paymentRecord = new PaymentRecord();
//			paymentRecord.setChargingItemId(d.getChargingItemId());
//			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
//			paymentRecord.setChargingItemNum(Integer.valueOf(count));
//			paymentRecord.setPaymentAmount(d.getPrice());
//			paymentRecord.setMemberCode(d.getMemberCode());
//			paymentRecord.setRunningNumber(d.getOrderCode());
//			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
//			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
//			if(maps.containsKey(paymentRecord.getMemberCode())){
//				list = maps.get(paymentRecord.getMemberCode());
//			}else{
//				maps.put(paymentRecord.getMemberCode(), list);
//			}
//
//			list.add(paymentRecord);
//		}
//
//		//将数据分拆，然后存起来
//		for(String s:maps.keySet()){
//			//永久费用拆分到10年
//			splitTenYearOnPaymentTime(maps.get(s),CAB_KENNEL_TEN_CHARGE_ID,CAB_KENNEL_TEN_CHARGE_PRICE);
//		}
//	}

	/**
	 * 拆分年度犬舍费
	 * @param startDate
	 * @param endDate
	 */
	private void initKennelAnnualFee(String startDate,String endDate,int year){
		List<PaymentRecord> kennelRecord = paymentRecordDao.findRecordByChargeItem(KENNEL_CHARGE_ID, startDate, endDate);
		List<PaymentOrderDetail> kennelDetail = paymentOrderDetailDao.findDetailByChargeItem(KENNEL_CHARGE_ID, startDate, endDate);
		System.out.println("拆分前总记录数："+(kennelRecord.size()+kennelDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();
		for(PaymentRecord paymentRecord:kennelRecord){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}
			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:kennelDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}
			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){

			//如果会员缴费都是同一种费用，按照会员的截止时间，倒叙将年费分拆到各个月。
			//查询用户的截止时间
			Date kennelEndDate = null;
			try{
				kennelEndDate = kennelService.getKennelByMemberCode(s).getEndTime();
			}catch(Exception e){
				//默认memberEndDate 为null,按照缴费日期计算
			}


			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			int currentYear = c.get(Calendar.YEAR);
			if(kennelEndDate == null){
				//按照缴费日期计算
				splitOnPaymentTime(maps.get(s),CAB_KENNEL_CHARGE_ID,CAB_KENNEL_CHARGE_PRICE);
			}else if(s.contains("HZ")){
				//合作机构都统一拆分到会员处理
				splitOnPaymentTime(maps.get(s),CAB_KENNEL_CHARGE_ID,CAB_KENNEL_CHARGE_PRICE);
			}
			else if(kennelEndDate.getTime() > DateUtils.parseDate((currentYear+10)+"-01-01").getTime() || kennelEndDate.getTime()<DateUtils.parseDate("2015-01-01").getTime()){
				//时间过大，按照缴费日期计算
				splitOnPaymentTime(maps.get(s),CAB_KENNEL_CHARGE_ID,CAB_KENNEL_CHARGE_PRICE);
			}else{
				//按照会员的截止时间推算开始时间，然后拆分
//				Calendar beginC = Calendar.getInstance();
//				beginC.setTime(kennelEndDate);
//				beginC.add(beginC.YEAR, -maps.get(s).size());
//				if(beginC.get(beginC.YEAR)<year){
//					beginC.set(beginC.YEAR, year);
//					beginC.set(beginC.MONTH, 1);
//				}
//				Date beginDate = beginC.getTime();

				splitOnPaymentTime(maps.get(s),CAB_KENNEL_CHARGE_ID,CAB_KENNEL_CHARGE_PRICE);
			}
		}
	}


//	/**
//	 * 年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
//	 * 这个方法通过指定一个初始的生效时间，以后每一年都是按照这个时间往后推一年。
//	 * @param list
//	 */
//	private void splitOn(List<PaymentRecord> list,Date ,String chargeItemId,BigDecimal price){
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTime();
//		for(int i=0;i<list.size();i++){
//			PaymentRecord pr = list.get(i);
//			splitYearToMonth(pr, calendar.getTime(), chargeItemId,price);
//			calendar.add(calendar.YEAR, 1);
//		}
//	}

//	/**
//	 * 10年的年费拆分到各月
//	 * 这个方法默认缴费日期就是年费的正式生效时间
//	 * @param list
//	 */
//	private void splitTenYearOnPaymentTime(List<PaymentRecord> list,String chargeItemId,BigDecimal price){
//		String memberCode = list.get(0).getMemberCode();
//		if(memberCode.contains("HZ")){
//			try {
//				changeHZToMember(list);
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}
//		}
//		for(PaymentRecord pr:list){
//			splitTenYearToMonth(pr, pr.getPaymentTime(), chargeItemId, price);
//		}
//	}

	/**
	 * 会员年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
	 * 这个方法默认缴费日期就是年费的正式生效时间
	 * @param list
	 */
	private void splitOnPaymentTime(List<PaymentRecord> list,String chargeItemId,BigDecimal price){
		String memberCode = list.get(0).getMemberCode();
		if(memberCode.contains("HZ")){
			try {
				changeHZToMember(list);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		for(PaymentRecord pr:list){
			splitYearToMonth(pr, pr.getPaymentTime(), chargeItemId, price);
		}
	}



	/**
	 * 拆分会员年费的入口
	 */
	private void initMemberAnnualFee(String startDate,String endDate,int year){
		//数据使用服务年费（一般用户） 直接扣费的
		List<PaymentRecord> normals = paymentRecordDao.findRecordByChargeItem(MEMBER_BASIC_CHARGE_ID, startDate, endDate);

		//数据使用服务年费（专业用户） 直接扣费的
		List<PaymentRecord> professional = paymentRecordDao.findRecordByChargeItem(MEMBER_PRO_CHARGE_ID, startDate, endDate);

		//数据库使用年费（一般用户） 订单的
		List<PaymentOrderDetail> normalDetail = paymentOrderDetailDao.findDetailByChargeItem(MEMBER_BASIC_CHARGE_ID, startDate, endDate);

		//数据库使用年费 （专业用户） 订单的
		List<PaymentOrderDetail> professionalDetail = paymentOrderDetailDao.findDetailByChargeItem(MEMBER_PRO_CHARGE_ID, startDate, endDate);

		System.out.println("年费拆分前总记录数："+(normals.size()+professional.size()+professionalDetail.size()+normalDetail.size()));

		Map<String,List<PaymentRecord>> maps = new HashMap<String,List<PaymentRecord>>();

		for(PaymentRecord paymentRecord:normals){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}


			list.add(paymentRecord);
		}

		for(PaymentRecord paymentRecord:professional){
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}

			list.add(paymentRecord);
		}

		for(PaymentOrderDetail d:normalDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			if(d.getPaymentOrder() == null){
				int i = 0;
			}
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}
			list.add(paymentRecord);


		}

		for(PaymentOrderDetail d:professionalDetail){
			PaymentRecord paymentRecord = new PaymentRecord();
			paymentRecord.setChargingItemId(d.getChargingItemId());
			String count = d.getChargingItemCount() == null?"0":d.getChargingItemCount();
			paymentRecord.setChargingItemNum(Integer.valueOf(count));
			paymentRecord.setPaymentAmount(d.getPrice());
			paymentRecord.setMemberCode(d.getMemberCode());
			paymentRecord.setRunningNumber(d.getOrderCode());
			paymentRecord.setPaymentTime(d.getPaymentOrder().getPaymentTime());
			List<PaymentRecord> list = new ArrayList<PaymentRecord>();
			if(maps.containsKey(paymentRecord.getMemberCode())){
				list = maps.get(paymentRecord.getMemberCode());
			}else{
				maps.put(paymentRecord.getMemberCode(), list);
			}
			list.add(paymentRecord);
		}

		//将数据分拆，然后存起来
		for(String s:maps.keySet()){
			//判断用户的缴费是不是同时包含基础会员费与专业会员费。
			boolean isSingleFee = true;
			String firstChargeId = maps.get(s).get(0).getChargingItemId();
			List<PaymentRecord> paymentRecords = maps.get(s);
			for(PaymentRecord p:maps.get(s)){
				if(!firstChargeId.equals(p.getChargingItemId())){
					isSingleFee = false;
				}
			}


			if(isSingleFee){
				//如果会员缴费都是同一种费用，按照会员的截止时间，倒叙将年费分拆到各个月。
				//查询用户的截止时间
				Date memberEndDate = null;
				try{
					memberEndDate = memberService.getByMemberCode(s).getMemberEndDate();
				}catch(Exception e){
					//默认memberEndDate 为null,按照缴费日期计算
				}


				Calendar c = Calendar.getInstance();
				c.setTime(new Date());
				int currentYear = c.get(Calendar.YEAR);
				if(memberEndDate == null){
					//按照缴费日期计算
					splitMemberFeeOnPaymentTime(maps.get(s));
				}else if(s.contains("HZ")){
					//合作机构都统一拆分到会员处理
					splitMemberFeeOnPaymentTime(maps.get(s));
				}
				else if(memberEndDate.getTime() > DateUtils.parseDate((currentYear+10)+"-01-01").getTime() || memberEndDate.getTime()<DateUtils.parseDate("2015-01-01").getTime()){
					//时间过大，按照缴费日期计算
					splitMemberFeeOnPaymentTime(maps.get(s));
				}else{
					//按照会员的截止时间推算开始时间，然后拆分
					Calendar beginC = Calendar.getInstance();
					beginC.setTime(memberEndDate);
					beginC.add(beginC.YEAR, -maps.get(s).size());
					if(beginC.get(beginC.YEAR)<year){
						beginC.set(beginC.YEAR, year);
						beginC.set(beginC.MONTH, 1);
					}
					Date beginDate = beginC.getTime();

					splitMemberFeeOnPaymentTime(maps.get(s));
				}
			}else{
				//如果会员缴费的内容包含俩种费用，基础会员费就按照缴费时间算
				List<PaymentRecord> basicFee = new ArrayList<PaymentRecord>();
				List<PaymentRecord> professionalFee = new ArrayList<PaymentRecord>();

				List<PaymentRecord> Fee = maps.get(s);
				Date upgradeToProDate = new Date();
				for(PaymentRecord p:Fee){
					if(p.getChargingItemId().equals(MEMBER_BASIC_CHARGE_ID)){
						basicFee.add(p);
					}

					if(p.getChargingItemId().equals(MEMBER_PRO_CHARGE_ID)){
						if(p.getPaymentTime().getTime()<upgradeToProDate.getTime()){
							upgradeToProDate = p.getPaymentTime();
						}
						professionalFee.add(p);
					}
				}

				//基础会员直接按照缴费时间计算
				splitMemberFeeOnPaymentTime(basicFee);

				//专业会员费，按目前的会员截止时间倒推
				splitMemberFeeOnPaymentTime(professionalFee);
			}

		}
	}

	/**
	 * 合作机构缴纳的年费需要分开到合作机构所管理的会员身上
	 * @param list
	 * @throws ParseException
	 */
	private void changeHZToMember(List<PaymentRecord> list) throws ParseException{
		String hzMemberCode = list.get(0).getMemberCode();
		Org org = new Org();
		org = orgDao.getALLOrgByMemberCode(hzMemberCode);
		Member member = new Member();
		try{
			member.setRegistrant(org.getUser().getLoginName());
		}catch(Exception e){
			e.printStackTrace();
		}
		List<Member> members = memberService.findList(member);

		//生成虚拟缴费记录
		//会员从2015年开始算，缴过几次费用，则分解成几条记录，
		List<PaymentRecord> virtuals = new ArrayList<PaymentRecord>();
		for(int i=0;i<members.size();i++){
			Date endDate = members.get(i).getMemberEndDate();
			Calendar calendar = Calendar.getInstance();
			if(endDate !=null){
				calendar.setTime(endDate);
				while(calendar.getTime().getTime()>DateUtils.parseDate("2016-01-01", "yyyy-MM-dd").getTime()){
					calendar.add(calendar.YEAR, -1);
					PaymentRecord payment = new PaymentRecord();
					payment.setMemberCode(members.get(i).getMemberCode());
					payment.setPaymentTime(calendar.getTime());
					payment.setDelFlag("0");
					virtuals.add(payment);
				}
			}
		}

		//将实际发生的缴费记录，与虚拟的缴费记录进行比较，

		f1:for(int i=0;i<list.size();i++){
			PaymentRecord real = list.get(i);
			Date paymentTime = real.getPaymentTime();
			paymentTime.setHours(0);
			paymentTime.setMinutes(0);
			paymentTime.setSeconds(0);
			long realTime = paymentTime.getTime();

			//第一步，相等
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差10天以内
				if(virtualTime==realTime&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}

			//第二步，将虚拟缴费日期比实际缴费日期早10天内 的 匹配成功
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差10天以内
				if(virtualTime>=realTime&&(virtualTime-realTime<=1000L*60*60*24*10)&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}

			//如果没有匹配到，第三步，将缴费日期比发生日期早30天的匹配成功
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差100天以内
				if(virtualTime>=realTime&&(virtualTime-realTime<=1000L*60*60*24*30)&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}

			//如果没有匹配到，第四步，将缴费日期比发生日期早100天的匹配成功
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差100天以内
				if(virtualTime>=realTime&&(virtualTime-realTime<=1000L*60*60*24*100)&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}

			//如果没有匹配到，第五步，将缴费日期比发生日期早365天的匹配成功
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差100天以内
				if(virtualTime>=realTime&&(virtualTime-realTime<=1000L*60*60*24*365)&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}

			//如果没有匹配到，不做任何限制，胡乱匹配吧
			for(PaymentRecord virtual:virtuals){
				long virtualTime  = virtual.getPaymentTime().getTime();
				//相差100天以内
				if(virtualTime>=realTime&&virtual.getDelFlag().equals("0")){
					real.setPaymentTime(virtual.getPaymentTime());
					real.setMemberCode(virtual.getMemberCode());
					virtual.setDelFlag("1");
					continue f1;
				}
			}


			System.out.println(real.getRunningNumber()+"数据处理不完善，有些数据还是无法处理");
		}
	}




//	/**
//	 * 会员年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
//	 * 这个方法通过指定一个初始的生效时间，以后每一年都是按照这个时间往后推一年。
//	 * @param list
//	 */
//	private void splitMemberFeeOn(List<PaymentRecord> list,Date ){
//
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTime();
//		for(int i=0;i<list.size();i++){
//			PaymentRecord pr = list.get(i);
//			if(pr.getChargingItemId().equals(MEMBER_BASIC_CHARGE_ID)){
//				splitYearToMonth(pr, calendar.getTime(), CAB_MEMBER_BASIC_CHARGE_ID, CAB_MEMBER_BASIC_CHARGE_PRICE);
//			}else{
//				splitYearToMonth(pr, calendar.getTime(), CAB_MEMBER_PRO_CHARGE_ID, CAB_MEMBER_PRO_CHARGE_PRICE);
//			}
//			calendar.add(calendar.YEAR, 1);
//		}
//	}

	/**
	 * 会员年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
	 * 这个方法默认缴费日期就是年费的正式生效时间
	 * @param list
	 */
	private void splitMemberFeeOnPaymentTime(List<PaymentRecord> list){
		String memberCode = list.get(0).getMemberCode();
		if(memberCode.contains("HZ")){
			try {
				changeHZToMember(list);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		for(PaymentRecord pr:list){
			if(pr.getChargingItemId().equals(MEMBER_BASIC_CHARGE_ID)){
				splitYearToMonth(pr, pr.getPaymentTime(), CAB_MEMBER_BASIC_CHARGE_ID, CAB_MEMBER_BASIC_CHARGE_PRICE);
			}else{
				splitYearToMonth(pr, pr.getPaymentTime(), CAB_MEMBER_PRO_CHARGE_ID, CAB_MEMBER_PRO_CHARGE_PRICE);
			}
		}
	}

//	/**
//	 * 美容师年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
//	 * 这个方法通过指定一个初始的生效时间，以后每一年都是按照这个时间往后推一年。
//	 * @param list
//	 */
//	private void splitGroomerFeeOn(List<PaymentRecord> list,Date ){
//
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTime();
//		for(int i=0;i<list.size();i++){
//			PaymentRecord pr = list.get(i);
//			if(pr.getChargingItemId().equals(GROOMER_RESERVE_CHARGE_ID)){
//				splitYearToMonth(pr, calendar.getTime(), CAB_GROOMER_RESERVE_CHARGE_ID, CAB_GROOMER_RESERVE_CHARGE_PRICE);
//			}else{
//				splitYearToMonth(pr, calendar.getTime(), CAB_GROOMER_FORMAL_CHARGE_ID, CAB_GROOMER_FORMAL_CHARGE_PRICE);
//			}
//			calendar.add(calendar.YEAR, 1);
//		}
//	}

	/**
	 * 美容师年费拆分到各个月是基于年费的正式生效时间的。（我在2014年缴费，可能是2016年的年费，那么就是2016年才生效）
	 * 这个方法默认缴费日期就是年费的正式生效时间
	 * @param list
	 */
	private void splitGroomerFeeOnPaymentTime(List<PaymentRecord> list){
		String memberCode = list.get(0).getMemberCode();
		for(PaymentRecord pr:list){
			if(pr.getChargingItemId().equals(GROOMER_RESERVE_CHARGE_ID)){
				splitYearToMonth(pr, pr.getPaymentTime(), CAB_GROOMER_RESERVE_CHARGE_ID, CAB_GROOMER_RESERVE_CHARGE_PRICE);
			}else{
				splitYearToMonth(pr, pr.getPaymentTime(), CAB_GROOMER_FORMAL_CHARGE_ID, CAB_GROOMER_FORMAL_CHARGE_PRICE);
			}
		}
	}

	/**
	 * 将一个收费记录，分拆到各个月份
	 * @param paymentRecord 要拆分的记录
	 * @param beginDate 生效的时间
	 * @param chargeItemId 新的收费项
	 * @param money 收费项的实际金额
	 */
	private void splitYearToMonth(PaymentRecord paymentRecord,Date beginDate,String chargeItemId,BigDecimal money){
		String paymentAmount = paymentRecord.getPaymentAmount();
		BigDecimal moneyPerMonth = new BigDecimal(0);
		BigDecimal moneyLastMonth = new BigDecimal(0);
		BigDecimal pricePerMonth = new BigDecimal(0);
		BigDecimal priceLastMonth = new BigDecimal(0);
		//实缴金额为0的不处理
		if(!paymentAmount.equals("0")){
			BigDecimal realMoney = new BigDecimal(paymentAmount);
			if(realMoney.compareTo(money) >= 0){
				moneyPerMonth = money.divide(new BigDecimal(12),2,BigDecimal.ROUND_HALF_UP);
				moneyLastMonth = money.subtract(new BigDecimal(11).multiply(moneyPerMonth));

				pricePerMonth = moneyPerMonth;
				priceLastMonth = moneyLastMonth;
			}else{
				moneyPerMonth = realMoney.divide(new BigDecimal(12),2,BigDecimal.ROUND_HALF_UP);
				moneyLastMonth = realMoney.subtract(new BigDecimal(11).multiply(moneyPerMonth));

				pricePerMonth = money.divide(new BigDecimal(12),2,BigDecimal.ROUND_HALF_UP);
				priceLastMonth = money.subtract(new BigDecimal(11).multiply(pricePerMonth));
			}

			Date paymentDate = (Date) beginDate.clone();
			beginDate.setHours(23);
			beginDate.setMinutes(0);
			beginDate.setSeconds(0);
			Calendar ca = Calendar.getInstance();
			ca.setTime(beginDate);

			//计算分期的起始时间
			Calendar tempCal = Calendar.getInstance();
			tempCal.setTime(beginDate);
			tempCal.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
			Date installmentBeginDate = tempCal.getTime();

			tempCal.add(tempCal.MONTH, 11);
			Date installmentEndDate = tempCal.getTime();


			//存入12个月中
			for(int i=0;i<12;i++){
				SaPaymentDetail sa = new SaPaymentDetail();
				sa.setChargeItemId(chargeItemId);
				if(i != 0){
					ca.add(ca.MONTH, 1);
				}
				ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
				sa.setChargeDate(ca.getTime());
				if(i == 11){
					sa.setPaymentMoney(moneyLastMonth.toString());//实收
					sa.setPrice(priceLastMonth.toString());//应收
				}else{
					sa.setPaymentMoney(moneyPerMonth.toString());
					sa.setPrice(pricePerMonth.toString());
				}
				sa.setType("cab");
				sa.setMemberCode(paymentRecord.getMemberCode());
				sa.setRunningNumber(paymentRecord.getRunningNumber());
				sa.setPaymentNum(1);
				sa.setPaymentTime(paymentDate);
				sa.setInstallmentBeginDate(installmentBeginDate);
				sa.setInstallmentEndDate(installmentEndDate);
				this.save(sa);
			}
		}
	}

//	/**
//	 * 将一个收费记录，分拆到各个月份
//	 * @param paymentRecord 要拆分的记录
//	 * @param beginDate 生效的时间
//	 * @param chargeItemId 新的收费项
//	 * @param money 收费项的实际金额
//	 */
//	private void splitTenYearToMonth(PaymentRecord paymentRecord,Date beginDate,String chargeItemId,BigDecimal money){
//		String paymentAmount = paymentRecord.getPaymentAmount();
//		BigDecimal moneyPerMonth = new BigDecimal(0);
//		BigDecimal moneyLastMonth = new BigDecimal(0);
//		BigDecimal pricePerMonth = new BigDecimal(0);
//		BigDecimal priceLastMonth = new BigDecimal(0);
//
//		//实缴金额为0的不处理
//		if(!paymentAmount.equals("0")){
//			BigDecimal realMoney = new BigDecimal(paymentAmount);
//			if(realMoney.compareTo(money) >= 0){
//				moneyPerMonth = money.divide(new BigDecimal(120),2,BigDecimal.ROUND_HALF_UP);
//				moneyLastMonth = money.subtract(new BigDecimal(119).multiply(moneyPerMonth));
//
//				pricePerMonth = moneyPerMonth;
//				priceLastMonth = moneyLastMonth;
//			}else{
//				moneyPerMonth = realMoney.divide(new BigDecimal(120),2,BigDecimal.ROUND_HALF_UP);
//				moneyLastMonth = realMoney.subtract(new BigDecimal(119).multiply(moneyPerMonth));
//
//				pricePerMonth = money.divide(new BigDecimal(120),2,BigDecimal.ROUND_HALF_UP);
//				priceLastMonth = money.subtract(new BigDecimal(119).multiply(pricePerMonth));;
//			}
//
//			Calendar ca = Calendar.getInstance();
//			beginDate.setHours(23);
//			beginDate.setMinutes(0);
//			beginDate.setSeconds(0);
//			ca.setTime(beginDate);
//
//			//存入12个月中
//			for(int i=0;i<120;i++){
//				SaPaymentDetail sa = new SaPaymentDetail();
//				sa.setChargeItemId(chargeItemId);
//				if(i!=0){
//				ca.add(ca.MONTH, 1);
//				}
//				ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
//				sa.setChargeDate(ca.getTime());
//				if(i == 119){
//					sa.setPaymentMoney(moneyLastMonth.toString());
//					sa.setPrice(priceLastMonth.toString());
//				}else{
//					sa.setPaymentMoney(moneyPerMonth.toString());
//					sa.setPrice(pricePerMonth.toString());
//				}
//				sa.setType("cab");
//				sa.setMemberCode(paymentRecord.getMemberCode());
//				sa.setRunningNumber(paymentRecord.getRunningNumber());
//				sa.setPaymentNum(1);
//				this.save(sa);
//			}
//		}
//	}
}