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

import java.util.Date;

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.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.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    public static Role[] roleList = { Role.SCANNER, Role.SUBJECT_HEADER };

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView list(HttpServletRequest request, UserSearchQuery query) {
        User user = RequestUtils.getWebUser(request).getUser();
        query.setSchoolId(user.getSchoolId());
        query = userService.findByQuery(query);

        ModelAndView view = new ModelAndView("modules/user/userList");
        view.addObject("roleList", roleList);
        view.addObject("query", query);
        return view;
    }

    @RequestMapping("/delete")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String delete(HttpServletRequest request, RedirectAttributes redirectAttributes, @RequestParam Integer id) {
        User current = RequestUtils.getWebUser(request).getUser();
        User user = userService.findById(id);
        String message = null;
        if (user == null) {
            message = "找不到指定用户";
        } else if (!user.getSchoolId().equals(current.getSchoolId()) || user.getId().equals(current.getId())) {
            message = "不能删除指定用户";
        } else {
            userService.delete(user);
            message = "删除成功";
        }
        redirectAttributes.addFlashAttribute("message", message);
        return "redirect:/admin/user/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView addInit(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("modules/user/userEdit");
        User user = new User();
        user.setEnable(true);
        view.addObject("user", user);
        view.addObject("roleList", roleList);
        return view;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView editInit(HttpServletRequest request, @RequestParam Integer id) {
        User current = RequestUtils.getWebUser(request).getUser();
        User user = userService.findById(id);
        if (user != null && user.getSchoolId().equals(current.getSchoolId())) {
            ModelAndView view = new ModelAndView("modules/user/userEdit");
            view.addObject("user", user);
            view.addObject("roleList", roleList);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/user/list");
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String save(HttpServletRequest request, Model model, User user) {
        User current = RequestUtils.getWebUser(request).getUser();
        User previous = null;
        if (user.getId() != null) {
            previous = userService.findById(user.getId());
        }
        if (previous == null) {
            String message = validate(user);
            if (message == null) {
                user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
                user.setSchoolId(current.getSchoolId());
                user.setEnable(true);
                user.setCreatedTime(new Date());
                userService.save(user);
            } else {
                model.addAttribute("user", user);
                model.addAttribute("roleList", roleList);
                model.addAttribute("message", message);
                return "modules/user/userEdit";
            }
        } else if (previous.getSchoolId().equals(current.getSchoolId())) {
            previous.setLoginName(user.getLoginName());
            previous.setName(user.getName());
            previous.setRole(user.getRole());
            if (StringUtils.isNotBlank(user.getPassword())) {
                previous.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            }
            if (previous.getRole() != Role.SUBJECT_HEADER) {
                previous.setSubjectCode(null);
            } else {
                previous.setSubjectCode(user.getSubjectCode());
            }
            previous.setEnable(user.isEnable());
            String message = validate(previous);
            if (message == null) {
                previous.setUpdatedTime(new Date());
                userService.save(previous);
            } else {
                model.addAttribute("user", previous);
                model.addAttribute("roleList", roleList);
                model.addAttribute("message", message);
                return "modules/user/userEdit";
            }
        }
        return "redirect:/admin/user/list";
    }

    private String validate(User user) {
        String message = null;
        if (StringUtils.isBlank(user.getLoginName())) {
            message = "登录名不能为空";
        } else if (!checkLoginName(user)) {
            message = "登录名不能重复";
        } else if (StringUtils.isBlank(user.getName())) {
            message = "名称不能为空";
        } else if (StringUtils.isBlank(user.getPassword())) {
            message = "密码不能为空";
        } else if (user.getRole() == Role.SUBJECT_HEADER && StringUtils.isBlank(user.getSubjectCode())) {
            message = "科组长必须绑定科目代码";
        }
        return message;
    }
}
