package cn.com.qmth.stmms.admin.school;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.query.SchoolSearchQuery;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.biz.user.service.query.UserSearchQuery;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin/sys/school")
public class SchoolController extends BaseParameterController{

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private UserService userService;

    @RequestMapping
    public ModelAndView list(HttpServletRequest request, SchoolSearchQuery query) {
        ModelAndView view = new ModelAndView("modules/sys/schoolList");
        query = schoolService.findByQuery(query);
        view.addObject("query", query);
        return view;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addInit(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("modules/sys/schoolEdit");
        view.addObject("school", new School());
        return view;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editInit(HttpServletRequest request, @RequestParam Integer id) {
        School school = schoolService.findById(id);
        if (school != null) {
            ModelAndView view = new ModelAndView("modules/sys/schoolEdit");
            view.addObject("school", school);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school");
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(HttpServletRequest request, School school) {
        School previous = null;
        if (school.getId() != null) {
            previous = schoolService.findById(school.getId());
        }
        if (previous == null) {
            school.setEnable(true);
            school = schoolService.save(school);
            return "redirect:/admin/sys/school/admin?id=" + school.getId();
        } else {
            previous.setName(school.getName());
            previous.setProvince(school.getProvince());
            previous.setCity(school.getCity());
            previous.setAddress(school.getAddress());
            previous.setDescription(school.getDescription());
            schoolService.save(previous);
        }
        return "redirect:/admin/sys/school";
    }

    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public ModelAndView adminInit(HttpServletRequest request, @RequestParam Integer id,
            @RequestParam(required = false) String message) {
        School school = schoolService.findById(id);
        if (school != null) {
            User user = userService.findSchoolAdmin(id);
            if (user == null) {
                user = new User();
                user.setSchoolId(id);
            }
            ModelAndView view = new ModelAndView("modules/sys/schoolAdminEdit");
            view.addObject("school", school);
            view.addObject("user", user);
            view.addObject("message", message);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school");
        }
    }
    
    @RequestMapping(value = "/admin/save", method = RequestMethod.POST)
    public ModelAndView adminSave(HttpServletRequest request, User user) {
        School school = schoolService.findById(user.getSchoolId());
        if (school == null) {
            return new ModelAndView("redirect:/admin/sys/school");
        }
        User previous = userService.findSchoolAdmin(user.getSchoolId());
        String message = "";
        if (previous != null) {
            previous.setLoginName(user.getLoginName());
            previous.setName(user.getName());
            if (StringUtils.isNotBlank(user.getPassword())) {
                previous.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            }
            if (checkLoginName(previous)) {
                userService.save(previous);
                return new ModelAndView("redirect:/admin/sys/school");
            } else {
                message = "登录名重复";
            }
        } else if (StringUtils.isBlank(user.getPassword())) {
            message = "密码不能为空";
        } else if (checkLoginName(user)) {
            user.setStatus(1);
            user.setType(UserType.ADMIN);
            user.setRoleNames(Role.SCHOOL_ADMIN.getName());
            user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            userService.save(user);
            return new ModelAndView("redirect:/admin/sys/school");
        } else {
            message = "登录名重复";
        }
        return adminInit(request, user.getSchoolId(), message);
    }
    
    @RequestMapping(value = "/viewer", method = RequestMethod.GET)
    public ModelAndView viewerInit(HttpServletRequest request, @RequestParam Integer id,
            @RequestParam(required = false) String message) {
        School school = schoolService.findById(id);
        if (school != null) {
            User user = userService.findSchoolViewer(id);
            if (user == null) {
                user = new User();
                user.setSchoolId(id);
            }
            ModelAndView view = new ModelAndView("modules/sys/schoolViewerEdit");
            view.addObject("school", school);
            view.addObject("user", user);
            view.addObject("message", message);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school");
        }
    }

    @RequestMapping(value = "/viewer/save", method = RequestMethod.POST)
    public ModelAndView viewerSave(HttpServletRequest request, User user) {
        School school = schoolService.findById(user.getSchoolId());
        if (school == null) {
            return new ModelAndView("redirect:/admin/sys/school");
        }
        User previous = userService.findSchoolViewer(user.getSchoolId());
        String message = "";
        if (previous != null) {
            previous.setLoginName(user.getLoginName());
            previous.setName(user.getName());
            if (StringUtils.isNotBlank(user.getPassword())) {
                previous.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            }
            if (checkLoginName(previous)) {
                userService.save(previous);
                return new ModelAndView("redirect:/admin/sys/school");
            } else {
                message = "登录名重复";
            }
        } else if (StringUtils.isBlank(user.getPassword())) {
            message = "密码不能为空";
        } else if (checkLoginName(user)) {
            user.setStatus(1);
            user.setType(UserType.SCHOOLVIEWER);
            user.setRoleNames(Role.SCHOOL_VIEWER.getName());
            user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            userService.save(user);
            return new ModelAndView("redirect:/admin/sys/school");
        } else {
            message = "登录名重复";
        }
        return adminInit(request, user.getSchoolId(), message);
    }
    
    private boolean checkLoginName(User user) {
        User previous = userService.findByLoginName(user.getLoginName());
        if (previous == null || (user.getId() != null && previous.getId().equals(user.getId()))) {
            return true;
        } else {
            return false;
        }
    }
    @RequestMapping(value = "/admin/view/{id}",method = RequestMethod.GET)
    private ModelAndView adminView(HttpServletRequest request,UserSearchQuery query,@PathVariable Integer id,RedirectAttributes redirectAttributes){
        ModelAndView view = new ModelAndView("modules/sys/schoolAdminList");
        School school = schoolService.findById(id);
        if (school != null) {
        	view.addObject("schoolId",id);
            view.addObject("query",school.getUsers());
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school");
        }
    }

    @RequestMapping("/adminList")
    private ModelAndView adminList(HttpServletRequest request, UserSearchQuery query, @RequestParam (required=false) String message){
        ModelAndView view = new ModelAndView("modules/sys/schoolAdminList");
            query.setType(UserType.ADMIN);
            query.addIncludeRole(Role.SCHOOL_ADMIN);
            query = userService.searchByQuery(query);
            view.addObject("query",query);
            view.addObject("message",message);
            return view;
    }
    @RequestMapping(value = "/adminList/add", method = RequestMethod.GET)
    public ModelAndView adminListAdd(HttpServletRequest request, @RequestParam Integer id,
                                  @RequestParam(required = false) String message) {
            ModelAndView view = new ModelAndView("modules/sys/schoolAdminEdit");
            User user = new User();
            user.setSchoolId(id);
            view.addObject("user",user);
            return view;
    }
    @RequestMapping(value = "/adminList/save", method = RequestMethod.POST)
    public 	String adminListSave(HttpServletRequest request, User user,RedirectAttributes redirectAttributes) {
        School school = schoolService.findById(user.getSchoolId());
        UserSearchQuery query = new UserSearchQuery();
        query.setSchoolId(user.getSchoolId());
        if (school == null) {
            return "redirect:/admin/sys/school";
        }
         if (StringUtils.isBlank(user.getPassword())) {
        	 addMessage(redirectAttributes, "密码不能为空");
        } else if (checkLoginName(user)) {
            user.setStatus(1);
            user.setType(UserType.ADMIN);
            user.setRoleNames(Role.SCHOOL_ADMIN.getName());
            user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            userService.save(user);
            Set<School> schools = new HashSet<>();
            schools.add(school);
            user.setSchools(schools);
            userService.save(user);
        } else {
        	addMessage(redirectAttributes, "登录名重复");
        }
        return "redirect:/admin/sys/school/admin/view/"+user.getSchoolId();
    }
    @RequestMapping(value = "/adminList/reSetPW", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject reSetPW(HttpServletRequest request,@RequestParam Integer userId) {
        JSONObject obj = new JSONObject();
        //重置密码 8888
         User user = userService.findById(userId);
         user.setPassword(Md5EncryptUtils.md5("8888"));
         User previous = userService.save(user);
         if(previous != null){
             obj.accumulate("success", true);
         }else {
             obj.accumulate("success", false);
             obj.accumulate("message", "重置密码失败！");
         }
        return obj;
    }
    @RequestMapping(value = "/adminList/update", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateStatus(HttpServletRequest request, @RequestParam Integer userId,@RequestParam Integer status) {
        JSONObject obj = new JSONObject();
        String message = "";
        User user = userService.findById(userId);
        user.setStatus(status);
        User previous = userService.save(user);
        if(previous != null){
            obj.accumulate("success", true);
        }else {
            obj.accumulate("success", false);
            if(status.equals(1)){
                message = "启用失败！";
            }else {
                message = "暂停失败！";
            }
            obj.accumulate("message", message);
        }
        return obj;
    }
    
    @RequestMapping("/{schoolId}")
    public String get(HttpServletRequest request, @PathVariable Integer schoolId) {
    	User user = RequestUtils.getWebUser(request).getUser();
    	user.setSchoolId(schoolId);
    	userService.save(user);
    	return "redirect:" + request.getParameter("url");
    }
}
