package com.school.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.exam.constant.URL;
import com.school.entity.Teacher;
import com.school.service.TeacherService;

/**
 * SpringMVC 控制器
 * 
 * @author Administrator
 * 
 */
@Controller
public class TeacherController {

	
	 
	private static final long serialVersionUID = 1L;

	@Autowired
	private TeacherService teacherService;
	@RequestMapping(value=URL.SSS)
	public String install() {
		
	

		return "redirect:/install/index.jsp";
	}
	@RequestMapping("index.html")
	public String index() {
		
	

		return "redirect:./teacherList.htm"; // 添加成功后重定向到列表页面
	}
	// 查询所有
	@RequestMapping("teacherList.htm.do")
	public String findTeacherList(ModelMap modelMap) {
		List<Teacher> lists = teacherService.selectTeacher();
		modelMap.put("teachers", lists);

		return "teacher/list"; // 指定哪个文件下的页面名称
	}

	// 转到添加页面
	@RequestMapping("toAddTeacher.htm")
	public String toSaveTeacher() {

		return "teacher/add";
	}

	// 添加保存
	@RequestMapping("doAddTeacher.htm")
	public String saveTeacher(HttpServletRequest request) throws IOException {
		//设置中文
		request.setCharacterEncoding("UTF-8");		
		String name = request.getParameter("teacherName");
		int age = Integer.parseInt(request.getParameter("age"));
		
		Teacher teacher = new Teacher();
		teacher.setTeacherName(name);
		teacher.setAge(age);
		teacherService.insertTeacher(teacher);

		return "redirect:teacherList.htm"; // 添加成功后重定向到列表页面
	}

	// 转到修改页面
	@RequestMapping("toEditTeacher.do")
	public String toEdit(ModelMap modelMap, int id) {
		Teacher teacher = teacherService.selectById(id);
		modelMap.put("teacher", teacher);

		return "teacher/edit";
	}

	// 编辑保存
	@RequestMapping("doEditTeacher.htm")
	public String editTeacher(HttpServletRequest request) throws IOException {
		//设置中文
		request.setCharacterEncoding("UTF-8");		
		int ids = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("teacherName");
		int age = Integer.parseInt(request.getParameter("age"));
		
		Teacher teacher = new Teacher(ids, name, age);
		teacherService.updateTeacher(teacher);

		return "redirect:teacherList.htm"; // 添加成功后重定向到列表页面
	}
	// 删除
	@RequestMapping("delete2")
	public String delete1() {
	
		return "teacher/dd"; // 删除成功后重定向到列表页面
	}
	// 删除
	@RequestMapping("deleteTeacher.htm")
	public String delete(int id) {
		teacherService.deleteTeacher(id);
		return "redirect:teacherList.htm"; // 删除成功后重定向到列表页面
	}

}
