package cn.com.qmth.stmms.api.controller;

import cn.com.qmth.stmms.api.exception.ApiException;
import cn.com.qmth.stmms.biz.config.service.impl.SystemCache;
import cn.com.qmth.stmms.biz.exam.service.SubjectUserService;
import cn.com.qmth.stmms.biz.file.service.FileService;
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.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.ApiUser;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestIPUtil;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Set;

@Controller("loginApiController")
@RequestMapping("/api")
public class LoginController extends BaseApiController {

    public static final String SUBJECT_CODE_SPLIT = ",";

    @Autowired
    private SubjectUserService subjectUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private FileService fileService;

    @Autowired
    private SystemCache systemCache;

    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SCANNER, Role.SUBJECT_HEADER, Role.COLLEGE_ADMIN })
    @RequestMapping(value = "/user/login", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject login(HttpServletRequest request) {
        ApiUser user = RequestUtils.getApiUser(request);
        JSONObject obj = new JSONObject();
        obj.accumulate("userId", user.getUserData() != null ? user.getUserData().getId() : 0);
        obj.accumulate("userName", user.getUserData() != null ? user.getUserData().getName() : "");
        obj.accumulate("userRole", user.getRole().toString());
        obj.accumulate("campusId", 0);
        obj.accumulate("schoolId", user.getSchoolId());
        obj.accumulate("fileServer", fileService.getFileServer());
        School school = schoolService.findById(user.getSchoolId());
        obj.accumulate("doubleTrack", systemCache.isDoubleTrack() && school.isDoubleTrack());
        JSONArray array = new JSONArray();
        if (user.getUserData() != null && Role.SUBJECT_HEADER.equals(user.getRole())) {
            Set<String> set = subjectUserService.findSubjectCode(user.getUserData().getId());
            for (String subjectCode : set) {
                array.add(subjectCode);
            }
            obj.accumulate("subjectCode", array);
        } else {
            obj.accumulate("subjectCode", array);
        }
        return obj;
    }

    @RequestMapping(value = "/admin/login", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject adminLogin(HttpServletRequest request, @RequestParam String loginName,
            @RequestParam String password) {
        User user = userService.findByLoginName(loginName);
        if (user == null || !user.getPassword().equals(EncryptUtils.md5(password))) {
            throw ApiException.AUTHORIZATION_UNEXIST;
        }
        if (!user.isEnable()) {
            throw ApiException.USER_DISABLED;
        }
        if (!Role.SCHOOL_ADMIN.equals(user.getRole()) && !Role.SCAN_ADMIN.equals(user.getRole())) {
            throw ApiException.USER_ROLE_INVALID;
        }
        user.setLastLoginTime(new Date());
        user.setLastLoginIp(RequestIPUtil.getIpAddress(request));
        user.refreshScanToken();
        user = userService.save(user);
        log.info("/api/admin/login success, loginName={}, scanToken={}", user.getLoginName(), user.getScanToken());
        JSONObject obj = new JSONObject();
        obj.accumulate("id", user.getId());
        obj.accumulate("name", user.getName());
        obj.accumulate("role", user.getRole().toString());
        obj.accumulate("schoolId", user.getSchoolId());
        School school = schoolService.findById(user.getSchoolId());
        obj.accumulate("schoolName", school.getName());
        obj.accumulate("token", user.getScanToken());
        obj.accumulate("fileServer", fileService.getFileServer());
        return obj;
    }
}
