package com.ssj.sys.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.sys.train.bean.ExamInfo;
import com.ssj.bean.sys.train.bean.TrainUser;
import com.ssj.bean.sys.train.bean.VideoFile;
import com.ssj.bean.sys.train.bean.VideoInfo;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.service.sys.fx.service.MerchantService;
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 com.ssj.service.weixin.library.service.ILibJoinService;

@RequestMapping("sys/train")
@Controller
public class TrainController extends BaseController {

	@Autowired
	private ExamInfoService examInfoService;

	@Autowired
	private VideoFileService videoFileService;
	
	@Autowired
	private VideoInfoService videoInfoService;
	
	@Autowired
	private VideoUserService videoUserService;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private TrainUserService trainUserService;
	
	@Autowired
	private ILibJoinService libJoinService;
	
	
	
	
	@RequestMapping("/user/list")
	public String userList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleType", request.getParameter("roleType")==null?"1":request.getParameter("roleType"));
		params.put("mobile", request.getParameter("mobile")==null?"":request.getParameter("mobile"));
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
		params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
		
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = trainUserService.findTrainUserBySysPage(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		return "sys/train/user_list";
	}
	
	
	@RequestMapping("/user/edit")
	public String userEdit(Model model,String id)
			throws Exception {
		TrainUser trainUser=new TrainUser();
		if(StringUtils.isNotEmpty(id)) {
			trainUser=trainUserService.getById(id);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("GTE_type", "1");
	    Page<TbLibJoin> page= libJoinService.findByPage(params, initPage(1,10000,Direction.DESC, new String[] { "type" }));
		
		model.addAttribute("libJoins", page.getContent());
		model.addAttribute("trainUser",trainUser);
		return "sys/train/user_edit";
	}
	
	
	@RequestMapping("/user/save")
	@ResponseBody
	public Response userSave(TrainUser param) throws Exception{
	   	Response response = new  Response();
	   	if(StringUtils.isNotEmpty(param.getId())) {
	   		TrainUser trainUser=trainUserService.getById(param.getId());
	   		trainUser.setRoleType(param.getRoleType());
	   		trainUser.setPassword(param.getPassword());
	   		trainUser.setName(param.getName());
	   		trainUser.setLibId(param.getLibId());
	   		trainUser.setCreateTime(new Date());
	   		trainUserService.save(trainUser);
	   	}else {
	   		TrainUser trainUser=trainUserService.getTrainUserByMobile(param.getMobile());
	   		if(trainUser!=null) {
	   			response.failure("此手机号码已存在。");
	   		   	return response;
	   		}
	   		param.setStatus(1);
	   		param.setCreateTime(new Date());
	   		trainUserService.save(param);
	   	}
	   	response.success();
	   	return response;
	 }
	
	
	@RequestMapping("/user/delete")
	@ResponseBody
	public Response userDelete(String id) throws Exception{
	   	Response response = new  Response();
	   	if(StringUtils.isNotEmpty(id)) {
	   		TrainUser trainUser=trainUserService.getById(id);
	   		trainUser.setStatus(2);
	   		trainUser.setCreateTime(new Date());
	   		trainUserService.save(trainUser);
	   	}
	   	response.success();
	   	return response;
	 }
	
	
	
	
	@RequestMapping("/video/list")
	public String videoList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleType", request.getParameter("roleType")==null?"1":request.getParameter("roleType"));
		params.put("module", request.getParameter("module")==null?"":request.getParameter("module"));
		params.put("title", request.getParameter("title")==null?"":request.getParameter("title"));
		params.put("index", request.getParameter("index")==null?"":request.getParameter("index"));
		
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = videoInfoService.findTrainVideoInfoByPage(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		return "sys/train/video_list";
	}
	
	
	@RequestMapping("/video/edit")
	public String videoEdit(Model model,String id)
			throws Exception {
		VideoInfo videoInfo=new VideoInfo();
		if(StringUtils.isNotEmpty(id)) {
			videoInfo=videoInfoService.getById(id);
		}
		model.addAttribute("videoInfo",videoInfo);
		return "sys/train/video_edit";
	}
	
	


	 @RequestMapping("/video/save")
	 @ResponseBody
	 public Response videoSave(VideoInfo param) throws Exception{
    	Response response = new  Response();
    	if(StringUtils.isNotEmpty(param.getId())) {
	    	VideoInfo videoInfo=videoInfoService.getById(param.getId());
	    	videoInfo.setDescription(param.getDescription());
	    	videoInfo.setModule(param.getModule());
	    	videoInfo.setRoleType(param.getRoleType());
	    	videoInfo.setStatus(param.getStatus());
	    	videoInfo.setTitle(param.getTitle());
	    	videoInfo.setUrl(param.getUrl());
	    	videoInfo.setUpdateTime(new Date());
	    	videoInfoService.save(videoInfo);
    	}else {
    		Integer indes=1;
    		VideoInfo maxVideoInfo=videoInfoService.getVideoInfoByMaxIndes(param.getRoleType());
    		if(maxVideoInfo!=null) {
    			indes=maxVideoInfo.getIndes()+1;
    		}
    		param.setIndes(indes);
    		param.setCreateTime(new Date());
    		videoInfoService.save(param);
    	}
    	response.success();
    	return response;
	 }
	 
	 
	 @RequestMapping("/video/indes/update")
	 @ResponseBody
	 public Response videoIndesUpdate(Model model,String id,Integer indes) throws Exception{
    	Response response = new  Response();
    	if(StringUtils.isNotEmpty(id)) {
	    	VideoInfo videoInfo=videoInfoService.getById(id);
	    	VideoInfo indesVideoInfo=videoInfoService.getVideoInfoByIndes(videoInfo.getRoleType(), indes);
	    	if(indesVideoInfo!=null) {
	    		response.failure("排序号，同端下不可重复喔，请重新填写。");
	    		return response;
	    	}
	    	videoInfo.setIndes(indes);
	    	videoInfoService.save(videoInfo);
    	}
    	response.success();
    	return response;
	 }
	
	
	@RequestMapping("/pace/list")
	public String paceList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception { 
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
		params.put("id",merchant!=null ? merchant.getId() : "无权限");
		
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = videoInfoService.findMerchantTeaNumByPage(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
        for (Map<String, Object> pageMap : list) {
        	Map<String, Object> map=videoUserService.findTrainVideoUserByPage(pageMap);
        	pageMap.putAll(map);
		}
        
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		
		return "sys/train/pace_list";
	}
	
	
	
	@RequestMapping("/pace/list/info")
	public String paceListInfo(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception { 
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
		params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
		params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
		
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = videoUserService.findTeaInfoNumByPage(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();

        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

		return "sys/train/pace_list_info";
	}
	
	
	
	@RequestMapping("/import/exam/info")
	@ResponseBody
    public Response importDeviceData(HttpServletRequest request, 
    		@RequestParam("file") MultipartFile file,String videoId)
    				throws Exception {
		Response response = new  Response();
		try {
			VideoInfo videoInfo=videoInfoService.getById(videoId);
			List<ExamInfo> oldExamInfos=examInfoService.findExamInfoByVideoId(videoId);
			List<Map<String,String>> datas=ImLibUserController.analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<ExamInfo> examInfos=new ArrayList<ExamInfo>();
				ExamInfo examInfo=null;
				for (Map<String,String> map : datas) {
					examInfo=new ExamInfo();
					examInfo.setRoleType(videoInfo.getRoleType());
					examInfo.setVideoId(videoInfo.getId());
					examInfo.setExamNum(Integer.valueOf(map.get("data_0")));
					examInfo.setExamType(Integer.valueOf(map.get("data_1")));
					examInfo.setTitle(map.get("data_2"));
					examInfo.setOptions(map.get("data_3").trim().replaceAll("\\n", ""));
					examInfo.setAnswer(map.get("data_4").trim().replaceAll("\\n", ""));
					examInfo.setScore(Integer.valueOf(map.get("data_5").trim()));
					examInfo.setStatus(1);
					if(map.containsKey("data_6") && StringUtils.isNotEmpty(map.get("data_6"))) {
						examInfo.setId(map.get("data_6"));
					}
					examInfo.setCreateTime(new Date());
					examInfos.add(examInfo);
				}
				examInfoService.save(examInfos);
			}
			if(oldExamInfos!=null && oldExamInfos.size()>0){
				for (ExamInfo examInfo : oldExamInfos) {
					examInfo.setStatus(2);
				}
				examInfoService.save(oldExamInfos);
			}
			response.success();
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
    }
	
	public static void main(String[] args) {
		
		
		
	}
	
	
	@RequestMapping("/file/list")
	public String fileList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
		params.put("roleType", request.getParameter("roleType")==null?"":request.getParameter("roleType"));
		params.put("module", request.getParameter("module")==null?"":request.getParameter("module"));
		params.put("title", request.getParameter("title")==null?"":request.getParameter("title"));
		
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = videoFileService.findVideoFileBySysPage(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		return "sys/train/file_list";
	}
	
	
	@RequestMapping("/file/edit")
	public String fileEdit(Model model,String id)
			throws Exception {
		VideoFile videoFile=new VideoFile();
		if(StringUtils.isNotEmpty(id)) {
			videoFile=videoFileService.getById(id);
		}
		model.addAttribute("videoFile",videoFile);
		return "sys/train/file_edit";
	}
	

	 @RequestMapping("/file/save")
	 @ResponseBody
	 public Response fileSave(VideoFile param) throws Exception{
    	Response response = new  Response();
    	if(StringUtils.isNotEmpty(param.getId())) {
    		VideoFile videoFile=videoFileService.getById(param.getId());
    		videoFile.setModule(param.getModule());
    		videoFile.setType(param.getType());
    		videoFile.setRoleType(param.getRoleType());
    		videoFile.setStatus(param.getStatus());
    		videoFile.setTitle(param.getTitle());
    		videoFile.setFormat(param.getFormat());
    		videoFile.setUrl(param.getUrl());
    		videoFile.setUpdateTime(new Date());
    		videoFileService.save(videoFile);
    	}else {
    		param.setCreateTime(new Date());
    		videoFileService.save(param);
    	}
    	response.success();
    	return response;
	 }
	
	
	
	
	
}
