package com.ssj.sys.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.problem.domain.RequestMethodLog;
import com.ssj.framework.core.util.WebUtil;
import com.ssj.service.weixin.problem.service.RequestMethodLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.*;
import org.springframework.web.multipart.MultipartFile;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.imlibuser.TbClassStudent;
import com.ssj.bean.sys.imlibuser.TbClassStudentTemp;
import com.ssj.bean.sys.imlibuser.TbClassTeacher;
import com.ssj.bean.sys.imlibuser.TbClassTeacherTemp;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.conch.common.service.ConchCommonService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.imlibuser.service.TbClassStudentService;
import com.ssj.service.sys.imlibuser.service.TbClassStudentTempService;
import com.ssj.service.sys.imlibuser.service.TbClassTeacherService;
import com.ssj.service.sys.imlibuser.service.TbClassTeacherTempService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibJoinConsumeService;
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.UserService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;


/**
 * 倒入老师和学员
 * 2019年10月29日10:55:14
 *
 */
@RequestMapping("sys/imlibuser")
@Controller
public class ImLibUserController extends BaseController {

	@Autowired
    private TbClassStudentService tbLibImStudentService;
	
	@Autowired
    private TbClassStudentTempService tbLibImStudentTempService;
	
	@Autowired
    private TbClassTeacherService tbLibImTeacherService;
	
	@Autowired
    private TbClassTeacherTempService tbLibImTeacherTempService;
	
	@Autowired
    private ConchCommonService conchCommonService;
	
	@Autowired
 	private ILibJoinService joinService;    
	
	@Autowired
	private LibVipServiceService libVipServiceService;   
	
	@Autowired
	private ILibVipService libVipService;
	
	@Autowired
    private IBookManagerService managerService;
	
	@Autowired
    private UserService userService;
	
	@Autowired
    private EasemobService easemobService;
	
	@Autowired
    private TbClassStudentService tbClassStudentService;
	
	@Autowired
    private TbClassTeacherService tbClassTeacherService;
	
	@Autowired
	private IBookManagerService bookManagerService;

	@Autowired
 	private ILibJoinConsumeService joinConsumeService;

	@Autowired
	private RequestMethodLogService requestMethodLogService;
	
	/**
	 * ----------------机构相关功能-----------------------
	 */
	
	//机构首页
	@RequestMapping(value="/school/list")
	public String index(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("leagueNname", request.getParameter("leagueNname")==null?"":request.getParameter("leagueNname"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        
        Page<Map<String,Object>> page = tbLibImStudentService.findLibImByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		return "sys/imlibuser/schoolList";
	}
	
	
	
	@RequestMapping(value="/school/exlist")
    @ResponseBody
    public void exportSchool( HttpServletRequest request, HttpServletResponse response) {  
    	ServletOutputStream os = null;
    	try { 
    	
			String libName="校区列表_明细表";
    		os = response.getOutputStream(); //获得输出流  
    		response.reset();   //清空输出流  
    		String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";  
    		response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
    		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    		response.setCharacterEncoding("utf-8");
    		
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("leagueNname", request.getParameter("leagueNname")==null?"":request.getParameter("leagueNname"));
            SplitPage sp = new SplitPage();
            sp.setAction(request.getRequestURI());
            sp.setPageNo(1);
            sp.setPageSize(10000);
            sp.setParams(params);
            
            Page<Map<String,Object>> page = tbLibImStudentService.findLibImByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"create_time"}));
            List<Map<String,Object>> list= page.getContent();
            
 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("校区名称", "league_name", 20));
    		myColumns3.add(new ExcelColumn("校区服务学币", "lib_service", 20));
    		myColumns3.add(new ExcelColumn("平台服务学币", "platform_service", 20));
    		myColumns3.add(new ExcelColumn("端口", "port_num", 20));
    		myColumns3.add(new ExcelColumn("老师人数", "teacher_num", 20));
    		myColumns3.add(new ExcelColumn("学生人数", "student_num", 20));

