package com.ssj.service.sys.fx.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;

import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantSign;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibJoinConsume;
import com.ssj.dao.sys.fx.dao.FxQueryDao;
import com.ssj.dao.sys.fx.dao.MerchantSignDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.fx.service.MerchantSignService;
import com.ssj.service.weixin.library.service.ILibJoinConsumeService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;


@Service
public class MerchantSignServiceImpl2 extends BaseServiceImpl<MerchantSign, String> implements MerchantSignService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private MerchantSignDao dao;
	
    @Autowired
    private FxQueryDao queryDao;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private ILibJoinService libJoinService;
	
	@Autowired
	private ILibJoinConsumeService libJoinConsumeService;
	
	@Autowired
	private LibVipServiceService libVipServiceService;
	
    @Override
    public PagingAndSortingRepository<MerchantSign, String> getDao() {
        return dao;
    }

    //12点定时任务，处理套餐的数据
    //1：处理加油包过期的数据
    
    //2：处理激活日期的数据，生成一条0的激活数据，设置下一个结算日，CurIsSummary=0，免费结算
    //注：如果在激活日期之前的时间，也会生成一条0的激活数据，设置下一个结算日，CurIsSummary=0，免费结算
    
    //3：处理激活日期的下一结算日数据，再生成一条0的结算数据，CurIsSummary=0的，设置下一个结算时间。
    //注：设置当前的时间
    
    //4：处理开始计费日期，生成一条真实的数据30，设置当前的时间， 设置下一个结算日，CurIsSummary=+1，真实开始结算。
    
    
    //5：处理开始计费日期的下一个结算日，生成一条30的数据，如果当前的CurIsSummary>=LibServiceMonth证明，结算完成，把结算日期都设置为空。
    //注：处理商户主套餐过期的数据,加油包全过期。
    
    @Override
	public void runMerchantSignByEndTime() {
    	try {
	    	//1：处理加油包过期的数据
			List<MerchantSign> merchantSigns=dao.findMerchantSignByEndTime();
			for (MerchantSign merchantSign : merchantSigns) {
				try {
					merchantSign.setRemarks("加油包失效【加油包过期】");
					merchantSign.setStatus(1);
					merchantSign.setUpdateTime(new Date());
					this.save(merchantSign);
					
					Merchant merchant = merchantService.getById(merchantSign.getMerchantId());
					merchant.setLibService(merchant.getLibService()-merchantSign.getLibService());
					merchantService.save(merchant);
		
					//同步商户表与机构表
					this.syncMerchantByLibJoin(merchant);
					
					//记录加油包记录
					TbLibJoinConsume consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchantSign.getLibService());
					consume.setPlatformService(0);
					consume.setType(11);
					consume.setComputeNum(merchantSign.getNum());
					consume.setSignType(merchant.getSignType());
					consume.setRemarks("加油包失效【加油包过期】");
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);
					
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					//调用openApi接口
					libVipServiceService.openApiServiceCRM(
							1,
							merchant.getLibId(), 
							merchant.getSignType(),
							merchant.getMealType(),
							merchant.getLibService(),
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getComputeTime()!=null ? format.format(merchant.getComputeTime()) : format.format(merchant.getActiveTime()),
							merchant.getComputeTime()!=null ? 
									format.format(DateHelper.getMonthDate(merchant.getComputeTime(),merchant.getLibServiceMonth())) : 
										format.format(DateHelper.getMonthDate(merchant.getActiveTime(),merchant.getLibServiceMonth())));
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("1：处理加油包过期数据，异常："+e.getMessage());
				}
			}
			
			//1.1：处理加油包激活的数据
			List<MerchantSign> merchantStartSigns=dao.findMerchantSignByStartTime();
			for (MerchantSign merchantSign : merchantStartSigns) {
				try {
					merchantSign.setStatus(0);
					merchantSign.setUpdateTime(new Date());
					this.save(merchantSign);
					
					Merchant merchant = merchantService.getById(merchantSign.getMerchantId());
					merchant.setLibService(merchant.getLibService()+merchantSign.getLibService());
					merchantService.save(merchant);
					
					//记录加油包记录
					TbLibJoinConsume consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchantSign.getLibService());
					consume.setPlatformService(0);
					consume.setType(10);
					consume.setComputeNum(merchantSign.getNum());
					consume.setSignType(merchant.getSignType());
					if(merchantSign.getSignType().equals(4)) {
						consume.setRemarks("加油包开通【新模式月包】");
					}else {
						consume.setRemarks("加油包开通【新模式量包】");
					}
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);
					
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					//调用openApi接口
					libVipServiceService.openApiServiceCRM(
							1,
							merchant.getLibId(), 
							merchant.getSignType(),
							merchant.getMealType(),
							merchant.getLibService(),
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getComputeTime()!=null ? format.format(merchant.getComputeTime()) : format.format(merchant.getActiveTime()),
							merchant.getComputeTime()!=null ? 
									format.format(DateHelper.getMonthDate(merchant.getComputeTime(),merchant.getLibServiceMonth())) : 
										format.format(DateHelper.getMonthDate(merchant.getActiveTime(),merchant.getLibServiceMonth()))
										);
					
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("1：处理加油包激活数据，异常："+e.getMessage());
				}
			}
			
			
			//2：处理激活日期的数据，生成一条0的激活数据，设置下一个结算日，CurIsSummary=0，免费结算
		    //注：如果在激活日期之前的时间，也会生成一条0的激活数据，设置下一个结算日，CurIsSummary=0，免费结算
			List<Merchant> activeMerchants=merchantService.findMerchantSignByActiveTime();
			for (Merchant merchant : activeMerchants) {
				try {
					//如果开始计费时间为null，就不处理
					if(merchant.getComputeTime()==null) {
						continue;
					}
					
					merchant.setCurIsSummary(0);
					merchant.setCurSummaryTime(new Date());
					merchant.setNextSummaryTime(DateHelper.getMonthDate(merchant.getCurSummaryTime(),1));
					merchantService.save(merchant);
					
					//记录
					TbLibJoinConsume consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchant.getLibService());
					consume.setPlatformService(0);
					consume.setType(7);
					consume.setComputeNum(merchant.getCurIsSummary());
					consume.setSignType(merchant.getSignType());
					consume.setRemarks("激活期扣费【服务包扣费】");
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);
					
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("2：处理商户系统激活日期数据，异常："+e.getMessage());
				}
			}
			
			
			
			//3：处理激活日期的数据，设置下一个结算日，CurIsSummary=1
		    //注：如果在激活日期之前的时间，设置下一个结算日，CurIsSummary=1
			for (Merchant merchant : activeMerchants) {
				try {
					
					if(merchant.getComputeTime()==null) {
						merchant.setCurIsSummary(1);
						merchant.setCurSummaryTime(new Date());
						merchant.setNextSummaryTime(DateHelper.getMonthDate(merchant.getCurSummaryTime(),1));
						merchantService.save(merchant);
						
						//记录
						TbLibJoinConsume consume=new TbLibJoinConsume();
						consume.setFromLibId(merchant.getLibId());
						consume.setFromMerchantId(merchant.getId());
						consume.setLibService(merchant.getLibService());
						consume.setPlatformService(0);
						consume.setType(7);
						consume.setComputeNum(merchant.getCurIsSummary());
						consume.setSignType(merchant.getSignType());
						consume.setRemarks("激活期扣费【服务包扣费】");
						consume.setCreateTime(new Date());
						libJoinConsumeService.save(consume);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("3：处理商户系统激活日期数据，异常："+e.getMessage());
				}
			}
			
			
			
			//4：处理激活日期的下一结算日数据，再生成一条0的结算数据，CurIsSummary=0的，设置下一个结算时间。
		    //注：设置当前的时间
			List<Merchant> activeEndMerchants=merchantService.findMerchantSignBySummaryTime();
			for (Merchant merchant : activeEndMerchants) {
				
				//如果开始计费时间为null，就不处理
				if(merchant.getComputeTime()==null) {
					continue;
				}
				
				//只有在激活期的商户才处理数据。
				if(merchant.getCurIsSummary()==null || merchant.getCurIsSummary()==0) {
					try {
						//如果当前日期还是小于开始计费日期，再生一条激活的记录
						if(merchant.getComputeTime().getTime()>new Date().getTime()) {
							
							merchant.setCurIsSummary(0);
							merchant.setCurSummaryTime(new Date());
							merchant.setNextSummaryTime(DateHelper.getMonthDate(merchant.getCurSummaryTime(),1));
							merchantService.save(merchant);
							
							//生成激活期的免费失效记录。
							TbLibJoinConsume consume=new TbLibJoinConsume();
							consume.setFromLibId(merchant.getLibId());
							consume.setFromMerchantId(merchant.getId());
							consume.setLibService(merchant.getLibService());
							consume.setPlatformService(0);
							consume.setType(8);
							consume.setComputeNum(merchant.getCurIsSummary());
							consume.setSignType(merchant.getSignType());
							consume.setRemarks("激活期失效【服务包失效】");
							consume.setCreateTime(new Date());
							libJoinConsumeService.save(consume);
							
							
							consume=new TbLibJoinConsume();
							consume.setFromLibId(merchant.getLibId());
							consume.setFromMerchantId(merchant.getId());
							consume.setLibService(merchant.getLibService());
							consume.setPlatformService(0);
							consume.setType(7);
							consume.setComputeNum(merchant.getCurIsSummary());
							consume.setSignType(merchant.getSignType());
							consume.setRemarks("激活期扣费【服务包扣费】");
							consume.setCreateTime(new Date());
							libJoinConsumeService.save(consume);
						}

					} catch (Exception e) {
						e.printStackTrace();
						logger.error("4：处理商户激活结算日期数据，异常："+e.getMessage());
					}
				}
			}
			
			
			
			//5：处理开始计费日期，生成一条真实的数据30，设置当前的时间， 设置下一个结算日，CurIsSummary=+1，真实开始结算。
			List<Merchant> computeMerchants=merchantService.findMerchantSignByComputeTime();
			for (Merchant merchant : computeMerchants) {
				try {
					//如果开始计费时间为null，就不处理
					if(merchant.getComputeTime()==null) {
						continue;
					}
					
					//记录激活期的结算
					TbLibJoinConsume consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchant.getLibService());
					consume.setPlatformService(0);
					consume.setType(8);
					consume.setComputeNum(merchant.getCurIsSummary());
					consume.setSignType(merchant.getSignType());
					consume.setRemarks("激活期失效【服务包失效】");
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);
					
					
					merchant.setCurIsSummary(1);
					merchant.setCurSummaryTime(new Date());
					merchant.setNextSummaryTime(DateHelper.getMonthDate(merchant.getCurSummaryTime(),1));
					merchantService.save(merchant);
					
					//记录
					consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchant.getLibService());
					consume.setPlatformService(0);
					consume.setType(7);
					consume.setComputeNum(merchant.getCurIsSummary());
					consume.setSignType(merchant.getSignType());
					consume.setRemarks("计费期扣费【服务包扣费：第"+merchant.getCurIsSummary()+"月】");
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);

				} catch (Exception e) {
					e.printStackTrace();
					logger.error("5：处理商户系统激活日期数据，异常："+e.getMessage());
				}
			}
			
			
			
			//6：处理商户结算的数据
			List<Merchant> summaryMerchants=merchantService.findMerchantSignBySummaryTime();
			for (Merchant merchant : summaryMerchants) {
				try {
					//还在免费期的，直接跳出，由第3步处理了
					if(merchant.getCurIsSummary()==null || merchant.getCurIsSummary()<=0) {
						continue;
					}
					
					//没有月份数据的，直接跳出，不做处理
					if(merchant.getLibServiceMonth()==null || merchant.getLibServiceMonth()<=0) {
						continue;
					}
					
					//记录
					TbLibJoinConsume consume=new TbLibJoinConsume();
					consume.setFromLibId(merchant.getLibId());
					consume.setFromMerchantId(merchant.getId());
					consume.setLibService(merchant.getLibService());
					consume.setSignType(merchant.getSignType());
					consume.setPlatformService(0);
					consume.setType(8);
					consume.setComputeNum(merchant.getCurIsSummary());
					consume.setRemarks("计费期失效【服务包失效：第"+(merchant.getCurIsSummary())+"月】");
					consume.setCreateTime(new Date());
					libJoinConsumeService.save(consume);
					
					//处理商户结算的数据
					//已经够月份了，就终止商户
					if(merchant.getCurIsSummary()>=merchant.getLibServiceMonth()) {
						try {
							merchant.setCurIsSummary(0);
							merchant.setCurSummaryTime(null);
							merchant.setNextSummaryTime(null);
							merchant.setLibServiceMonth(0);
							merchant.setLibService(0);
							merchantService.save(merchant);
							
							this.syncMerchantByLibJoin(merchant);
							
							List<MerchantSign> signs=this.findMerchantSignByMerchantId(merchant.getId());
							for (MerchantSign merchantSign : signs) {
								merchantSign.setRemarks("套餐过期引起加油包过期");
								merchantSign.setStatus(1);
								merchantSign.setUpdateTime(new Date());
								this.save(merchantSign);
							}
							
						} catch (Exception e) {
							e.printStackTrace();
							logger.error("3：处理商户结算的数据，异常："+e.getMessage());
						}
						continue;
					}else {
						merchant.setCurIsSummary(merchant.getCurIsSummary()==null ? 1 : merchant.getCurIsSummary()+1);
						merchant.setCurSummaryTime(new Date());
						merchant.setNextSummaryTime(DateHelper.getMonthDate(new Date(),1));
						merchantService.save(merchant);
						
						
						//记录
						consume=new TbLibJoinConsume();
						consume.setFromLibId(merchant.getLibId());
						consume.setFromMerchantId(merchant.getId());
						consume.setLibService(merchant.getLibService());
						consume.setPlatformService(0);
						consume.setType(7);
						consume.setComputeNum(merchant.getCurIsSummary());
						consume.setSignType(merchant.getSignType());
						consume.setRemarks("计费期扣费【服务包扣费：第"+merchant.getCurIsSummary()+"月】");
						consume.setCreateTime(new Date());
						libJoinConsumeService.save(consume);
						
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("6：处理商户结算的数据，异常："+e.getMessage());
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("12点定时任务，处理套餐的数据，异常："+e.getMessage());
		}
		
	}
    
    
    //加油的数量
    private static int signLibService=5;
    
	//套餐模式 【1优选套餐 2VIP套餐 3尊享套餐 4校园服务】 4加油包月包+月 5加油包量包+量。
	//现在暂时只记录加油的记录。
	@Override
	public void insertMerchantSignAndSync(String merchantId, Integer signType,Integer num) {
		Merchant merchant = merchantService.getById(merchantId);
		List<MerchantSign> merchantSigns=new ArrayList<MerchantSign>();
		
		//开始计费时间是否大等于今天。
		boolean isGTDay=false;
		Date computeTime=merchant.getComputeTime()!=null ? merchant.getComputeTime(): merchant.getActiveTime();
		if(computeTime.getTime()<=new Date().getTime()) {
			computeTime=new Date();
			isGTDay=true;
		}

		String remarks="加油包开通【新模式月包】";
		Calendar cal = Calendar.getInstance();
		cal.setTime(computeTime);
		switch (signType) {
		case 4:
			remarks="加油包开通【新模式月包】";
			for (int i = 1; i <=num; i++) {
				MerchantSign merchantSign=new MerchantSign();
				merchantSign.setMerchantId(merchantId);
				merchantSign.setSignType(signType);
				merchantSign.setNum(1);
				if(isGTDay && i==1) {
					merchantSign.setStatus(0);
				}else {
					merchantSign.setStatus(2);
				}
				
				merchantSign.setCreateTime(new Date());
				merchantSign.setLibService(signLibService);
				
				merchantSign.setSignTime(cal.getTime());
				cal.add(Calendar.MONTH, 1);
				merchantSign.setEndSignTime(cal.getTime());
				merchantSigns.add(merchantSign);
			}
			break;
		case 5:
			remarks="加油包开通【新模式量包】";
			MerchantSign merchantSign=new MerchantSign();
			merchantSign.setMerchantId(merchantId);
			merchantSign.setSignType(signType);
			merchantSign.setNum(num);
			if(isGTDay) {
				merchantSign.setStatus(0);
			}else {
				merchantSign.setStatus(2);
			}
			merchantSign.setCreateTime(new Date());
			
			merchantSign.setLibService(signLibService*num);
			merchantSign.setSignTime(cal.getTime());
			cal.add(Calendar.MONTH, 1);
			merchantSign.setEndSignTime(cal.getTime());
			merchantSigns.add(merchantSign);
			
			break;
		default:
			break;
		}
		//保存加油包的记录
		this.save(merchantSigns);

		//记录加油包记录
		switch (signType) {
		case 4:
			for (int i = 1; i <=num; i++) {
				TbLibJoinConsume consume=new TbLibJoinConsume();
				consume.setToLibId(merchant.getLibId());
				consume.setToMerchantId(merchant.getId());
				consume.setLibService(signLibService);
				consume.setPlatformService(0);
				consume.setType(9);
				consume.setComputeNum(0);
				consume.setSignType(merchant.getSignType());
				consume.setRemarks(remarks);
				consume.setCreateTime(new Date());
				libJoinConsumeService.save(consume);
			}
			break;
		case 5:
			TbLibJoinConsume consume=new TbLibJoinConsume();
			consume.setToLibId(merchant.getLibId());
			consume.setToMerchantId(merchant.getId());
			consume.setLibService(signLibService*num);
			consume.setPlatformService(0);
			consume.setType(9);
			consume.setComputeNum(0);
			consume.setSignType(merchant.getSignType());
			consume.setRemarks(remarks);
			consume.setCreateTime(new Date());
			libJoinConsumeService.save(consume);
			break;
		default:
			break;
		}
		
		if(computeTime.getTime()<=new Date().getTime()) {
			TbLibJoinConsume consume=null;
			switch (signType) {
			case 4:
				consume=new TbLibJoinConsume();
				consume.setFromLibId(merchant.getLibId());
				consume.setFromMerchantId(merchant.getId());
				consume.setLibService(signLibService);
				consume.setPlatformService(0);
				consume.setType(10);
				consume.setComputeNum(1);
				consume.setSignType(merchant.getSignType());
				consume.setRemarks("加油包激活【新模式月包】");
				consume.setCreateTime(new Date());
				libJoinConsumeService.save(consume);
				
				break;
			case 5:
				consume=new TbLibJoinConsume();
				consume.setFromLibId(merchant.getLibId());
				consume.setFromMerchantId(merchant.getId());
				consume.setLibService(signLibService*num);
				consume.setPlatformService(0);
				consume.setType(10);
				consume.setComputeNum(num);
				consume.setSignType(merchant.getSignType());
				consume.setRemarks("加油包激活【新模式量包】");
				consume.setCreateTime(new Date());
				libJoinConsumeService.save(consume);
				
				break;
			default:
				break;
			}
			if(consume!=null) {
				
				libJoinConsumeService.save(consume);
				
				//增量商户表的人数
				merchant.setLibService(merchant.getLibService()+consume.getLibService());
				merchantService.save(merchant);	
				//同步商户表与机构表
				this.syncMerchantByLibJoin(merchant);
				
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				//调用openApi接口
				libVipServiceService.openApiServiceCRM(
						1,
						merchant.getLibId(), 
						merchant.getSignType(),
						merchant.getMealType(),
						merchant.getLibService(),
						merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
						merchant.getComputeTime()!=null ? format.format(merchant.getComputeTime()) : format.format(merchant.getActiveTime()),
						merchant.getComputeTime()!=null ? 
								format.format(DateHelper.getMonthDate(merchant.getComputeTime(),merchant.getLibServiceMonth())) : 
									format.format(DateHelper.getMonthDate(merchant.getActiveTime(),merchant.getLibServiceMonth())) 
									);
			}
		}
		
		
		
	}

	
	@Override
	public void syncMerchantByLibJoin(Merchant merchant) {
		if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) {
			TbLibJoin libJoin = libJoinService.getById(merchant.getLibId());
			libJoin.setLibService(merchant.getLibService());
			libJoinService.save(libJoin);
		}
	}

	@Override
	public List<MerchantSign> findMerchantSignByMerchantId(String merchantId) {
		return dao.findMerchantSignByMerchantId(merchantId);
	}

	@Override
	public Page<Map<String, Object>> findMerchantSignByPage(Map<String, Object> params, Pageable initPage) {
		return queryDao.findMerchantSignByPage(params, initPage);
	}

	@Override
	public List<MerchantSign> findMerchantSignByMerchantIdGTTime(String merchantId, Date computeTime, Integer status) {
		return dao.findMerchantSignByMerchantIdGTTime(merchantId, computeTime, status);
	}
	
	
	@Override
	public List<MerchantSign> findMerchantSignAll(String merchantId) {
		return dao.findMerchantSignAll(merchantId);
	}

}


