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


import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.mybatis.ManagerMBDto;
import com.ssj.bean.sys.usercenter.domain.*;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.conch.conch.dao.ConchDerverDao;
import com.ssj.dao.sys.usercenter.dao.*;
import com.ssj.dao.weixin.user.dao.UserDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybStudentWorkImgDao;
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.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.mapper.correctsys.CorrectSysMapper;
import com.ssj.service.sys.usercenter.service.UserCenterService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.user.service.UserService;
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.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import java.util.*;

/**
 * @author Mount Liu
 * @date 2018/9/11
 */
@Service(version = "1.0")
@Transactional
public class UserCenterServiceImpl extends BaseServiceImpl<User, String> implements UserCenterService {

	@Autowired
	private UserDao dao;

	//@Autowired
	//private HomeworkPictureDao homeworkPictureDao;

	//@Autowired
	//private ProblemPictureDao problemPictureDao;

	//@Autowired
	//private SmarttimeDao smarttimeDao;

	@Autowired
	private ZuoybStudentWorkImgDao zuoybStudentWorkImgDao;

	@Autowired
	private UserCenterQueryDao userCenterQueryDao;

	@Autowired
	private CuratorCenterDao curatorCenterDao;
	@Autowired
	private ParentCenterDao parentCenterDao;
	@Autowired
	private SchoolmasterCenterDao schoolmasterCenterDao;
	@Autowired
	private StudentCenterDao studentCenterDao;
	@Autowired
	private TeacherCenterDao teacherCenterDao;
    @Autowired
    private ConchDerverDao conchDerverDao;
    @Autowired
	private IBookManagerService managerService;
	@Autowired
	private UserService userService;
	// @Autowired
   // private LessonServiceDao lessonServiceDao;
	@Autowired
	private CorrectSysMapper correctSysMapper;

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

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

	@Override
	public Map<String, Object> studentDetail(String vipId) {
		Map<String,Object> map = new HashMap<>(16);
		//1.数据统计：作业、难题、小时光、错题数量
		long homeworkCount = 1;
		long prolemCount = 1;
		long smarttimeCount = 1;
		long wrongCount = zuoybStudentWorkImgDao.countByVipId(vipId);
		//贝壳服务
		//List<Map<String, Object>> conchService = userCenterQueryDao.findStudentServiceList(vipId, "S005");
		//作业吧服务
		List<Map<String, Object>> zybService = userCenterQueryDao.findStudentServiceList(vipId, "S003");
		//一对一
		//List<Map<String, Object>> ydyService = userCenterQueryDao.findStudentOneToOneServiceList(vipId);
		//学习状态分析：学习积极性、专注度、作业速度、自律性
		List<Map<String, Object>> studentWorkList = userCenterQueryDao.findStudentWorkList(vipId,new String[]{"学习积极性","专注度","作业速度","自律性"});
		map.put("homeworkCount",homeworkCount);
		map.put("prolemCount",prolemCount);
		map.put("smarttimeCount",smarttimeCount);
		map.put("wrongCount",wrongCount);
		//map.put("conchService",conchService);
		map.put("zybService",zybService);
		//map.put("ydyService",ydyService);
		map.put("studentWorkList",studentWorkList);
		return map;
	}

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

    @Override
    public Page<ParentCenter> findParentListByPage(HashMap<String, Object> paramsMap, Pageable pageable) {
        Map<String, SearchFilter> filters = SearchFilter.parse(paramsMap);
        Specification<ParentCenter> specification = DynamicSpecifications.bySearchFilter(filters.values(), ParentCenter.class);
        return parentCenterDao.findAll(specification, pageable);
    }

	@Override
	public Page<TeacherCenter> findTeacherListByPage(HashMap<String, Object> paramsMap, Pageable pageable) {
		Map<String, SearchFilter> filters = SearchFilter.parse(paramsMap);
		Specification<TeacherCenter> specification = DynamicSpecifications.bySearchFilter(filters.values(), TeacherCenter.class);
		return teacherCenterDao.findAll(specification, pageable);
	}

