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

import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.sys.imlibuser.TbClass;
import com.ssj.bean.sys.imlibuser.TbClassStudent;
import com.ssj.bean.sys.imlibuser.TbClassStudentTemp;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.QrCode;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.sys.imlibuser.dao.TbClassQueryDao;
import com.ssj.dao.sys.imlibuser.dao.TbClassStudentTempDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.service.conch.common.service.ConchCommonService;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.fx.service.MerchantAreaService;
import com.ssj.service.sys.imlibuser.service.TbClassService;
import com.ssj.service.sys.imlibuser.service.TbClassStudentService;
import com.ssj.service.sys.imlibuser.service.TbClassStudentTempService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.QrCodeService;
import com.ssj.service.weixin.user.service.UserService;
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.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(version = "1.0")
@Transactional
public class TbClassStudentTempServiceImpl extends BaseServiceImpl<TbClassStudentTemp, String> implements TbClassStudentTempService {

	@Autowired
	private TbClassStudentTempDao dao;
	
	@Autowired
	private TbClassQueryDao queryDao;
	
	@Autowired
	private TbClassStudentService tbLibImStudentService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ILibVipService vipService; 
	
	@Autowired
	private ConchCommonService  conchCommonService;
	
	@Autowired
 	private ILibJoinService joinService;    
	
	@Autowired
 	private LibVipServiceService libVipServiceService;

	@Autowired
	private QrCodeService qrCodeService;
	
	@Autowired
    private TokenManager tokenManager;
	
	@Autowired
	private ConchDerverService conchDerverService;
	
	@Autowired
	private EasemobService easemobService;
	
	@Autowired
	private TbClassService tbClassService;
	
	@Autowired
	private TbClassStudentService tbClassStudentService;
	
	@Autowired
	private MerchantAreaService merchantAreaService;
	
	
	@Override
	public PagingAndSortingRepository<TbClassStudentTemp, String> getDao() {
		return dao;
	}

	@Override
	public Page<Map<String, Object>> findStudentErrorByPage(
			Map<String, Object> searchParam, Pageable pageable) {
		return queryDao.findStudentErrorByPage(searchParam, pageable);
	}


