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

import com.ssj.bean.weixin.libmy.domain.LibVipBind;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.dao.weixin.library.dao.LibVipBindDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.LibVipBindService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LibVipBindServiceImpl extends BaseServiceImpl<LibVipBind, String> implements LibVipBindService {

	@Autowired
	private LibVipBindDao dao;
	
	@Autowired
	private  IBookManagerService bookManagerService;
	

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

	@Override
	public void vipBindByMasterId(String vipId,String masterId,String teacherId,String userId) {
		if(StringUtils.isNotEmpty(teacherId) && StringUtils.isEmpty(masterId)){
			TbLibManager manager=bookManagerService.findByUserId(teacherId, 7);//老师找到校长
			masterId=manager.getMasterId();
		}
		List<LibVipBind> binds=dao.findByVipIdAndMasterId(vipId, masterId, teacherId);
		if(CollectionUtils.isEmpty(binds)){
			LibVipBind b=new LibVipBind();
			b.setCreateTime(new Date());
			b.setMasterId(masterId);
			b.setTeacherId(StringUtils.isEmpty(teacherId)?null:teacherId);
			b.setVipId(vipId);
			b.setUserId(userId);
			dao.save(b);
		}
	}


	@Override
	public List<LibVipBind> findVipByVipIdsAndMaster(String[] vipIds, String masterId) {
		return dao.findByVipIdInAndMasterId(vipIds, masterId);
	}

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

	@Override
	public LibVipBind findByVipId(String studentId) {
		
		return dao.findByVipId(studentId);
	}

	@Override
	public List<LibVipBind> findVipBindsByMasterId(String masterId) {
		return dao.findByMasterId(masterId);
	}

	@Override
	public int checkIsBindMaster(String vipId) {
		int count = dao.countByVipIdAndMasterIdIsNotNull(vipId);
		if(count >1) {
			count = 1;
		}
		return count;
	}

	@Override
	public LibVipBind findByVipIdAndSubject(String vipId, String subject) {
		List<LibVipBind> list = dao.findByVipIdAndSubject(vipId, subject);
		LibVipBind libVipBind = null;
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (i == 0) {
					libVipBind = list.get(i);
				} else {
					//删除多余重复数据
					dao.delete(list.get(i));
				}
			}
		}
		return libVipBind;
	}
}
