package com.ssj.service.weixin.library.service.impl;


import com.ssj.bean.weixin.card.domain.LibCardInfo;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.dao.weixin.card.dao.ILibMainCardDao;
import com.ssj.dao.weixin.library.dao.ILibJoinQueryDao;
import com.ssj.dao.weixin.library.dao.ILibVipDao;
import com.ssj.dao.weixin.library.dao.LibVipDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.card.util.CardUtil;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.service.weixin.library.service.ILibVipService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LibVipServiceImpl extends BaseServiceImpl<LibVip, String> implements ILibVipService {

	@Autowired
	private ILibVipDao dao;
	@Autowired
	private ILibMainCardDao cardDao;
	
	@Autowired
	private TokenManager tokenManager;
	
	@Autowired
	private ILibJoinQueryDao  libJoinQueryDao;
	@Autowired
	private LibVipDao libVipDao;

	
	@Override
	public LibVip findByUserId(String userId) {
		
		return dao.findByUserId(userId);
	}

	@Override
	public PagingAndSortingRepository<LibVip, String> getDao() {
		
		return dao;
	}

	@Override
	public Page<LibVip> findByPage(Map<String, Object> params, Pageable sp) {
		Map<String, SearchFilter> filters = SearchFilter.parse(params);
		Specification<LibVip> specification = DynamicSpecifications.bySearchFilter(filters.values(), LibVip.class);
		return  dao.findAll(specification,sp);
	}

	@Override
	public void vipEnCodeAll() throws Exception{
		List<LibVip>  list= dao.getLibVipIsNullQrCodeAll();
		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
		int pageSize = Integer.parseInt( PropertiesUtil.getValue("export_page_size"));
		int i=0;
		String fPath ="";
		for (LibVip vip : list) {
			if(i%pageSize ==0 || i==0){
				fPath+="/VIP/"+ DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd")+"/"+i;
				if (!fPath.endsWith("/")) {
					fPath += "/";
				}
				File f2 = new File(file_path+fPath);
				if (!f2.exists()) {
					f2.mkdirs();
				}
			}
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libVip/bindingLibVip_VIPVIP.html";
			String fPathId = fPath + vip.getFlowId() + ".jpg";
			url=url.replace("VIPVIP", vip.getId());
			BarcodeFactory.bookencode(url,file_path+fPathId,300, 300); 
			vip.setQrcodeUrl(fPathId);
			this.save(vip);
			i++;
		}
	}

	@Override
	public void pushVipCard(final String openId,final String cardId) {
		if(openId!=null){
			  Thread t1 = new Thread(new Runnable() {
		            public void run() {
		            	sendCardToUser(openId,cardId);
		            }
		        });
		        t1.start();
		}
		
	}

	/**
	 * 发送卡券消息
	 * @param openId
	 */
	public void sendCardToUser(String openId,String cardId){
		//查询卡券id
		if(cardId != null && !"".equals(cardId)){
			CardUtil.custSend(tokenManager.getSSJAccessToken(), openId, cardId, tokenManager.getSSJJSAccessToken());
		}else{
			LibCardInfo cardInfo =  cardDao.findByCardTypeAndStat("MEMBER_CARD", "1");
			CardUtil.custSend(tokenManager.getSSJAccessToken(), openId, cardInfo.getCardId(), tokenManager.getSSJJSAccessToken());
		}
	}

	@Override
	public LibVip findByUserIdAndStat(String userId, String stat) {
		
		return dao.findByUserIdAndStat(userId,stat);
	}

	@Override
	public List<Map<String, Object>> getLibVipList(
			Map<String, Object> searchParams) {
		return libJoinQueryDao.getLibVipList(searchParams);
	}

	@Override
	public List<LibVip> getByUserId(String userId) {
		return dao.getByUserId(userId);
	}

	@Override
	public List<LibVip> findListByUserId(String userId,String species) {
		
		return dao.findListByUserId(userId,species);
	}

	@Override
	public LibVip findByCode(String code) {
		return dao.findByCode(code);
	}
	
	
	@Override
	public List<Map<String, Object>> countLibVipNum() {
		return libJoinQueryDao.countLibVipNum();
	}

	@Override
	public Map<String, Object> getUserCountByLib(String libId) {
		
		return libJoinQueryDao.getUserCountByLib(libId);
	}

	@Override
	public List<Map<String, Object>> get2LibUser(String libId, String type) {
		return libJoinQueryDao.get2LibUser(libId,type);
	}

	@Override
	public List<LibVip> findByUserIdAndSpeciseService(String userId,
			String species) {
		return dao.findByUserIdAndSpeciseService(userId, species);
	}
	@Override
	public List<LibVip> findByUserIdAndSpeciseService(String userId,String species,String libId) {
		return dao.findByUserIdAndSpeciseService(userId, species,libId);
	}
	
	@Override
	public  Integer getVipCode(){
		Integer vipCode =0;
		try {
    		String vipcode_list = (String) SystemResourceLocator.getValue("weekendvip_list");
    		String vipcode_cur = tokenManager.getCurWeekendVipCode();
    		 synchronized (this) {
	    		String maxCode=vipcode_cur;
	    		String[] vipCodes=vipcode_list.split(";");
	    		/*
	    		for (String code : vipCodes) { 
	    			String[] codes=code.split("-");
	    			if("0".equals(maxCode)){
	    				vipCode= Integer.parseInt(codes[0]);
	    				break;
	    			}
	    			if(Integer.parseInt(codes[0])<=Integer.parseInt(maxCode) 
	    					&& Integer.parseInt(codes[1])>=Integer.parseInt(maxCode)){
	    				vipCode= Integer.parseInt(maxCode)+1;
	    				break;
	    			}
				}
	    		tokenManager.createCurWeekendVipCode(vipCode+"");
	    		*/
	    		String[] codes=vipCodes[0].split("-");
    			if(StringUtils.isEmpty(maxCode) || "0".equals(maxCode)){
    				vipCode= Integer.parseInt(codes[0]);
    			}
    			if(Integer.parseInt(codes[0])<=Integer.parseInt(maxCode) 
    					&& Integer.parseInt(codes[1])>Integer.parseInt(maxCode)){
    				vipCode= Integer.parseInt(maxCode)+1;
    			}
    			codes=vipCodes[1].split("-");
    			if(vipCode==0){
    				vipCode= Integer.parseInt(codes[0]);
    			}
    			if(Integer.parseInt(codes[0])<=Integer.parseInt(maxCode) 
    					&& Integer.parseInt(codes[1])>Integer.parseInt(maxCode)){
    				vipCode= Integer.parseInt(maxCode)+1;
    			}
    			tokenManager.createCurWeekendVipCode(vipCode+"");
    		 }	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return vipCode;
	}

	@Override
	public LibVip findOneByUserId(String userId) {
		
		return dao.findOneByUserId(userId);
	}

	@Override
	public List<LibVip> getStartDateAndEndDateValidVip(String startDate,
			String endDate) {
		return dao.getStartDateAndEndDateValidVip(startDate, endDate);
	}
	
	@Override
	public LibVip findByCardCode(String cardCode) {
		return dao.findByCardCode(cardCode);
	}

	@Override
	public List<LibVip> getByUserIdDerverIsNull(String userId) {
		return dao.getByUserIdDerverIsNull(userId);
	}

	@Override
	public LibVip findByDerver(String derver) {
		return dao.findByDerver(derver);
	}

	@Override
	public int findDitinctVipByTearcherIdTotal(String teacherUserId) {
		
		return dao.findDitinctVipByTearcherIdTotal(teacherUserId);
	}

	@Override
	public Page<Map<String, Object>> findDistinctVipByTeacherId(Map<String, Object> searchParams, Pageable pageable) {
		return libVipDao.findDistinctVipByTeacherId(searchParams, pageable);
	}

	@Override
	public void updateVipByVipId(String vipId) {
		dao.updateVipByVipId(vipId);
	}

	@Override
	public List<String> findDistinctUserIdList() {
		return dao.findDistinctUserIdList();
	}

	@Override
	public List<LibVip> findByDervers(List<String> dervers) {
		return dao.findByDerverIn(dervers);
	}

	@Override
	public List<LibVip> findByIds(List<String> ids) {
		return dao.findByIdIn(ids);
	}

	@Override
	public List<LibVip> findByChildName(String name) {
		return dao.findByChildNameLike(name);
	}

	@Override
	public LibVip findByQrcodeUrl(String qrcodeUrl) {
		return dao.findByQrcodeUrl(qrcodeUrl);
	}
	@Override
	public List<Map<String, Object>> getServiceVip(String userId, 
			String species) {
		return libJoinQueryDao.getServiceVip(userId, species);
	}

	@Override
	public List<Map<String, Object>> getServiceVip(String userId,String libId,String species) {
		return libJoinQueryDao.getServiceVip(userId, species);
	}

	@Override
	public LibVip findByChildUserId(String childUserId) {
		return dao.findByChildUserId(childUserId);
	}

	@Override
	public LibVip findByUserIdAndChildName(String parentId, String childName) {
		return dao.findByUserIdAndChildName(parentId, childName);
	}
	
	@Override
	public List<LibVip> findByUserIdAndChildNames(String parentId, String childName) {
		return dao.findByUserIdAndChildNames(parentId, childName);
	}

	@Override
	public String validateIsParent(String userId, String childUserId) {
		LibVip vip = dao.validateIsParent(userId, childUserId);
		if(vip != null) {
			//如果发送方是小孩则返回小孩姓名
			if(vip.getChildUserId().equals(userId)) {
				return vip.getChildName();
			}
			if(StringUtils.isBlank(vip.getParentRole())) {
				return "爸妈";
			}
		    return vip.getParentRole();
		}
		//判断是否是副家长
		return	dao.validateIsSecondParent(userId, childUserId);
	}
	
	@Override
	public List<LibVip> getOtherChildInfo(String userId) {
		return dao.getOtherChildInfo(userId);
	}

	@Override
	public void updateGradeByGrade(String newGrade, String oldGrade) {
		dao.updateGradeByGrade(newGrade, oldGrade);
	}



	@Override
	public List<LibVip> findByLibId(String libId) {
		return dao.findByLibId(libId);
	}

	@Override
	public LibVipService findInnerStudentByVipId(String vipId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<LibVip> findByLibIdActivateTime(String libId, Date signTime) {
		return dao.findByLibIdActivateTime(libId, signTime);
	}

	@Override
	public List<Map<String, Object>> findVipByLibIdMaxActivateTime(String libId, Date activateTime, String species) {
		return libVipDao.findVipByLibIdMaxActivateTime(libId, activateTime, species);
	}

	@Override
	public int countByLibId(String libId) {
		return dao.countByLibId(libId);
	}

	@Override
	public void updateLibId(String libId) {
		dao.updateLibId(libId);
	}
}