	@Override
	public Page<CuratorCenter> findCuratorListByPage(HashMap<String, Object> paramsMap, Pageable pageable) {
		Map<String, SearchFilter> filters = SearchFilter.parse(paramsMap);
		Specification<CuratorCenter> specification = DynamicSpecifications.bySearchFilter(filters.values(), CuratorCenter.class);
		return curatorCenterDao.findAll(specification, pageable);
	}

	@Override
	public Page<ConchDerver> findConchListByPage(HashMap<String, Object> paramsMap, Pageable pageable) {
		Map<String, SearchFilter> filters = SearchFilter.parse(paramsMap);
		Specification<ConchDerver> specification = DynamicSpecifications.bySearchFilter(filters.values(), ConchDerver.class);
		return conchDerverDao.findAll(specification, pageable);
	}

	@Override
	public Page<Map<String, Object>> findConchListByQueryPage(Map<String, Object> paramsMap, Pageable pageable) {
		return userCenterQueryDao.findConchListByPage(paramsMap, pageable);
	}

	@Override
	public Page<Map<String, Object>> findStudentListByQueryPage(Map<String, Object> paramsMap, Pageable pageable) {
		return userCenterQueryDao.findStudentListByPage(paramsMap, pageable);
	}

	@Override
	public List<Map<String, Object>> findRoleList(String userId) {
		return userCenterQueryDao.findRoleList(userId);
	}

	@Override
	public void findSchoolmasterDetail(Model model, String schoolmasterUserId) {
		SchoolmasterCenter schoolmaster = schoolmasterCenterDao.findByUserId(schoolmasterUserId);
		model.addAttribute("schoolmaster", schoolmaster);

		List<TeacherCenter> teacherList = teacherCenterDao.findByMasterId(schoolmasterUserId);
		model.addAttribute("teacherList", teacherList);

		List<StudentCenter> studentList = studentCenterDao.findBySchoolmasterUserId(schoolmasterUserId);
		model.addAttribute("studentList", studentList);


		model.addAttribute("lessonServiceList", "");
	}

    @Override
    public void findParentDetail(Model model, String parentUserId) {
        List<StudentCenter> childList = studentCenterDao.findByParentId(parentUserId);
        model.addAttribute("childList", childList);
    }

	@Override
	public void findTeacherDetail(Model model, String id) {
		TeacherCenter teacher = teacherCenterDao.findOne(id);
		model.addAttribute("teacher", teacher);
		List<Map<String, Object>> subscribeCountList = userCenterQueryDao.findStudentSubscribeCountList(id);
		model.addAttribute("subscribeCountList", subscribeCountList);
		List<Map<String, Object>> studentList = userCenterQueryDao.findOneByOneStudentList(teacher.getUserId());
		model.addAttribute("studentList", studentList);
		List<String> vipIdList = new ArrayList<>();
		for (int i = 0; i < studentList.size(); i++) {
			vipIdList.add(studentList.get(i).get("id").toString());
		}
		List<Map<String, Object>> oneToOneService = userCenterQueryDao.findStudentOneToOneServiceList(vipIdList);
		model.addAttribute("oneToOneService", oneToOneService);
		List<Map<String, Object>> workCountList = userCenterQueryDao.findWorkCountOfTeacherList(teacher.getUserId());
		model.addAttribute("workCountList", workCountList);
		Map<String, Object> workRateMap = new HashMap<>(16);
		if (workCountList != null && workCountList.size() > 0) {
			for (Map<String, Object> map : workCountList) {
				workRateMap.put(map.get("type").toString(), map.get("num"));
			}
			if (Integer.valueOf(workRateMap.get("all_week").toString()) > 0) {
				double rate = Double.valueOf(workRateMap.get("finished_week").toString()) / Double.valueOf(workRateMap.get("all_week").toString());
				workRateMap.put("week_rate", rate);
			} else {
				workRateMap.put("week_rate", "");
			}
			if (Integer.valueOf(workRateMap.get("all_month").toString()) > 0) {
				double rate = Double.valueOf(workRateMap.get("finished_month").toString()) / Double.valueOf(workRateMap.get("all_month").toString());
				workRateMap.put("month_rate", rate);
			} else {
				workRateMap.put("month_rate", "");
			}
			if (Integer.valueOf(workRateMap.get("all_year").toString()) > 0) {
				double rate = Double.valueOf(workRateMap.get("finished_year").toString()) / Double.valueOf(workRateMap.get("all_year").toString());
				workRateMap.put("year_rate", rate);
			} else {
				workRateMap.put("year_rate", "");
			}
		} else {
			workRateMap.put("week_rate", "");
			workRateMap.put("month_rate", "");
			workRateMap.put("year_rate", "");
		}
		model.addAttribute("workRateMap", workRateMap);
	}

