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

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.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.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;

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

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private UserService userService;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, UserSearchQuery query) {
        query.setType(UserType.ADMIN);
        query.addIncludeRole(Role.SCHOOL_ADMIN);
        query = userService.searchByQuery(query);
        model.addAttribute("query", query);
        return "modules/sys/schoolUserList";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("schools", schoolService.findAll());
        model.addAttribute("user", new User());
        return "modules/sys/schoolUserAdd";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String adminSave(HttpServletRequest request, User user, Integer[] schoolIds,
            RedirectAttributes redirectAttributes) {
        Set<School> schools = new HashSet<>();
        if (schoolIds == null || schoolIds.length == 0) {
            addMessage(redirectAttributes, "至少选择一个学校");
            return "redirect:/admin/sys/school/user/add";
        } else {
            for (Integer id : schoolIds) {
                School school = schoolService.findById(id);
                schools.add(school);
            }
        }
        if (user.getId() != null) {
            User previous = userService.findById(user.getId());
            previous.setName(user.getName());
            previous.setSchoolId(schoolIds[0]);
            previous.setSchools(schools);
            userService.save(previous);
            return "redirect:/admin/sys/school/user";
        } else 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()));
            user.setSchoolId(schoolIds[0]);
            userService.save(user);
            user.setSchools(schools);
            userService.save(user);
            return "redirect:/admin/sys/school/user";
        }
        addMessage(redirectAttributes, "登录名重复");
        return "redirect:/admin/sys/school/user/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editInit(HttpServletRequest request, @RequestParam Integer id) {
        User user = userService.findById(id);
        if (user != null) {
            ModelAndView view = new ModelAndView("modules/sys/schoolUserEdit");
            view.addObject("schools", schoolService.findAll());
            if (user.getSchools().isEmpty()) {
                Set<School> schools = new HashSet<>();
                schools.add(schoolService.findById(user.getSchoolId()));
                user.setSchools(schools);
                userService.save(user);
            }
            view.addObject("user", user);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school/user");
        }
    }

    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;
        }
    }

}
