package com.ssj.api.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ssj.api.domain.model.RoleTypeModel;
import com.ssj.api.domain.vo.train.TrainExamUserSaveVo;
import com.ssj.api.domain.vo.train.TrainExamVo;
import com.ssj.api.domain.vo.train.TrainLoginVo;
import com.ssj.api.domain.vo.train.TrainVideoFileVo;
import com.ssj.api.domain.vo.train.TrainVideoVo;
import com.ssj.api.security.annotation.IgnoreSecurity;
import com.ssj.bean.sys.train.bean.ExamInfo;
import com.ssj.bean.sys.train.bean.TrainUser;
import com.ssj.bean.sys.train.bean.VideoInfo;
import com.ssj.bean.sys.train.bean.VideoUser;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.CodecUtil;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.sys.train.service.ExamInfoService;
import com.ssj.service.sys.train.service.TrainUserService;
import com.ssj.service.sys.train.service.VideoFileService;
import com.ssj.service.sys.train.service.VideoInfoService;
import com.ssj.service.sys.train.service.VideoUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * 类描述: 培训系统
 * 创建时间:2020年8月7日9:34:18
 */
@Api(value = "培训系统", tags = "培训系统")
@RestController
@RequestMapping("/api/train")
public class ApiTrainController extends BaseController {
	
	@Autowired
    private VideoUserService videoUserService;
	
	@Autowired
    private VideoInfoService videoInfoService;
	
	@Autowired
    private VideoFileService videoFileService;
	
	@Autowired
    private ExamInfoService examInfoService;
	
	@Autowired
    private TrainUserService trainUserService;
	

	private static List<RoleTypeModel> defaultRoleTypeModels=new ArrayList<RoleTypeModel>();
	private static List<String> defaultRoleTypeNames=new ArrayList<String>();
	static {
		defaultRoleTypeNames.add("校长端");
		defaultRoleTypeNames.add("老师端");
		defaultRoleTypeNames.add("家长端");
		defaultRoleTypeNames.add("学生端");
		
		RoleTypeModel roleTypeModel1=new RoleTypeModel();
		roleTypeModel1.setRoleType(1);
		roleTypeModel1.setRoleName(defaultRoleTypeNames.get(0));
		roleTypeModel1.setUnlock(0);
		roleTypeModel1.setUnlockAll(0);
		roleTypeModel1.setModules(new String[] {"主要功能","其它功能"});
		defaultRoleTypeModels.add(roleTypeModel1);
		
		RoleTypeModel roleTypeModel2=new RoleTypeModel();
		roleTypeModel2.setRoleType(2);
		roleTypeModel2.setRoleName(defaultRoleTypeNames.get(1));
		roleTypeModel2.setUnlock(0);
		roleTypeModel1.setUnlockAll(0);
		roleTypeModel2.setModules(new String[] {"现场管理","作业标注","学科答疑"});
		defaultRoleTypeModels.add(roleTypeModel2);
		
		
		RoleTypeModel roleTypeModel3=new RoleTypeModel();
		roleTypeModel3.setRoleType(3);
		roleTypeModel3.setRoleName(defaultRoleTypeNames.get(2));
		roleTypeModel3.setUnlock(0);
		roleTypeModel1.setUnlockAll(0);
		roleTypeModel3.setModules(new String[] {});
		defaultRoleTypeModels.add(roleTypeModel3);
		
		RoleTypeModel roleTypeModel4=new RoleTypeModel();
		roleTypeModel4.setRoleType(4);
		roleTypeModel4.setRoleName(defaultRoleTypeNames.get(3));
		roleTypeModel4.setUnlock(0);
		roleTypeModel1.setUnlockAll(0);
		roleTypeModel4.setModules(new String[] {});
		defaultRoleTypeModels.add(roleTypeModel4);
		
	}
	
	
	private Map<String, Object> getTrainVideoUserMap(Integer roleType,List<Map<String,Object>> list){
		for (Map<String, Object> map : list) {
			if(roleType==(int)map.get("role_type")) {
				return map;
			}
		}
		return null;
	}
	