	@Override
	public int insertTbClassStudent(TbLibJoin libJoin,TbClassStudentTemp tbLibImStudentTemp) {
		int reqNum=1;
		if(libJoin!=null){
			tbLibImStudentTemp.setLibId(libJoin.getId());
			tbLibImStudentTemp.setLeagueName(libJoin.getLeagueName());
			tbLibImStudentTemp.setCreateTime(new Date());
			tbLibImStudentTemp.setStatus(1);
			
			try {
//				if(StringUtils.isNotEmpty(tbLibImStudentTemp.getSchool())) {
//					List<PositionSchoolV1Dto> positionSchoolV1Dtos= merchantAreaService.findSchoolList(libJoin.getId());
//					if(positionSchoolV1Dtos!=null && positionSchoolV1Dtos.size()>0) {
//						List<String> libJoinSchools=new ArrayList<String>();
//						for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
//							libJoinSchools.add(positionSchoolV1Dto.getSchoolName());
//						}
//						if(!libJoinSchools.contains(tbLibImStudentTemp.getSchool())){
//							tbLibImStudentTemp.setStatus(0);
//							tbLibImStudentTemp.setErrorReason("导入的学校未绑定机构");
//							this.save(tbLibImStudentTemp);
//							reqNum=0;
//							return reqNum;
//						}
//					}
//				}
				
				if(StringUtils.isNotEmpty(tbLibImStudentTemp.getDerver())) {
					ConchDerver conchDerver = conchDerverService.findByDerver(tbLibImStudentTemp.getDerver());
					if (conchDerver == null) {
						tbLibImStudentTemp.setStatus(0);
						tbLibImStudentTemp.setErrorReason("导入的小塾不存在");
						this.save(tbLibImStudentTemp);
						reqNum=0;
						return reqNum;
					}
				}
				User user=userService.findByMobile(tbLibImStudentTemp.getParentPhone());
				if(user==null){//无家长，生成家长
					user=new User();
					user.setId(IdWorker.generateId());
					user.setUserName(tbLibImStudentTemp.getParentName());
					user.setMobile(tbLibImStudentTemp.getParentPhone());
					user.setCreateTime(new Date());
					user=userService.save(user);
				}
				LibVip libVip=null;
				List<LibVip> libVips=vipService.findByUserIdAndChildNames(user.getId(), tbLibImStudentTemp.getStudentName());
				if(libVips!=null && libVips.size()>=2) {
					tbLibImStudentTemp.setStatus(0);
					tbLibImStudentTemp.setErrorReason("请删除重名孩子，再尝试导入");
					this.save(tbLibImStudentTemp);
					reqNum=0;
					return reqNum;
				}else if (libVips!=null && libVips.size()==1) {
					libVip=libVips.get(0);
				}
				if(libVip==null){//无学生，生成学生
					
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getDerver())) {
						ConchDerver conchDerver = conchDerverService.findByDerver(tbLibImStudentTemp.getDerver().trim());
						if(conchDerver!=null) {
							if (StringUtils.isNotEmpty(conchDerver.getVipId())) {
								tbLibImStudentTemp.setStatus(0);
								tbLibImStudentTemp.setErrorReason("导入小塾已被其他人绑定");
								this.save(tbLibImStudentTemp);
								reqNum=0;
								return reqNum;
							}
						}
					}
					
					libVip=new LibVip();
					libVip.setChildType(0);
					libVip.setUserId(user.getId());
					libVip.setParentName(tbLibImStudentTemp.getParentName());
					libVip.setChildName(tbLibImStudentTemp.getStudentName());
					libVip.setPhone(tbLibImStudentTemp.getParentPhone());
					libVip.setSchool(tbLibImStudentTemp.getSchool());
					libVip.setParentRole(tbLibImStudentTemp.getParentRole());
					libVip.setGrade(tbLibImStudentTemp.getGrade());
					libVip.setLibId(libJoin.getId());
					libVip.setStat("1");
					libVip.setCreateTime(new Date());
					libVip=vipService.save(libVip);
					tbLibImStudentTemp.setVipId(libVip.getId());
				}else {
					tbLibImStudentTemp.setVipId(libVip.getId());
					
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getDerver())) {
						if(StringUtils.isNotEmpty(libVip.getDerver())) {
							if(!libVip.getDerver().equals(tbLibImStudentTemp.getDerver())) {
								tbLibImStudentTemp.setStatus(0);
								tbLibImStudentTemp.setErrorReason("小塾号与用户已绑定的小塾不一致");
								this.save(tbLibImStudentTemp);
								reqNum=0;
								return reqNum;
							}
						}
					}
					
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getDerver())) {
						ConchDerver conchDerver = conchDerverService.findByDerver(tbLibImStudentTemp.getDerver().trim());
						if(conchDerver!=null) {
							if (StringUtils.isNotEmpty(conchDerver.getVipId()) && !libVip.getDerver().equals(tbLibImStudentTemp.getDerver())) {
								tbLibImStudentTemp.setStatus(0);
								tbLibImStudentTemp.setErrorReason("导入小塾已被其他人绑定");
								this.save(tbLibImStudentTemp);
								reqNum=0;
								return reqNum;
							}
						}
					}

					//有学生，判断机构是为空，绑定机构
					if(StringUtils.isEmpty(libVip.getLibId())) {
						libVip.setLibId(libJoin.getId());
						libVip=vipService.save(libVip);
					}else {
						//有学生，判断机构不为空，判断是否机构和导入机构一致，一致的话反回导入不成功，不一致的话返回机构不合
						if(!libVip.getLibId().equals(tbLibImStudentTemp.getLibId())) {
							tbLibImStudentTemp.setStatus(0);
							tbLibImStudentTemp.setErrorReason("与平台已有用户机构冲突");
							this.save(tbLibImStudentTemp);
							reqNum=0;
							return reqNum;
						}else {
							tbLibImStudentTemp.setStatus(0);
							tbLibImStudentTemp.setErrorReason("与平台已有用户信息冲突");
							this.save(tbLibImStudentTemp);
							reqNum=0;
							return reqNum;
						}
					}
					
					
				}
				
				
