package com.ssj.service.conch.teacher.service.impl;

import com.ssj.bean.sys.teacher.domain.ApplyTeacher;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.sys.teacher.dao.IApplyTeacherDao;
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.ResponseEntity;
import com.ssj.service.conch.teacher.request.oneonly.ApplyTeacherReq;
import com.ssj.service.conch.teacher.request.oneonly.TeacherImgVO;
import com.ssj.service.conch.teacher.service.IApplyTeachService;
import com.ssj.service.weixin.library.service.IBookManagerService;
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.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ApplyTeacherServiceImpl extends BaseServiceImpl<ApplyTeacher, String> implements IApplyTeachService {

	@Autowired
	private IApplyTeacherDao dao;
	
	@Autowired
    private TokenManager tokenManager;
	
	@Autowired
	private IBookManagerService managerService;
	
	@Autowired
	private UserService userService;
	
	@Override
	public PagingAndSortingRepository<ApplyTeacher, String> getDao() {
		return dao;
	}

	@Override
	public ResponseEntity applyTeacher(ApplyTeacherReq request, String accessToken) {
		ResponseEntity response = new ResponseEntity();
		//查询是否有数据
		String userId = tokenManager.getUserId(accessToken);
		User user = userService.getById(userId);
		ApplyTeacher teacher = dao.findTeacherByUserId(userId);

		//将科目列表拼成分号隔开的字符串
		StringBuilder subjects = new StringBuilder();
		if (request.getSubjects() != null){
			request.getSubjects().forEach((subject) -> {
				if (subject.getActive() == 2){
					subjects.append(subject.getName()).append(";");
				}
			});
		}
		//如果有科目,删除最后一个分号
		if (subjects.length() > 0){
			subjects.deleteCharAt(subjects.length() - 1);
		}

		if(teacher == null){ //新增
			teacher = new ApplyTeacher();
			teacher.setHeadPicUrl(request.getHeadPicUrl()==null?user.getPhoto():request.getHeadPicUrl());
			teacher.setRealName(request.getRealName());
			teacher.setSex(request.getSex());
			teacher.setSubject(subjects.toString());
			List<TeacherImgVO> imgList = request.getTeacherImgList();
			List<String> list1 = new ArrayList<String>();
			List<String> list2 = new ArrayList<String>();
			for(TeacherImgVO vo:imgList){
				if(vo.getType() == 1){
					list1.add(vo.getFileKey());
				}else{
					list2.add(vo.getFileKey());
				}
			}
			teacher.setTeacherImg(StringUtils.join(list2, ",")); //正反面
			teacher.setTitleImg(StringUtils.join(list1, ",")); //资格证
			teacher.setCreateTime(new Date());
			teacher.setConcatPhone(request.getConcatPhone());
			teacher.setSchoolAge(request.getSchoolAge());
			teacher.setPersonalLabel(StringUtils.join(request.getPersonalLabel().toArray(), ","));
			teacher.setPersonalInfo(request.getPersonalInfo());
			teacher.setSuccessfulCase(request.getSuccessfulCase());
			teacher.setTeachPoint(request.getTeachPoint());
			teacher.setUserId(user.getId());
			teacher.setAuditState("1");
			this.save(teacher);
		}else{ //修改 联系方式、教龄时间、个人标签、个人简介、教学特征、成功案例。
			//如果是审核通过的数据，同步更新tb_lib_manager 表的教师信息
			if(teacher.getAuditState().equals("3")){ //审核不通过
				teacher = new ApplyTeacher();
				teacher.setHeadPicUrl(request.getHeadPicUrl()==null?user.getPhoto():request.getHeadPicUrl());
				teacher.setRealName(request.getRealName());
				teacher.setSex(request.getSex());
				teacher.setSubject(subjects.toString());
				List<TeacherImgVO> imgList = request.getTeacherImgList();
				List<String> list1 = new ArrayList<String>();
				List<String> list2 = new ArrayList<String>();
				for(TeacherImgVO vo:imgList){
					if(vo.getType() == 1){
						list1.add(vo.getFileKey());
					}else{
						list2.add(vo.getFileKey());
					}
				}
				teacher.setTeacherImg(StringUtils.join(list2, ",")); //正反面
				teacher.setTitleImg(StringUtils.join(list1, ",")); //资格证
				teacher.setCreateTime(new Date());
				teacher.setConcatPhone(request.getConcatPhone());
				teacher.setSchoolAge(request.getSchoolAge());
				teacher.setPersonalLabel(StringUtils.join(request.getPersonalLabel().toArray(), ","));
				teacher.setPersonalInfo(request.getPersonalInfo());
				teacher.setSuccessfulCase(request.getSuccessfulCase());
				teacher.setTeachPoint(request.getTeachPoint());
				teacher.setUserId(user.getId());
				teacher.setAuditState("1");
				this.save(teacher);
			}else{
				teacher.setHeadPicUrl(request.getHeadPicUrl()==null?user.getPhoto():request.getHeadPicUrl());
				teacher.setConcatPhone(request.getConcatPhone());
				teacher.setSchoolAge(request.getSchoolAge());
				teacher.setPersonalLabel(StringUtils.join(request.getPersonalLabel().toArray(), ","));
				teacher.setPersonalInfo(request.getPersonalInfo());
				teacher.setSuccessfulCase(request.getSuccessfulCase());
				teacher.setTeachPoint(request.getTeachPoint());
				teacher.setUpdateTime(new Date());
				this.save(teacher);
				TbLibManager manager = managerService.findByUserId(userId, 7);
				if(manager !=null){
					manager.setTelephone(request.getConcatPhone());
					manager.setSchoolAge(request.getSchoolAge());
					manager.settPhoto(request.getHeadPicUrl()==null?user.getPhoto():request.getHeadPicUrl());
					manager.setPersonalInfo(teacher.getPersonalInfo());
					manager.setPersonalLabel(teacher.getPersonalLabel());
					manager.setSuccessfulCase(teacher.getSuccessfulCase());
					manager.setTeachPoint(teacher.getTeachPoint());
					manager.setSchoolAge(teacher.getSchoolAge());
					managerService.save(manager);
				}
			}	
		}
		response.success();
		return response;
	}

	@Override
	public ApplyTeacher findInfoByUserId(String userId) {
		
		return dao.findTeacherByUserId(userId);
	}

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

}
