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

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
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.biz.utils.RoleAuthUtil;
import cn.com.qmth.stmms.common.auth.annotation.AuthRequire;
import cn.com.qmth.stmms.common.enums.Auth;
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.Paginator;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller("analysisAdminUser")
@RequestMapping("/admin/analysis/user")
public class AnalysisUserController {

    private static final Role[] ROLES = { Role.MASTER, Role.HEAD_TEACHER, Role.SUBJECT_TEACHER };

    private static final Role[] CAMPUS_ROLES = { Role.CAMPUS_ADMIN };

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleAuthService roleService;

    @RequestMapping(value = { "", "/list" })
    @AuthRequire(value = { Auth.CAMPUS_USER_VIEW, Auth.CAMPUS_USER_VIEW }, isAny = true)
    public ModelAndView list(HttpServletRequest request, UserSearchQuery query,
            @RequestParam(required = false) String roleName) {
        User user = RequestUtils.getWebUser(request).getUser();
        ModelAndView view = new ModelAndView("admin/school/user-list");
        view.addObject("roles", ROLES);
        // if (StringUtils.isNotEmpty(user.getCampusCode())) {
        // view.addObject("campus",
        // campusService.findByCode(user.getCampusCode()));
        // query.setSchoolId(user.getSchoolId());
        // }
        if (user.getSchoolId() > 0) {
            view.addObject("school", schoolService.findById(user.getSchoolId()));
            query.setSchoolId(user.getSchoolId());
        }
        query.setType(UserType.TEACHER);
        query.addIncludeRole(roleService.findRoleByName(roleName));
        query = userService.searchByQuery(query);
        if (query.getCurrentCount() > 0) {
            List<User> list = new LinkedList<User>();
            for (User item : query.getResult()) {
                list.add(RoleAuthUtil.buildRoleAuthByUser(item, roleService));
            }
            view.addObject("userList", list);
            view.addObject("paginator",
                    new Paginator(query.getPageNumber(), query.getPageSize(), (int) query.getTotalCount()));
        }
        view.addObject("query", query);
        view.addObject("roleName", roleName);
        return view;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @AuthRequire(value = { Auth.CAMPUS_USER_CREATE, Auth.CAMPUS_USER_CREATE }, isAny = true)
    public ModelAndView addInit(HttpServletRequest request) {
        User user = RequestUtils.getWebUser(request).getUser();
        ModelAndView view = new ModelAndView("admin/school/user-add");
        // if (StringUtils.isNotEmpty(user.getCampusCode())) {
        // view.addObject("campusCode", user.getCampusCode());
        // view.addObject("roles", ROLES);
        // }
        if (user.getSchoolId() > 0) {
            view.addObject("schoolId", user.getSchoolId());
            view.addObject("roles", CAMPUS_ROLES);
        }

        view.addObject("typeValue", UserType.TEACHER.getValue());
        return view;
    }

    @RequestMapping(value = "/edit/{userId}", method = RequestMethod.GET)
    @AuthRequire(value = { Auth.CAMPUS_USER_EDIT, Auth.CAMPUS_USER_EDIT }, isAny = true)
    public ModelAndView editInit(HttpServletRequest request, @PathVariable Integer userId) {
        User user = RequestUtils.getWebUser(request).getUser();
        ModelAndView view = new ModelAndView("admin/school/user-edit");
        User editUser = userService.findById(userId);
        editUser = RoleAuthUtil.buildRoleAuthByUser(user, roleService);
        if (editUser != null && UserType.ADMIN != editUser.getType()) {
            // if (StringUtils.isNotEmpty(editUser.getCampusCode())) {
            // view.addObject("campusCode", user.getCampusCode());
            // view.addObject("roles", ROLES);
            // }
            if (editUser.getSchoolId() > 0) {
                view.addObject("schoolId", user.getSchoolId());
                view.addObject("roles", CAMPUS_ROLES);
            }

            view.addObject("editUser", editUser);

        } else {
            view = new ModelAndView("redirect:/admin/analysis/user");
        }
        return view;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @AuthRequire(value = { Auth.CAMPUS_USER_CREATE, Auth.CAMPUS_USER_EDIT, Auth.CAMPUS_USER_CREATE,
            Auth.CAMPUS_USER_EDIT }, isAny = true)
    public ModelAndView save(HttpServletRequest request, User user, @RequestParam String saveType) {
        String uri = "redirect:/admin/analysis/user";
        User webUser = RequestUtils.getWebUser(request).getUser();
        user.setType(UserType.findByValue(3));
        if (!validateLoginName(user)) {
            return new ModelAndView("admin/school/user-edit").addObject("user", user).addObject("loginNameError", true);
        }
        if (saveType.equalsIgnoreCase("isAdd")) {
            user.setSchoolId(webUser.getSchoolId());
            user.setStatus(1);
            user.setCreatedTime(new Date());
            user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
            userService.save(user);
        } else if (saveType.equalsIgnoreCase("isEdit")) {
            user.setUpdatorId(webUser.getId());
            if (user.getId() != null && user.getId() > 0) {
                User old = userService.findById(user.getId());
                user.setUpdatedTime(new Date());
                user.setCreatedTime(old.getCreatedTime());
                user.setStatus(old.getStatus());
                user.setSchoolId(old.getSchoolId());
                user.setType(old.getType());
                if (user.getPassword().isEmpty()) {
                    user.setPassword(Md5EncryptUtils.md5(old.getPassword()));
                } else {
                    user.setPassword(Md5EncryptUtils.md5(user.getPassword()));
                }
                /*
                 * if (old != null) { if (old.getSchoolId() ==
                 * webUser.getSchoolId()) { userService.save(user); } return new
                 * ModelAndView(uri); }
                 */
                userService.save(user);
                return new ModelAndView(uri);
            }
        }
        return new ModelAndView(uri);
    }

    @RequestMapping("/delete/{userId}")
    @AuthRequire(value = { Auth.STUDENT_DELETE, Auth.CAMPUS_USER_DELETE }, isAny = true)
    public String studentDelete(HttpServletRequest request, @PathVariable Integer userId) {
        User user = userService.findById(userId);
        if (user != null && UserType.ADMIN != user.getType()) {
            userService.delete(user);
        }
        return "redirect:/admin/analysis/user";
    }

    private boolean validateLoginName(User user) {
        boolean flag = false;
        User old = userService.findByLoginName(user.getLoginName());
        if (old == null) {
            flag = true;
        } else if (user.getId() != null && user.getId().intValue() == old.getId().intValue()) {
            flag = true;
        }
        return flag;
    }
}