//				boolean isError=insertTbClassStudentByService(tbLibImStudentTemp);
//				if(!isError) {
//					tbLibImStudentTemp.setStatus(0);
//					tbLibImStudentTemp.setErrorReason("导入的服务时间与用户现有服务时间冲突");
//					this.save(tbLibImStudentTemp);
//					//还原绑定机构
//					libVip.setLibId(null);
//					libVip=vipService.save(libVip);
//					reqNum=0;
//					return reqNum;
//				}
				
				//绑定derver
				if(StringUtils.isNotEmpty(tbLibImStudentTemp.getDerver()) && StringUtils.isEmpty(libVip.getDerver())){
					if (StringUtils.isBlank(user.getEasemobName())) {
					    //如果家长没有环信id
						user.setEasemobName(userService.createUniqueEasemobName());
					    userService.save(user);
					    easemobService.createUserSingle(user.getEasemobName(), user.getUserName());
					}
					ResponseEntity responseEntity=conchCommonService.bindDerver(libVip.getId(), "", "", tbLibImStudentTemp.getDerver());
					try {
						if(responseEntity.getStatus().equals(ResponseConstant.CODE_999)){
							String DERVER ="DERVER_";
							ConchDerver  conchDerver= tokenManager.get(DERVER+tbLibImStudentTemp.getDerver(), ConchDerver.class);
							QrCode qrCode =qrCodeService.creatTicket(conchDerver.getDerver());
							conchDerver.setQrCode(qrCode.getUrl());
							conchDerver.setQrCodeImg(qrCode.getQrcodeUrl());
							conchDerver.setCreatedDate(new Date());
							conchDerverService.save(conchDerver);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				
//				TbClass tbClass=tbClassService.getDefaultTbClassByLibId(libJoin.getId());
				
//				TbClassStudent tbClassStudent=tbClassStudentService.getTbClassTeacherByVipId(tbClass.getId(), libVip.getId());
//				if(tbClassStudent==null) {
//					tbClassStudent=new TbClassStudent();
//					tbClassStudent.setLibId(libJoin.getId());	
//					tbClassStudent.setClassId(tbClass.getId());
//					tbClassStudent.setVipId(libVip.getId());
//					tbClassStudent.setStatus(1);
//					tbClassStudent.setCreateTime(new Date());
//					tbClassStudentService.save(tbClassStudent);
//				}

				//给学生增加一个默认的永久校区批改服务
	            libVipServiceService.insertLibCorrectService(libVip.getId(),libJoin.getId());
				
			} catch (Exception e) {
				e.printStackTrace();
				tbLibImStudentTemp.setStatus(0);
				tbLibImStudentTemp.setErrorReason("异常："+e.getMessage());
			}finally{
				this.save(tbLibImStudentTemp);
			}
			return reqNum;
		}
		return reqNum;
	}

	@Override
	public int insertBatchTbClassStudent(List<TbClassStudentTemp> tbLibImStudentTemps) {
		int successNum=0;
		for (TbClassStudentTemp tbLibImStudentTemp : tbLibImStudentTemps) {
			try {
				TbLibJoin libJoin=null;
				if(StringUtils.isNotEmpty(tbLibImStudentTemp.getLibId())){
					libJoin=joinService.getById(tbLibImStudentTemp.getLibId());
				}else{
				    libJoin=tbLibImStudentService.getTbLibJoinByLeagueName(tbLibImStudentTemp.getLeagueName());
				}
				//一定要有机构数据才能导入
				if(libJoin!=null){
					successNum=successNum+this.insertTbClassStudent(libJoin, tbLibImStudentTemp);
				}else{
					successNum=-1;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return successNum;
	}
	
	
	@Override
	public boolean insertTbClassStudentByService(TbClassStudentTemp tbLibImStudentTemp){
		try {
			//需要添加服务
			if(tbLibImStudentTemp.getStartTime()!=null){
				Integer serviceNum=tbLibImStudentTemp.getServiceNum()!=null && tbLibImStudentTemp.getServiceNum()>=1 ? tbLibImStudentTemp.getServiceNum() : 1;
				Date endTime=DateHelper.getMonthDate(tbLibImStudentTemp.getStartTime(),serviceNum);
				
				LibVipService libVipService = new LibVipService();
				libVipService.setBorrowDay(0);
				libVipService.setBorrowNum(0);
				libVipService.setDeposit(0);
				libVipService.setLibId(tbLibImStudentTemp.getLibId());
				libVipService.setOutMoney(new BigDecimal(0));
				libVipService.setSpecies("S003");
				libVipService.setStartTime(tbLibImStudentTemp.getStartTime());
				libVipService.setEndTime(endTime);
				libVipService.setStat(1);
				libVipService.setType("C004");
				libVipService.setVipId(tbLibImStudentTemp.getVipId());
				libVipService.setOrderDetailsId("zyb");
				libVipService.setIsJia(0);
				libVipService.setCourseCount(0);
				libVipService.setCorrectType(tbLibImStudentTemp.getCorrectType());
				
				boolean is=true;
				if(tbLibImStudentTemp.getTakeType()!=null && tbLibImStudentTemp.getTakeType()==1){
					//设置为立即生效，
					libVipServiceService.insertVipIdServiceByAndTakeType(libVipService, 1);
				}else{
					//设置为推后生效，如果有冲突就返回失败
					is=libVipServiceService.insertVipIdServiceByAndTakeType(libVipService, 2);
				}
				
				if(is) {
					//设置如果有S999为失效
					List<LibVipService> oldLibVipServices=libVipServiceService.findByVipIdAndSpeciesAndStat(libVipService.getVipId(), "S999",1);
						if(oldLibVipServices.size()>0) {
							for (LibVipService oldLibVipService : oldLibVipServices) {
								oldLibVipService.setStat(2);
							}
						libVipServiceService.save(oldLibVipServices);
						
						LibVip libVip=vipService.getById(libVipService.getVipId());
						libVip.setChildType(0);
						vipService.save(libVip);
					}
				}
				return is;
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public List<TbClassStudentTemp> findTbLibImStudentTempByVipId(String libId,String vipId) {
		return dao.findTbLibImStudentTempByVipId(libId, vipId);
	}
	


}