	@Override
	public ResponseEntity untieRole(String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		TbLibManager manager = managerService.findByUserIdAndType(userId, 14);
		if (manager != null) {
			//解除质检员身份
			manager.setState(2);
			managerService.save(manager);
		}
		responseEntity.success("成功");
		return responseEntity;
	}

	@Override
	public ResponseEntity addChecker(String userId, String name, String subject, String phone) {
		ResponseEntity responseEntity = new ResponseEntity();
		responseEntity.success("添加成功");
		List<TbLibManager> managers = managerService.findAllByUserIdAndTypeIn(userId, new int[]{8, 11, 12, 13, 14});
		if (managers.size() == 1) {
			TbLibManager manager = managers.get(0);
			int type = manager.getType();
			if (manager.getState() == 1) {
				if (type == 8) {
					responseEntity.success("该用户已由批改老师变为质检员，添加成功");
				} else if (type == 11) {
					responseEntity.success("该用户已由学习管理员变为质检员，添加成功");
				} else if (type == 12) {
					responseEntity.success("该用户已由超级管理员变为质检员，添加成功");
				} else if (type == 13) {
					responseEntity.success("该用户已由匹配老师变为质检员，添加成功");
				} else if (type == 14) {
					responseEntity.failure("该用户已拥有质检员身份，无需再次添加！");
					return responseEntity;
				}
			}
			manager.setState(1);
			if (StringUtil.isNotBlank(name)) {
				manager.setName(name);
			}
			if (StringUtil.isNotBlank(subject)) {
				manager.setCourseName(subject);
			}
			if (StringUtil.isNotBlank(phone)) {
				manager.setTelephone(phone);
			}
			manager.setType(14);
			managerService.save(manager);
		} else if (managers.size() > 0) {
			responseEntity.failure("数据存在问题，请联系管理员");
		} else {
			User user = userService.getById(userId);
			TbLibManager manager = new TbLibManager();
			manager.setType(14);
			manager.setState(1);
			manager.setUserId(userId);
			manager.setCreateTime(new Date());
			manager.setName(name);
			manager.setCourseName(subject);
			manager.setTelephone(phone);
			manager.settPhoto(user.getPhoto());
			managerService.save(manager);
		}
		return responseEntity;
	}

	@Override
	public Map<String, Object> findUserRoleByPage(Map<String, Object> params, int pageNo, int pageSize) {
		Map<String, Object> data = new HashMap<>(16);
		com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(pageNo, pageSize);
		List<ManagerMBDto> list = correctSysMapper.findUserRoleByPage(page, params);
		data.put("list", list);
		data.put("total", (int) page.getTotal());
		return data;
	}

	@Override
	public Page<Map<String, Object>> findVipStudentList(Map<String, Object> params, Pageable initPage) {
		return userCenterQueryDao.findVipStudentList(params,initPage);
	}

	@Override
	public List<Map<String, Object>> findVipListByUserId(Map<String, Object> params) {
		return userCenterQueryDao.findVipListByUserId(params);
	}

}