	    	CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {
			logger.error("异常", e);
    	}catch (Exception e1){
			logger.error("异常", e1);
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
					logger.error("异常", e);
    			}  
    		}
    	}
    } 
	
	
	
	
	
	/**
	 * ----------------学生相关功能-----------------------
	 */
	
	
	//学生导入
	@RequestMapping(value="/student/import")
	@ResponseBody
	public Response studentImport(Model model,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<TbClassStudentTemp> tbLibImStudentTemps=new ArrayList<TbClassStudentTemp>();
				TbClassStudentTemp tbLibImStudentTemp=null;
				boolean iserror=false;
				
				for (Map<String, String> map : datas) {
					tbLibImStudentTemp=new TbClassStudentTemp();
					tbLibImStudentTemp.setLeagueName(map.get("data_0"));
					tbLibImStudentTemp.setSchool(map.get("data_1"));
					tbLibImStudentTemp.setGrade(map.get("data_2"));
					tbLibImStudentTemp.setClassName(map.get("data_3"));
					
					tbLibImStudentTemp.setStudentName(map.get("data_4"));
					
					tbLibImStudentTemp.setParentName(map.get("data_5"));
					tbLibImStudentTemp.setParentPhone(map.get("data_6"));
					tbLibImStudentTemp.setParentRole(map.get("data_7"));
					
					if(map.containsKey("data_8")){
						tbLibImStudentTemp.setViceParentName(map.get("data_8"));
					}
					if(map.containsKey("data_9")){
						tbLibImStudentTemp.setViceParentPhone(map.get("data_9"));
					}
					if(map.containsKey("data_10")){
						tbLibImStudentTemp.setViceParentRole(map.get("data_10"));
					}
					
					
					if(map.containsKey("data_11")){
						tbLibImStudentTemp.setDerver(map.get("data_11"));
					}
					
					tbLibImStudentTemps.add(tbLibImStudentTemp);
					
					if(StringUtils.isEmpty(tbLibImStudentTemp.getSchool())){
						response.failure("学校名称不能为空");
						iserror=true;
						break;
					}
//					if(StringUtils.isEmpty(tbLibImStudentTemp.getGrade())){
//						response.failure("年级不能为空");
//						iserror=true;
//						break;
//					}
					if(StringUtils.isEmpty(tbLibImStudentTemp.getLeagueName())){
						response.failure("机构不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImStudentTemp.getStudentName())){
						response.failure("学生姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImStudentTemp.getParentName())){
						response.failure("主家长姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImStudentTemp.getParentRole())){
						response.failure("主家长角色不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImStudentTemp.getParentPhone()) || tbLibImStudentTemp.getParentPhone().length()!=11){
						response.failure("主家长电话不正确");
						iserror=true;
						break;
					}
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getViceParentName())) {
						if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentPhone())){
							response.failure("副家长电话不正确");
							iserror=true;
							break;
						}else if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentRole())){
							response.failure("副家长角色不正确");
							iserror=true;
							break;
						}
					}
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getViceParentPhone())) {
						if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentName())){
							response.failure("副家长姓名不正确");
							iserror=true;
							break;
						}else if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentRole())){
							response.failure("副家长角色不正确");
							iserror=true;
							break;
						}
					}
					if(StringUtils.isNotEmpty(tbLibImStudentTemp.getViceParentRole())) {
						if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentName())){
							response.failure("副家长姓名不正确");
							iserror=true;
							break;
						}else if(StringUtils.isEmpty(tbLibImStudentTemp.getViceParentPhone())){
							response.failure("副家长电话不正确");
							iserror=true;
							break;
						}
					}
				}
				if(!iserror){
					int successNum=tbLibImStudentTempService.insertBatchTbClassStudent(tbLibImStudentTemps);
					if(successNum<0){
						response.failure("机构数据为空，请检查机构是否存在！");
					}else if(tbLibImStudentTemps.size()!=successNum) {
						response.failure("存在导入失败数据，请查看失败列表！");
					}else{
						response.success("成功");
					}
				}
			}
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
	}	

	
	//学生列表
	@RequestMapping(value="/student/list/{libId}")
	public String studentList(Model model,@PathVariable String libId,
            @RequestParam(required = false, defaultValue = "10") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("libId", libId);
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImStudentService.findStudentByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        List<Map<String,Object>> list =page.getContent();
        for (Map<String, Object> map : list) {
        	List<LibVipService> libVipServices=libVipServiceService.findValidService(map.getOrDefault("id","").toString(), "S003");
        	if(libVipServices!=null && libVipServices.size()>=1){
        		map.put("libVipService", libVipServices.get(0));
        	}else{
        		libVipServices=libVipServiceService.findValidService(map.getOrDefault("id","").toString(), "S999");
        		if(libVipServices!=null && libVipServices.size()>=1){
            		map.put("libVipService", libVipServices.get(0));
            	}else{
            		map.put("libVipService",new LibVipService());
            	}
        	}
		}
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		
		TbLibJoin tbLibJoin=joinService.getById(libId);
		model.addAttribute("tbLibJoin", tbLibJoin);
		return "sys/imlibuser/studentList";
	}
	//流失学生列表
	@RequestMapping(value="/invalidStudent/list/{libId}")
	public String invalidStudent(Model model,@PathVariable String libId,
            @RequestParam(required = false, defaultValue = "10") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("libId", libId);
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImStudentService.findInvalidStudentByPage(params, initPage(pageNo, pageSize));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

		TbLibJoin tbLibJoin=joinService.getById(libId);
		model.addAttribute("tbLibJoin", tbLibJoin);
		return "sys/imlibuser/invalidStudentList";
	}

	@RequestMapping(value = "/student/addChildBack", method = RequestMethod.POST)
	@ResponseBody
	public Response addChildBack(String libId, String vipId){
		Response response = new Response();
		try {
			response = tbLibImStudentService.addChildBack(libId,vipId);
		}catch (Exception e){
			response.failure("重启学生服务失败");
		}

		return  response;
	}
	@RequestMapping(value = "/student/delStudent", method = RequestMethod.POST)
	@ResponseBody
	public Response delStudent(String libId, String vipId){
		Response response = new Response();
		try {
			response = tbLibImStudentService.delStudent(libId,vipId);
		}catch (Exception e){
			response.failure("删除学生发生异常");
		}

		return  response;
	}

	@RequestMapping(value = "/updateSortNo", method = RequestMethod.POST)
	@ResponseBody
	public Response updateSortNo(String id, String phone){
		Response response = new  Response();
		User user = userService.findByMobile(phone);
		if(user !=null){
			response.failure("平台已经存在"+phone+"的用户！");
			return response;
		}
		LibVip vip = libVipService.getById(id);
		if(vip!=null){
			String oldPhone = vip.getPhone();
			vip.setPhone(phone);
			libVipService.save(vip);
			User parentUser = userService.getById(vip.getUserId());
			if(parentUser!=null){
				parentUser.setMobile(phone);
				userService.save(parentUser);
			}
			recodeData(vip.getUserId(),phone,oldPhone,id);
		}
		response.success();
		return response;
	}

	private  void recodeData(String userId,String phone,String oldPhone, String vipId){
		Admin admin= (Admin) request.getSession().getAttribute("admin");
		if(admin !=null) {
			RequestMethodLog methodLog = new RequestMethodLog();
			methodLog.setAccountName(admin.getLoginName());
			methodLog.setMethodUrl("imlibuser/updateSortNo");
			methodLog.setMethodName("修改用户手机号码");
			methodLog.setIpAddress(WebUtil.getRemoteAddr(request));
			// methodLog.setOrgCode(admin.getOrgCode());
			methodLog.setCreateTime(new Date());
			methodLog.setSubstance("vipId->"+vipId+"-userId->"+userId+"-原手机号码->"+oldPhone+"修改为-"+phone);
			requestMethodLogService.save(methodLog);
		}
	}
	
	@RequestMapping(value="/student/exlist/{libId}")
    @ResponseBody
    public void exportStudent(@PathVariable String libId,HttpServletRequest request, HttpServletResponse response) {  
    	ServletOutputStream os = null;
    	try { 
    		TbLibJoin libJoin=joinService.getById(libId);
			String libName=libJoin.getLeagueName()+"_学生列表";
    		os = response.getOutputStream(); //获得输出流  
    		response.reset();   //清空输出流  
    		String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";  
    		response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
    		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    		response.setCharacterEncoding("utf-8");
    		
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("libId", libId);
    		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
            SplitPage sp = new SplitPage();
            sp.setAction(request.getRequestURI());
            sp.setPageNo(1);
            sp.setPageSize(10000);
            sp.setParams(params);
            Page<Map<String,Object>> page = tbLibImStudentService.findStudentByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"create_time"}));
            List<Map<String,Object>> list =page.getContent();
            for (Map<String, Object> map : list) {
            	List<LibVipService> libVipServices=libVipServiceService.findValidService(map.getOrDefault("id","").toString(), "S003");
            	if(libVipServices!=null && libVipServices.size()>=1){
            		map.put("libVipService", libVipServices.get(0));
            	}else{
            		libVipServices=libVipServiceService.findValidService(map.getOrDefault("id","").toString(), "S999");
            		if(libVipServices!=null && libVipServices.size()>=1){
                		map.put("libVipService", libVipServices.get(0));
                	}else{
                		map.put("libVipService",new LibVipService());
                	}
            	}
    		}
            
 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("学生姓名", "child_name", 20));
    		myColumns3.add(new ExcelColumn("学校", "school", 20));
    		myColumns3.add(new ExcelColumn("年级", "grade", 20));
    		myColumns3.add(new ExcelColumn("家长姓名", "parent_name", 20));
    		myColumns3.add(new ExcelColumn("家长角色", "parent_role", 20));
    		myColumns3.add(new ExcelColumn("家长电话", "phone", 20));
    		myColumns3.add(new ExcelColumn("小塾号", "derver", 20));

	    	CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {
			logger.error("异常", e);
    	}catch (Exception e1){
			logger.error("异常", e1);
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
					logger.error("异常", e);
    			}  
    		}
    	}
    } 
	
	
	
	
	
	//添加学生
	@RequestMapping(value="/student/add/{libId}")
	public String studentAdd(Model model,@PathVariable String libId) {
		model.addAttribute("libId", libId);
		return "sys/imlibuser/studentAdd";
	}	
	
	
	//添加学生服务
	@RequestMapping(value="/student/service/add/{libId}/{vipId}")
	public String studentServiceAdd(Model model,
			@PathVariable String libId,@PathVariable String vipId) {
	
		List<LibVipService> libVipServices=libVipServiceService.findValidService(vipId, "S003");
		List<LibVipService> libVipServices_S999=new ArrayList<LibVipService>();
		if(libVipServices==null || libVipServices.size()<=0) {
			libVipServices_S999=libVipServiceService.findValidService(vipId, "S999");
		}
		LibVip libVip=libVipService.getById(vipId);
		TbLibJoin libJoin=joinService.getById(libId);
		
		model.addAttribute("libVipServices", libVipServices);
		model.addAttribute("libVipServices_S999", libVipServices_S999);
		model.addAttribute("libVip", libVip);
		model.addAttribute("libJoin", libJoin);
		return "sys/imlibuser/studentServiceAdd";
	}	
	
	
	
	//检查学生服务
	@RequestMapping(value="/student/service/check/{libId}/{vipId}")
	@ResponseBody
	public Response studentServiceCheck (Model model,
			@PathVariable String libId,@PathVariable String vipId,String startTime,Integer serviceNum) {
		Response response = new  Response();
		Map<String,Object> data=new LinkedHashMap<String, Object>();
		
		Date sTime=DateHelper.parseDate(startTime, "yyyy-MM-dd HH:mm:ss");
		Date endTime=DateHelper.getMonthDate(sTime,serviceNum);
		List<LibVipService> libVipServices=libVipServiceService.findVipIdServiceByIntersectTime(vipId, "S003", sTime, endTime);
		
		List<LibVipService> libVipServices_S999=libVipServiceService.findVipIdServiceByIntersectTime(vipId, "S999", sTime, endTime);
		
		data.put("libVipServices", libVipServices);
		data.put("libVipServices_S999", libVipServices_S999);
		data.put("isService", libVipServices!=null && libVipServices.size()>0 ? true : false);
		data.put("isService_S999", libVipServices_S999!=null && libVipServices_S999.size()>0 ? true : false);
		response.success(data,"成功");
		return response;
	}	
	
	
	//保存学生服务
	@RequestMapping(value="/student/service/save/{libId}/{vipId}")
	@ResponseBody
	public Response studentServiceSave(Model model,
			@PathVariable String libId,@PathVariable String vipId,String startTime,Integer correctType,Integer serviceNum,Integer takeType) {
		Response response = new  Response();
		Date sTime=DateHelper.parseDate(startTime, "yyyy-MM-dd HH:mm:ss");
		
		TbClassStudentTemp tbLibImStudentTemp=new TbClassStudentTemp();
		tbLibImStudentTemp.setCorrectType(correctType);
		tbLibImStudentTemp.setStartTime(sTime);
		tbLibImStudentTemp.setCreateTime(new Date());
		tbLibImStudentTemp.setLibId(libId);
		tbLibImStudentTemp.setVipId(vipId);
		tbLibImStudentTemp.setTakeType(takeType);
		tbLibImStudentTemp.setServiceNum(serviceNum);
		tbLibImStudentTemp.setStatus(1);
		boolean is=tbLibImStudentTempService.insertTbClassStudentByService(tbLibImStudentTemp);
		
		if(!is){
			tbLibImStudentTemp.setErrorReason("服务添加失败！");
			tbLibImStudentTemp.setStatus(0);
		}
		tbLibImStudentTempService.save(tbLibImStudentTemp);
		response.success("成功");
		return response;
	}
		
	
	//添加学生
	@RequestMapping(value="/student/bind/{vipId}")
	public String studentBind(Model model,@PathVariable String vipId) {
		model.addAttribute("vipId", vipId);
		return "sys/imlibuser/studentBind";
	}	
	
	//学生记录
	@RequestMapping(value="/student/record/{libId}/{vipId}")
	public String record(Model model,@PathVariable String libId,@PathVariable String vipId) {
		model.addAttribute("vipId", vipId);
		model.addAttribute("libId", libId);
		List<TbClassStudentTemp> tbLibImStudentTemps=tbLibImStudentTempService.findTbLibImStudentTempByVipId(libId, vipId);
		model.addAttribute("tbLibImStudentTemps", tbLibImStudentTemps);
		return "sys/imlibuser/studentRecord";
	}	
	

	//添加学生
	@RequestMapping(value="/student/data/add/{libId}")
	@ResponseBody
	public Response studentDataAdd(Model model,@PathVariable String libId,
			TbClassStudentTemp tbLibImStudentTemp) {
		Response response = new  Response();
		
		tbLibImStudentTemp.setLibId(libId);
		
		TbLibJoin tbLibJoin=joinService.getById(libId);
		
		int countVip=libVipService.countByLibId(libId);
		if(countVip>tbLibJoin.getLibService()) {
			response.failure("校区人数已达到上限不能新导入学生。");
		}else {
			int num=tbLibImStudentTempService.insertTbClassStudent(tbLibJoin,tbLibImStudentTemp);
			if(num>0){
				response.success("成功");
			}else{
				response.failure("添加失败,请查看失败列表...");
			}
		}
		return response;
	}
	
	@RequestMapping(value="/student/data/service/save/{libId}")
	@ResponseBody
	public Response studentServiceSave(Model model,@PathVariable String libId,
			String vipIds,Integer correctType,String startTime,Integer serviceNum,Integer takeType) {
		Response response = new  Response();
		
		if(StringUtils.isNotEmpty(vipIds) && StringUtils.isNotEmpty(libId)){
			String[] vps=vipIds.split(";");
			for (String vipId : vps) {
				TbClassStudentTemp tbLibImStudentTemp=new TbClassStudentTemp();
				tbLibImStudentTemp.setLibId(libId);
				tbLibImStudentTemp.setVipId(vipId);
				tbLibImStudentTemp.setStartTime(DateHelper.parseDate(startTime, "yyyy-MM-dd HH:mm:ss"));
				tbLibImStudentTemp.setServiceNum(serviceNum);
				tbLibImStudentTemp.setStatus(1);
				tbLibImStudentTemp.setCreateTime(new Date());
				tbLibImStudentTemp.setCorrectType(correctType);
				tbLibImStudentTemp.setTakeType(takeType);
				tbLibImStudentTempService.insertTbClassStudentByService(tbLibImStudentTemp);
				tbLibImStudentTempService.save(tbLibImStudentTemp);
			}
		}
		response.success("成功");
		return response;
	}
	
	
	
	//删除学生，解除关联
	@RequestMapping(value="/student/data/del/{vipId}")
	@ResponseBody
	public Response studentDel(Model model,@PathVariable String vipId) {
		Response response = new  Response();
		LibVip libVip=libVipService.getById(vipId);
		if(libVip!=null){
			if(StringUtils.isNotEmpty(libVip.getLibId())) {
				List<LibVipService> libVipServices=libVipServiceService.findVipIdServiceByLibId(libVip.getLibId(),vipId,"S003");
				if(libVipServices!=null && libVipServices.size()>0) {
					for (LibVipService libVipService : libVipServices) {
						libVipService.setStat(2);
					}
					libVipServiceService.save(libVipServices);
				}
			}
			
			TbClassStudent tbClassStudent=tbClassStudentService.findByLibIdAndVipId(libVip.getLibId(), vipId);
			if(tbClassStudent!=null) {
				tbClassStudentService.delete(tbClassStudent);
			}
			
			libVip.setLibId(null);
			libVipService.save(libVip);

		}
		response.success("成功");
		return response;
	}	
	
	
	//解除关联小塾
	@RequestMapping(value="/student/data/del/derver/{vipId}")
	@ResponseBody
	public Response studentDerverDel(Model model,@PathVariable String vipId) {
		Response response = new  Response();
		tbLibImStudentService.untyingTbClassTeacherByVipId(vipId);
		response.success("成功");
		return response;
	}	
	
	//添加关联小塾
	@RequestMapping(value="/student/data/bind/derver/{vipId}")
	@ResponseBody
	public Response studentDerverDel(Model model,@PathVariable String vipId,String derver) {
		Response response = new  Response();
		LibVip libVip=libVipService.getById(vipId);
		if(libVip!=null) {
			User user=userService.getById(libVip.getUserId());
			if (StringUtils.isBlank(user.getEasemobName())) {
			    //如果家长没有环信id
				user.setEasemobName(userService.createUniqueEasemobName());
			    userService.save(user);
			    easemobService.createUserSingle(user.getEasemobName(), user.getUserName());
			}
			ResponseEntity responseEntity=conchCommonService.bindDerver(vipId, "", "", derver);
			if(ResponseConstant.CODE_999 .equals(responseEntity.getCode())){
				response.success(responseEntity.getMsg());
			}else{
				response.failure(responseEntity.getMsg());
			}
		}
		return response;
	}	
		

	//学生添加失败列表
	@RequestMapping(value="/student/error/list")
	public String studentErrorList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
		params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
		params.put("remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
		params.put("lookup", request.getParameter("lookup")==null?"":request.getParameter("lookup"));
		
		
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImStudentTempService.findStudentErrorByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		
		return "sys/imlibuser/studentErrorList";
	}	
	
	
	
	
	/**
	 * ----------------老师相关功能-----------------------
	 */
	
	//老师导入
	@RequestMapping(value="/teacher/import")
	@ResponseBody
	public Response teacherImport(Model model,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<TbClassTeacherTemp> tbLibImTeacherTemps=new ArrayList<TbClassTeacherTemp>();
				TbClassTeacherTemp tbLibImTeacherTemp=null;
				boolean iserror=false;
				
				
				for (Map<String,String> map : datas) {
					tbLibImTeacherTemp=new TbClassTeacherTemp();
					tbLibImTeacherTemp.setLeagueName(map.get("data_0"));
					tbLibImTeacherTemp.setTeacherName(map.get("data_1"));
					tbLibImTeacherTemp.setTeacherPhone(map.get("data_2"));
					tbLibImTeacherTemp.setGrade(map.get("data_3"));
					tbLibImTeacherTemp.setClassName(map.get("data_4"));
					tbLibImTeacherTemp.setSubject(map.get("data_5"));
					tbLibImTeacherTemp.setIsCorrect(1);
					
					tbLibImTeacherTemps.add(tbLibImTeacherTemp);
					
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getLeagueName())){
						response.failure("机构名称不能为空");
						iserror=true;
						break;
					}
