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

import com.ssj.bean.weixin.sales.domain.LibVipCode;
import com.ssj.dao.weixin.sales.dao.LibOrderDetailsQueryDao;
import com.ssj.dao.weixin.sales.dao.LibVipCodeDao;
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.service.weixin.sales.service.LibVipCodeService;
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.util.List;
import java.util.Map;
import java.util.Random;


/** 
 * @author  ZhangCaibao 
 * @version 2017年6月6日 下午4:05:04 
 * 类说明 
 */
@Service
@Transactional
public class LibVipCodeServiceImpl extends BaseServiceImpl<LibVipCode, String> implements  LibVipCodeService{
	 @Autowired
	private LibVipCodeDao  libVipCodeDao;
	 @Autowired
	 private LibOrderDetailsQueryDao  libOrderDetailsQueryDao;
	@Override
	public PagingAndSortingRepository<LibVipCode, String> getDao() {
		return libVipCodeDao;
	}

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

	@Override
	public LibVipCode findByVipCode(String vipCode, String libId) {
		return libVipCodeDao.findByVipCode(vipCode, libId);
	}

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

	@Override
	public void inserLibVipCode(String libId, String discount) {
		 Random random = new Random();
		int rand = random.nextInt(500000)%(500000-100000+1) + 100000;
		libVipCodeDao.inserLibVipCode(libId, discount,rand);		
	}

	@Override
	public LibVipCode findByVipCodeAndType(String vipCode, String libId) {
		return libVipCodeDao.findByVipCodeAndType(vipCode, libId);
	}
	
	@Override
	public synchronized List<LibVipCode> queryLibVipCodeBy(String libId, Integer type,String discount,Integer size) {
		List<LibVipCode> libVipCodes=libVipCodeDao.queryLibVipCodeBy(libId, type, discount, size);
		for (LibVipCode libVipCode : libVipCodes) {
			libVipCode.setType(3);
		}
		libVipCodeDao.save(libVipCodes);
		return libVipCodes;
	}

	@Override
	public List<LibVipCode> queryLibVipCodeByType() {
		return libVipCodeDao.queryLibVipCodeByType();
	}
}
