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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Controller;
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.config.model.SystemAuth;
import cn.com.qmth.stmms.biz.config.service.SystemAuthService;
import cn.com.qmth.stmms.biz.config.service.impl.SystemCache;
import cn.com.qmth.stmms.biz.lock.LockService;
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.school.thread.OrgSyncThread;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.enums.LockType;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.enums.SystemAuthType;
import cn.com.qmth.stmms.common.enums.UserSource;
import cn.com.qmth.stmms.common.utils.EncryptUtils;

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

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private UserService userService;

    @Qualifier("task-executor")
    @Autowired
    private AsyncTaskExecutor taskExecutor;

    @Autowired
    private LockService lockService;

    @Autowired
    private SystemAuthService authService;

    @Autowired
    private SystemCache authCache;

    @Logging(menu = "学校查询", type = LogType.QUERY)
    @RequestMapping
    public ModelAndView list(HttpServletRequest request, SchoolSearchQuery query) {
        ModelAndView view = new ModelAndView("modules/sys/schoolList");
        query = schoolService.findByQuery(query);
        view.addObject("query", query);
        boolean enableUpadteOrg = false;
        SystemAuth systemAuth = authService.findOne();
        if (systemAuth != null && SystemAuthType.ONLINE.equals(systemAuth.getType()) && authCache.isAuth()) {
            enableUpadteOrg = true;
        }
        view.addObject("enableUpadteOrg", enableUpadteOrg);
        view.addObject("running", lockService.isLocked(LockType.SCHOOL, ""));
        return view;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addInit(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("modules/sys/schoolEdit");
        view.addObject("doubleTrack", authCache.isDoubleTrack());
        view.addObject("groupDeleteWarn", authCache.isGroupDeleteWarn());
        School school = new School();
        school.setGroupDeleteCheck(true);
        view.addObject("school", 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);
            view.addObject("doubleTrack", authCache.isDoubleTrack());
            view.addObject("groupDeleteWarn", authCache.isGroupDeleteWarn());
            return view;
        } else {
            return new ModelAndView("redirect:/admin/sys/school");
        }
    }

    @Logging(menu = "新增（修改）学校", type = LogType.UPDATE)
    @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.setDoubleTrack(false);
            school.resetAccessKeyAndSecret();
            school = schoolService.save(school);
            return "redirect:/admin/sys/school/admin?id=" + school.getId();
        } else {
            if (authCache.isDoubleTrack()) {
                previous.setDoubleTrack(school.isDoubleTrack());
            }
            previous.setName(school.getName());
            previous.setProvince(school.getProvince());
            previous.setCity(school.getCity());
            previous.setAddress(school.getAddress());
            if (!authCache.isGroupDeleteWarn()) {
                previous.setGroupDeleteCheck(school.isGroupDeleteCheck());
            }
            previous.setDescription(school.getDescription());
            if (StringUtils.isBlank(previous.getAccessKey()) || StringUtils.isBlank(previous.getAccessSecret())) {
                previous.resetAccessKeyAndSecret();
            }
            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");
        }
    }

    @Logging(menu = "编辑系统管理员", type = LogType.UPDATE)
    @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(EncryptUtils.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.setEnable(true);
            user.setRole(Role.SCHOOL_ADMIN);
            user.setSource(UserSource.INTERNAL);
            user.setPassword(EncryptUtils.md5(user.getPassword()));
            userService.save(user);
            return new ModelAndView("redirect:/admin/sys/school");
        } else {
            message = "登录名重复";
        }
        return adminInit(request, user.getSchoolId(), message);
    }

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

    @RequestMapping(value = "/updateOrg", method = RequestMethod.GET)
    public String updateOrg(HttpServletRequest request) {
        if (lockService.trylock(LockType.SCHOOL, "")) {
            OrgSyncThread thread = new OrgSyncThread(schoolService, authCache);
            taskExecutor.submit(thread);
        }
        return "redirect:/admin/sys/school";
    }
}