	@IgnoreSecurity
	@RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "账号密码登录接口", httpMethod = "POST",  notes = "账号密码登录接口")
    public ResponseEntity login(@RequestParam(name = "accessToken") String accessToken,
    		@RequestBody TrainLoginVo requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data=new HashMap<String, Object>();
        try {
            TrainUser phoneUser = trainUserService.getTrainUserByMobile(requestVO.getLoginName());
            if (phoneUser == null) {
                responseEntity.failure(ResponseConstant.CODE_000, "账号无效");
                return responseEntity;
            }
            TrainUser user = trainUserService.login(requestVO.getLoginName(), requestVO.getPassword());
            if (user == null) {
            	responseEntity.failure("密码错误");
                return responseEntity;
            }

            data.put("userId", user.getId());
            data.put("name", StringUtils.isNotEmpty(user.getName())? user.getName(): "");
            data.put("photo", StringUtils.isNotEmpty(user.getPhoto())? user.getPhoto(): "");
            data.put("accessToken", getAccessToken(user.getId(),CodecUtil.createUUID()));
            responseEntity.success(data, "账号密码登录成功");
        } catch (Exception e) {
            logger.error("账号密码登录接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	
	@RequestMapping(value = "/auths")
    @ApiOperation(value = "学习中心-学习内容列表",   notes = "学习中心-学习内容列表")
    public ResponseEntity auths(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data=new HashMap<String, Object>();
        try {
            String userId = tokenManager.getUserId(accessToken);
            TrainUser tbLibManager = trainUserService.getById(userId);
            if(tbLibManager==null) {
            	responseEntity.failure("账号无身份权限");
                return responseEntity;
            }
            List<Map<String,Object>> list=videoUserService.findTrainVideoUserByUserId(userId);
            //是校长
            if(tbLibManager.getRoleType()==1) {
            	defaultRoleTypeModels.get(0).setUnlock(1);
            	
            	Map<String, Object> dataMap1=getTrainVideoUserMap(1, list);
            	if(dataMap1!=null && Integer.parseInt(dataMap1.get("success_num").toString())>=Integer.parseInt(dataMap1.get("count_num").toString())) {
            		defaultRoleTypeModels.get(1).setUnlock(1);
            		defaultRoleTypeModels.get(0).setUnlockAll(1);
            	}
            }else {
            	defaultRoleTypeModels.get(0).setUnlock(0);
            	defaultRoleTypeModels.get(0).setUnlockAll(0);
            	
            	defaultRoleTypeModels.get(1).setUnlock(1);
            }
            
            Map<String, Object> dataMap2=getTrainVideoUserMap(2, list);
        	if(dataMap2!=null && Integer.parseInt(dataMap2.get("success_num").toString())>=Integer.parseInt(dataMap2.get("count_num").toString())) {
        		defaultRoleTypeModels.get(2).setUnlock(1);
        		defaultRoleTypeModels.get(1).setUnlockAll(1);
        	}
           
        	Map<String, Object> dataMap3=getTrainVideoUserMap(3, list);
         	if(dataMap3!=null && Integer.parseInt(dataMap3.get("success_num").toString())>=Integer.parseInt(dataMap3.get("count_num").toString())) {
         		defaultRoleTypeModels.get(3).setUnlock(1);
         		defaultRoleTypeModels.get(2).setUnlockAll(1);
         	}
         	
         	Map<String, Object> dataMap4=getTrainVideoUserMap(4, list);
         	if(dataMap4!=null && Integer.parseInt(dataMap4.get("success_num").toString())>=Integer.parseInt(dataMap4.get("count_num").toString())) {
         		defaultRoleTypeModels.get(3).setUnlockAll(1);
         	}

            data.put("roleTypes", defaultRoleTypeModels);
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-选择身份接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	@RequestMapping(value = "/home")
    @ApiOperation(value = "学习中心-选择身份接口",   notes = "学习中心-选择身份接口")
    public ResponseEntity home(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
        try {
            String userId = tokenManager.getUserId(accessToken);
            TrainUser tbLibManager = trainUserService.getById(userId);
            if(tbLibManager==null) {
            	responseEntity.failure("账号无身份权限");
                return responseEntity;
            }
            List<Map<String,Object>> list=videoUserService.findTrainVideoUserByUserId(userId);
            
            Map<String, Object> map1=new HashMap<String, Object>();
            Map<String, Object> dataMap1=getTrainVideoUserMap(1, list);
            map1.put("roleType", 1);
            map1.put("roleName", defaultRoleTypeNames.get(0));
            //校长才显示校长端
            if(tbLibManager.getRoleType()==1) {
            	map1.put("successNum", dataMap1!=null ? Integer.parseInt(dataMap1.get("success_num").toString()):0);
            	map1.put("countNum", dataMap1!=null ? Integer.parseInt(dataMap1.get("count_num").toString()):0);
            	map1.put("unlock", 1);
            }else {
            	map1.put("successNum", 0);
            	map1.put("countNum", 0);
            	map1.put("unlock", 0);
            }
            data.add(map1);
            
            Map<String, Object> map2=new HashMap<String, Object>();
            Map<String, Object> dataMap2=getTrainVideoUserMap(2, list);
            map2.put("roleType", 2);
            map2.put("roleName", defaultRoleTypeNames.get(1));
            map2.put("successNum", dataMap2!=null ? Integer.parseInt(dataMap2.get("success_num").toString()):0);
            map2.put("countNum", dataMap2!=null ? Integer.parseInt(dataMap2.get("count_num").toString()):0);
            map2.put("unlock", (int)map1.get("successNum")>=(int)map1.get("countNum")?1:0);
            data.add(map2);
            
            Map<String, Object> map3=new HashMap<String, Object>();
            Map<String, Object> dataMap3=getTrainVideoUserMap(3, list);
            map3.put("roleType", 3);
            map3.put("roleName", defaultRoleTypeNames.get(2));
            map3.put("successNum", dataMap3!=null ? Integer.parseInt(dataMap3.get("success_num").toString()):0);
            map3.put("countNum", dataMap3!=null ? Integer.parseInt(dataMap3.get("count_num").toString()):0);
            map3.put("unlock", (int)map2.get("successNum")>=(int)map2.get("countNum")?1:0);
            data.add(map3);
            
            Map<String, Object> map4=new HashMap<String, Object>();
            Map<String, Object> dataMap4=getTrainVideoUserMap(4, list);
            map4.put("roleType", 4);
            map4.put("roleName", defaultRoleTypeNames.get(3));
            map4.put("successNum", dataMap4!=null ? Integer.parseInt(dataMap4.get("success_num").toString()):0);
            map4.put("countNum", dataMap4!=null ? Integer.parseInt(dataMap4.get("count_num").toString()):0);
            map4.put("unlock", (int)map3.get("successNum")>=(int)map3.get("countNum")?1:0);
            data.add(map4);
            
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-选择身份接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	
	@RequestMapping(value = "/video")
    @ApiOperation(value = "学习中心-视频学习内容",   notes = "学习中心-视频学习内容")
    public ResponseEntity video(@RequestParam(name = "accessToken") String accessToken,
    		@RequestBody TrainVideoVo requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
        try {
            String userId = tokenManager.getUserId(accessToken);
            
            List<Map<String, Object>> list=videoInfoService.findTrainVideoUserByRoleType(userId, requestVO.getRoleType(), requestVO.getModule());
            Map<String, Object> dataMap=null;
            for (Map<String, Object> map : list) {
            	int index=list.indexOf(map);
            	dataMap=new HashMap<String, Object>();
            	dataMap.put("id", map.get("id"));
            	dataMap.put("roleType", map.get("role_type"));
            	dataMap.put("module", map.get("module"));
            	dataMap.put("title", map.get("title"));
            	dataMap.put("description", map.get("description"));
            	dataMap.put("url", map.get("url"));
            	dataMap.put("roleName", defaultRoleTypeNames.get(Integer.parseInt(map.get("role_type").toString())-1));
            	
            	List<VideoUser> videoUsers=videoUserService.findVideoUserByUserIdAndVideoId(map.get("id").toString(), userId);
            	if(videoUsers!=null && videoUsers.size()>0) {
            		dataMap.put("status", 1);
            	}else {
            		dataMap.put("status", 0);
            	}
            	
            	VideoInfo maxVideoInfo=videoInfoService.getVideoInfoByMax(requestVO.getRoleType(), map.get("id").toString());
            	if(maxVideoInfo!=null) {
            		dataMap.put("type", 0);
            	}else {
            		dataMap.put("type", 1);
            	}
            	if(index<=0) {
            		dataMap.put("unlock", 1);
            	}else {
					if(Integer.parseInt(list.get(index-1).get("un_lock").toString())>0) {
						dataMap.put("unlock", 1);
					}else {
						dataMap.put("unlock", 0);
					}
            	}
				data.add(dataMap);
			}
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-视频学习内容接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }

	
	
	@RequestMapping(value = "/exam")
    @ApiOperation(value = "学习中心-考核测试题目",   notes = "学习中心-考核测试题目")
    public ResponseEntity exam(@RequestParam(name = "accessToken") String accessToken,
    		@RequestBody TrainExamVo requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
        try {
            List<ExamInfo> examInfos=examInfoService.findExamInfoByVideoId(requestVO.getVideoId());
            Map<String, Object> dataMap=null;
            for (ExamInfo examInfo : examInfos) {
            	dataMap=new HashMap<String, Object>();
            	dataMap.put("id", examInfo.getId());
            	dataMap.put("examNum", examInfo.getExamNum());
            	dataMap.put("examType", examInfo.getExamType());
            	dataMap.put("title", examInfo.getTitle());
            	dataMap.put("options", StringUtils.isNotEmpty(examInfo.getOptions())? examInfo.getOptions().split(";") : "");
            	dataMap.put("answer", StringUtils.isNotEmpty(examInfo.getAnswer())? examInfo.getAnswer().split(";") : "");
            	dataMap.put("score", examInfo.getScore());
            	data.add(dataMap);
			}
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-考核测试题目接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	
	
	@RequestMapping(value = "/exam/user/save")
    @ApiOperation(value = "学习中心-考核测试答案提交",   notes = "学习中心-考核测试答案提交")
    public ResponseEntity examUserSave(@RequestParam(name = "accessToken") String accessToken,
    		@RequestBody TrainExamUserSaveVo requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        if(requestVO.getScore()==null || requestVO.getScore()<0) {
        	 responseEntity.failure("分数不可小于0");
        	 return responseEntity;
        }
        if(StringUtils.isEmpty(requestVO.getVideoId())) {
       	 	responseEntity.failure("视频id不可为空");
       	 	return responseEntity;
        }
        try {
        	String userId = tokenManager.getUserId(accessToken);
        	VideoInfo videoInfo=videoInfoService.getById(requestVO.getVideoId());
        	VideoInfo maxVideoInfo=videoInfoService.getVideoInfoByMax(videoInfo.getRoleType(), videoInfo.getId());
        	//不是最后一个视频，不做其它处理，直接解锁。
        	if(maxVideoInfo!=null) {
        		VideoUser videoUser=new VideoUser();
        		videoUser.setVideoId(videoInfo.getId());
        		videoUser.setUserId(userId);
        		videoUser.setRoleType(videoInfo.getRoleType());
        		videoUser.setModule(videoInfo.getModule());
        		videoUser.setAnswerRecord(requestVO.getAnswer());
        		videoUser.setScore(requestVO.getScore());
        		videoUser.setStatus(1);
        		videoUser.setCreateTime(new Date());
        		videoUserService.save(videoUser);
        	}else {
        		//如果不够90，重新锁定RoleType的视频。
        		VideoUser videoUser=new VideoUser();
        		videoUser.setVideoId(videoInfo.getId());
        		videoUser.setUserId(userId);
        		videoUser.setRoleType(videoInfo.getRoleType());
        		videoUser.setModule(videoInfo.getModule());
        		videoUser.setAnswerRecord(requestVO.getAnswer());
        		videoUser.setScore(requestVO.getScore());
        		videoUser.setCreateTime(new Date());
        		if(requestVO.getScore()<90) {
        			videoUser.setStatus(0);
        		}else {
        			videoUser.setStatus(1);
        		}
        		videoUserService.save(videoUser);
        		
        		if(requestVO.getScore()<90) {
	        		List<VideoUser> videoUsers=videoUserService.findVideoUserByUserIdAndRoleType(videoInfo.getRoleType(), userId);
	        		if(videoUsers!=null && videoUsers.size()>0) {
	        			for (VideoUser video : videoUsers) {
	        				video.setStatus(0);
	        			}
	        			videoUserService.save(videoUsers);
	        		}
        		}
        	}
            responseEntity.success("保存成功");
        } catch (Exception e) {
            logger.error("学习中心-考核测试答案提交接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	
	@RequestMapping(value = "/file")
    @ApiOperation(value = "资料下载-资料列表",   notes = "资料下载-资料列表")
    public ResponseEntity file(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
        try {
            List<Map<String, Object>> videoFiles=videoFileService.findVideoFileByType();
            Map<String, Object> dataMap=null;
            for (Map<String, Object> map : videoFiles) {
            	dataMap=new HashMap<String, Object>();
            	dataMap.put("roleType", map.get("role_type"));
            	dataMap.put("roleName", defaultRoleTypeNames.get(Integer.parseInt(map.get("role_type").toString())-1));
            	dataMap.put("name", defaultRoleTypeNames.get(Integer.parseInt(map.get("role_type").toString())-1)+"学习资料");
            	dataMap.put("num", map.get("num"));
            	dataMap.put("url", map.get("url"));
            	data.add(dataMap);
			}
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-考核测试题目接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
	
	@RequestMapping(value = "/file/info")
    @ApiOperation(value = "资料下载-资料明细列表",   notes = "资料下载-资料明细列表")
    public ResponseEntity fileInfo(@RequestParam(name = "accessToken") String accessToken,
    		@RequestBody TrainVideoFileVo requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data=new HashMap<String, Object>();
        List< Map<String, Object>> list=new ArrayList<Map<String,Object>>();
        try {
        	Map<String, Object> params = new HashMap<String, Object>();
    		params.put("roleType", requestVO.getRoleType());
    		params.put("module", requestVO.getModule());
    		params.put("name", requestVO.getName());
    		params.put("type",2);
    		
            Page<Map<String,Object>> page = videoFileService.findVideoFileByPage(params, initPage(requestVO.getPageNo(), requestVO.getPageSize()));
            List<Map<String,Object>> videoFiles=page.getContent();
            Map<String, Object> dataMap=null;
        	SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy.MM.dd");
            for (Map<String, Object> map : videoFiles) {
            	dataMap=new HashMap<String, Object>();
            	dataMap.put("roleType", map.get("role_type"));
            	dataMap.put("roleName", defaultRoleTypeNames.get(Integer.parseInt(map.get("role_type").toString())-1));
            	dataMap.put("name", map.get("title"));
            	dataMap.put("module", map.get("module"));
            	dataMap.put("format", map.get("format"));
            	dataMap.put("url", map.get("url"));
            	dataMap.put("createTime", formatter2.format(formatter1.parse(map.get("create_time").toString())));
            	list.add(dataMap);
			}
            data.put("pages", page.getTotalPages());
            data.put("totals", Integer.parseInt(page.getTotalElements()+""));
            data.put("pageNo", requestVO.getPageNo());
            data.put("pageSize", requestVO.getPageSize());
            data.put("list", list);
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("学习中心-考核测试题目接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
	
	
}