//					if(StringUtils.isEmpty(tbLibImTeacherTemp.getClassName())){
//						response.failure("学校班级不能为空");
//						iserror=true;
//						break;
//					}
//					if(StringUtils.isEmpty(tbLibImTeacherTemp.getGrade())){
//						response.failure("老师年级不能为空");
//						iserror=true;
//						break;
//					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherName())){
						response.failure("老师姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherPhone()) || tbLibImTeacherTemp.getTeacherPhone().length()!=11){
						response.failure("老师电话号码不正确");
						iserror=true;
						break;
					}
				
				}
				if(!iserror){
					Integer successNum=tbLibImTeacherTempService.insertBatchTbLibImTeacher(tbLibImTeacherTemps);
					if(successNum<0){
						response.failure("机构数据为空，请检查机构是否存在！");
					}else if(tbLibImTeacherTemps.size()!=successNum) {
						response.failure("存在导入失败数据，请查看失败列表！");
					}else{
						response.success("成功");
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
	}	
	
	
	
	//校长导入
	@RequestMapping(value="/principal/import")
	@ResponseBody
	public Response principalImput(Model model,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<TbClassTeacherTemp> tbLibImTeacherTemps=new ArrayList<TbClassTeacherTemp>();
				TbClassTeacherTemp tbLibImTeacherTemp=null;
				boolean iserror=false;
				
				for (Map<String,String> map : datas) {
					tbLibImTeacherTemp=new TbClassTeacherTemp();
					tbLibImTeacherTemp.setLeagueName(map.get("data_0"));
					tbLibImTeacherTemp.setTeacherName(map.get("data_1"));
					tbLibImTeacherTemp.setTeacherPhone(map.get("data_2"));
					tbLibImTeacherTemps.add(tbLibImTeacherTemp);
					
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getLeagueName())){
						response.failure("机构名称不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherName())){
						response.failure("姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherPhone()) || tbLibImTeacherTemp.getTeacherPhone().length()!=11){
						response.failure("电话号码不正确");
						iserror=true;
						break;
					}
				}
				if(!iserror){
					Integer successNum=tbLibImTeacherTempService.insertBatchTbLibImPrincipal(tbLibImTeacherTemps);
					if(successNum<0){
						response.failure("机构数据为空，请检查机构是否存在！");
					}else if(tbLibImTeacherTemps.size()!=successNum) {
						response.failure("存在导入失败数据，请查看失败列表！");
					}else{
						response.success("成功");
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
	}	
	
	
	
	//科目组长导入
	@RequestMapping(value="/leader/import")
	@ResponseBody
	public Response leaderImput(Model model,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<TbClassTeacherTemp> tbLibImTeacherTemps=new ArrayList<TbClassTeacherTemp>();
				TbClassTeacherTemp tbLibImTeacherTemp=null;
				boolean iserror=false;
				
				for (Map<String,String> map : datas) {
					tbLibImTeacherTemp=new TbClassTeacherTemp();
					tbLibImTeacherTemp.setLeagueName(map.get("data_0"));
					tbLibImTeacherTemp.setTeacherName(map.get("data_1"));
					tbLibImTeacherTemp.setTeacherPhone(map.get("data_2"));
					tbLibImTeacherTemp.setGrade(map.get("data_3"));
					tbLibImTeacherTemp.setSubject(map.get("data_4"));
					tbLibImTeacherTemps.add(tbLibImTeacherTemp);
					
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getLeagueName())){
						response.failure("机构名称不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherName())){
						response.failure("姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherPhone()) || tbLibImTeacherTemp.getTeacherPhone().length()!=11){
						response.failure("电话号码不正确");
						iserror=true;
						break;
					}
				}
				if(!iserror){
					Integer successNum=tbLibImTeacherTempService.insertBatchTbLibImLeader(tbLibImTeacherTemps);
					if(successNum<0){
						response.failure("机构数据为空，请检查机构是否存在！");
					}else if(tbLibImTeacherTemps.size()!=successNum) {
						response.failure("存在导入失败数据，请查看失败列表！");
					}else{
						response.success("成功");
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
	}	
	
	
	//班主任导入
	@RequestMapping(value="/headmaster/import")
	@ResponseBody
	public Response headmasterImput(Model model,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<TbClassTeacherTemp> tbLibImTeacherTemps=new ArrayList<TbClassTeacherTemp>();
				TbClassTeacherTemp tbLibImTeacherTemp=null;
				boolean iserror=false;
				
				for (Map<String,String> map : datas) {
					tbLibImTeacherTemp=new TbClassTeacherTemp();
					tbLibImTeacherTemp.setLeagueName(map.get("data_0"));
					tbLibImTeacherTemp.setTeacherName(map.get("data_1"));
					tbLibImTeacherTemp.setTeacherPhone(map.get("data_2"));
					tbLibImTeacherTemp.setGrade(map.get("data_3"));
					tbLibImTeacherTemp.setClassName(map.get("data_4"));
					tbLibImTeacherTemps.add(tbLibImTeacherTemp);
					
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getLeagueName())){
						response.failure("校区名称不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherName())){
						response.failure("姓名不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getTeacherPhone()) || tbLibImTeacherTemp.getTeacherPhone().length()!=11){
						response.failure("电话号码不正确");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getGrade())){
						response.failure("年级名称不能为空");
						iserror=true;
						break;
					}
					if(StringUtils.isEmpty(tbLibImTeacherTemp.getClassName())){
						response.failure("班级名称不能为空");
						iserror=true;
						break;
					}
				}
				if(!iserror){
					Integer successNum=tbLibImTeacherTempService.insertBatchTbLibImHeadmaster(tbLibImTeacherTemps);
					if(successNum<0){
						response.failure("机构数据为空，请检查机构是否存在！");
					}else if(tbLibImTeacherTemps.size()!=successNum) {
						response.failure("存在导入失败数据，请查看失败列表！");
					}else{
						response.success("成功");
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("异常", e);
			response.failure("导入异常："+e.getMessage());
		}
		return response;
	}	
	
	

	

	//老师列表
	@RequestMapping(value="/teacher/list/{libId}/{type}")
	public String teacherList(Model model,@PathVariable String libId,@PathVariable String type,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("libId", libId);
		params.put("type", type);
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImTeacherService.findTeacherByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);    
		
		TbLibJoin tbLibJoin=joinService.getById(libId);
		model.addAttribute("tbLibJoin", tbLibJoin);
		return "sys/imlibuser/teacherList";
	}	
	
	
	
	//老师列表
	@RequestMapping(value="/headmaster/list/{libId}/{type}")
	public String headmasterList(Model model,@PathVariable String libId,@PathVariable String type,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("libId", libId);
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
		params.put("type", type);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImTeacherService.findHeadmasterByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);    
		
		TbLibJoin tbLibJoin=joinService.getById(libId);
		model.addAttribute("tbLibJoin", tbLibJoin);
		return "sys/imlibuser/headmasterList";
	}	
	
	
	
	@RequestMapping(value="/teacher/exlist/{libId}")
    @ResponseBody
    public void exportTeacher(@PathVariable String libId,HttpServletRequest request, HttpServletResponse response) {  
    	ServletOutputStream os = null;
    	try { 
    	
    		TbLibJoin libJoin=joinService.getById(libId);
			String libName=libJoin.getLeagueName()+"_老师列表";
    		os = response.getOutputStream(); //获得输出流  
    		response.reset();   //清空输出流  
    		String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";  
    		response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
    		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    		response.setCharacterEncoding("utf-8");
    		
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("libId", libId);
    		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
            SplitPage sp = new SplitPage();
            sp.setAction(request.getRequestURI());
            sp.setPageNo(1);
            sp.setPageSize(10000);
            sp.setParams(params);
            Page<Map<String,Object>> page = tbLibImTeacherService.findTeacherByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"create_time"}));
            
 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("老师姓名", "name", 20));
    		myColumns3.add(new ExcelColumn("所受科目", "course_name", 20));
    		myColumns3.add(new ExcelColumn("老师电话", "telephone", 20));
    		List<Map<String, Object>> list=page.getContent();

	    	CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {
			logger.error("异常", e);
    	}catch (Exception e1){
			logger.error("异常", e1);
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
					logger.error("异常", e);
    			}  
    		}
    	}
    } 
	
	
	
	private void getById(String libId) {
		// TODO Auto-generated method stub
		
	}



	//添加老师
	@RequestMapping(value="/teacher/add/{libId}")
	public String teacherAdd(Model model,@PathVariable String libId) {
		model.addAttribute("libId", libId);
		return "sys/imlibuser/teacherAdd";
	}	
		

	//添加老师
	@RequestMapping(value="/teacher/data/add/{libId}")
	@ResponseBody
	public Response teacherDataAdd(Model model,@PathVariable String libId,
			String teacherName,String subject,String teacherPhone,String school,String grade,Integer isCorrect) {
		Response response = new  Response();
		
		TbClassTeacherTemp tbLibImTeacherTemp=new TbClassTeacherTemp();
		tbLibImTeacherTemp.setLibId(libId);
		tbLibImTeacherTemp.setTeacherName(teacherName);
		tbLibImTeacherTemp.setSubject(subject);
		tbLibImTeacherTemp.setTeacherPhone(teacherPhone);
		tbLibImTeacherTemp.setSchool(school);
		tbLibImTeacherTemp.setGrade(grade);
		tbLibImTeacherTemp.setIsCorrect(isCorrect);
		
		TbLibJoin libJoin=joinService.getById(libId);
		int is=tbLibImTeacherTempService.insertTbLibImTeacher(libJoin, tbLibImTeacherTemp);
		if(is>0) {
			response.success("成功");
		}else {
			response.failure("添加失败,请查看失败列表...");
		}
		return response;
	}	
	
	
	//更改老师批改状态
	@RequestMapping(value="/teacher/data/iscorrect/save/{libId}/{teacherId}")
	@ResponseBody
	public Response teacherDataAdd(Model model,@PathVariable String libId,@PathVariable String teacherId,Integer isCorrect) {
		Response response = new  Response();

		//无效type=15的老师
		if(isCorrect==0) {
			TbLibManager tbLibManager=managerService.findAllByUserIdAndTypeAndState(teacherId, Constant.LIB_TEACHER_TYPE,1);
			if(tbLibManager!=null) {
				tbLibManager.setIsCorrect(0);
				managerService.save(tbLibManager);
			}
		}else if(isCorrect==1) {
			TbLibManager tbLibManager=managerService.findAllByUserIdAndTypeAndState(teacherId, Constant.LIB_TEACHER_TYPE,1);
			if(tbLibManager==null){//有老师user，生成type=15的老师
				tbLibManager=new TbLibManager();
				tbLibManager.setUserId(teacherId);
				tbLibManager.setType(Constant.LIB_TEACHER_TYPE);
				tbLibManager.setCreateTime(new Date());
				tbLibManager.setLibId(teacherId);
				tbLibManager.setIsCorrect(1);
				tbLibManager.setState(1);
				tbLibManager=managerService.save(tbLibManager);
			}else {
				tbLibManager.setIsCorrect(1);
				managerService.save(tbLibManager);
			}
		}
		
		response.success("成功");
		return response;
	}	
	
	

	
	
	//删除老师，解除关联
	@RequestMapping(value="/teacher/data/del/{libId}/{teacherId}/{classId}")
	@ResponseBody
	public Response teacherDel(Model model,@PathVariable String libId,@PathVariable String teacherId,@PathVariable String classId) {
		Response response = new  Response();
		try {
//			bookManagerService.saveTbLibManagerListStatus(libId,teacherId, new int[]{Constant.LIB_TEACHER_TYPE,
//	                Constant.ORG_TEACHER_TYPE, Constant.TEACHER_TYPE}, 2);
//	        tbClassTeacherService.saveTbClassTeacherStatusByLibId(libId, teacherId, 0);
			
			TbClassTeacher tbClassTeacher=tbClassTeacherService.getTbLibImTeacherByClassIdAndType(classId, teacherId,1);
			tbClassTeacher.setStatus(0);
			tbClassTeacherService.save(tbClassTeacher);
			
	        response.success("删除成功");
		} catch (Exception e) {
			 response.failure("删除失败");
		}
		return response;
	}	
	
	
	
	//删除校长，解除关联
	@RequestMapping(value="/principal/data/del/{libId}/{teacherId}")
	@ResponseBody
	public Response principalDel(Model model,@PathVariable String libId,@PathVariable String teacherId) {
		Response response = new  Response();
		try {
			bookManagerService.saveTbLibManagerListStatus(libId,teacherId, new int[]{Constant.CURATOR}, 2);
	        response.success("删除成功");
		} catch (Exception e) {
			 response.failure("删除失败");
		}
		return response;
	}	
	
	//删除科目组长，解除关联
	@RequestMapping(value="/leader/data/del/{libId}/{teacherId}")
	@ResponseBody
	public Response leaderDel(Model model,@PathVariable String libId,@PathVariable String teacherId) {
		Response response = new  Response();
		try {
			bookManagerService.saveTbLibManagerListStatus(libId,teacherId, new int[]{Constant.LEADER}, 2);
	        response.success("删除成功");
		} catch (Exception e) {
			 response.failure("删除失败");
		}
		return response;
	}	
	
	
	//删除班主任，解除关联
	@RequestMapping(value="/headmaster/data/del/{libId}/{teacherId}/{classId}")
	@ResponseBody
	public Response headmasterDel(Model model,@PathVariable String libId,@PathVariable String teacherId,@PathVariable String classId) {
		Response response = new  Response();
		try {
			TbClassTeacher tbClassTeacher=tbClassTeacherService.getTbLibImTeacherByClassIdAndType(classId, teacherId, 2);
			tbClassTeacher.setStatus(0);
			tbClassTeacherService.save(tbClassTeacher);
	        response.success("删除成功");
		} catch (Exception e) {
			 response.failure("删除失败");
		}
		return response;
	}	
		
	
	
	//老师添加失败列表
	@RequestMapping(value="/teacher/error/list")
	public String teacherErrorList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
		params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
		params.put("remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
		params.put("lookup", request.getParameter("lookup")==null?"":request.getParameter("lookup"));
		

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = tbLibImTeacherTempService.findTeacherErrorByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"create_time"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        
		return "sys/imlibuser/teacherErrorList";
	}	
	
	
	
	
	
	

	/**
	 * ----------------班级相关功能-----------------------
	 */
	
	//
	@RequestMapping(value="/join/get/{libId}")
	@ResponseBody
	public Response libIdjoin(Model model,@PathVariable String libId) {
		Response response = new  Response();
		Map<String,Object> data=new LinkedHashMap<String, Object>();
		TbLibJoin tbLibJoin=joinService.getById(libId);
		data.put("join", tbLibJoin);
		response.success(data, "查询成功");
		return response;
	}	
	
	
	@RequestMapping(value="/join/update/{libId}")
	@ResponseBody
	public Response libIdjoin(Model model,@PathVariable String libId,Integer type,Integer num) {
		Response response = new  Response();
		if(num<=0) {
			response.success("增加的学币不能小于1");
			return response;
		}
		TbLibJoin tbLibJoin=joinService.getById(libId);
		if(tbLibJoin!=null) {
			if(type==1) {
				tbLibJoin.setLibService(tbLibJoin.getLibService()+num);
				joinService.save(tbLibJoin);
				
				joinConsumeService.rechargeTbLibJoinConsume(libId, num, 0);
				
			}else if(type==2) {
				tbLibJoin.setPlatformService(tbLibJoin.getPlatformService()+num);
				joinService.save(tbLibJoin);	
				
				joinConsumeService.rechargeTbLibJoinConsume(libId, 0, num);
			}
		}
		response.success("查询成功");
		return response;
	}	
	

	
	
	
	
	
	/**
	 * ----------------解析文档相关功能-----------------------
	 */
	
	public static List<Map<String,String>> analysisExFile(MultipartFile file) throws Exception {
		List<Map<String,String>> datas=new ArrayList<Map<String,String>>();
		Map<String,String> map=null;
		
  		@SuppressWarnings("resource")
  		Workbook wb = new XSSFWorkbook(file.getInputStream());
  		Sheet sheet = wb.getSheetAt(0);
  		Row row = null;
  		Cell cell = null;
  		for (Iterator<Row> it = sheet.rowIterator(); it.hasNext();) {
  			map=new LinkedHashMap<String, String>();
  			row = it.next();
  			if (row == null) {
  				break;
  			}
  			if(row.getRowNum()<=0){
  				continue;
  			}
  			if(StringUtils.isEmpty(getValue(row.getCell(0)))){
  				continue;
  			}
  			for (Iterator<Cell> cit =row.cellIterator(); cit.hasNext();) {
  				cell = cit.next();
  				if (cell == null) {
  	  				break;
  	  			}
  	  			if(StringUtils.isEmpty(getValue(cell))){
  	  				continue;
  	  			}
  	  			map.put("data_"+cell.getColumnIndex(), getValue(cell));	
  			}
  			datas.add(map);
  		}
  		return datas;
  	}
	
	public static String getValue(Cell cell){
		if(cell==null) {
			return "";
		}
		if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()){
	        if(DateUtil.isCellDateFormatted(cell)){
	        	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  //设置转成的时间格式
		          Date date = cell.getDateCellValue();//取得的是date类型
		          String datestr = sdf.format(date);//这里是转成String类型了，要哪种按个人需求
		          return datestr;
	        }
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		String text=cell.getStringCellValue()!=null ? String.valueOf(cell.getStringCellValue()):"";
		return text.trim();
	}

	

}
