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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.exam.BaseExamController;
import cn.com.qmth.stmms.biz.exam.model.SubjectUser;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.SubjectUserService;
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.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.MarkerExcelError;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.enums.UserSource;
import cn.com.qmth.stmms.common.utils.EncryptUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.ImportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin/user/subject")
public class SubjectUserController extends BaseExamController {

    public static final String USER_PASSWORD = "123456";

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectUserService subjectUserService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamService examService;

    @RequestMapping(value = "/template")
    public String importFileTemplate(HttpServletResponse response, @RequestParam Boolean isHeader,
            RedirectAttributes redirectAttributes) {
        try {
            String fileName = isHeader ? "评卷组长数据导入模板.xlsx" : "复核员数据导入模板.xlsx";
            String title = isHeader ? "评卷组长数据" : "复核员数据";
            List<SubjectUser> list = new ArrayList<SubjectUser>();
            list.add(new SubjectUser());
            new ExportExcel(title, SubjectUser.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    @Logging(menu = "评卷组长/查询员导入", type = LogType.IMPORT_FILE)
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public String importFile(HttpServletRequest request, MultipartFile file, @RequestParam Boolean isHeader,
            RedirectAttributes redirectAttributes) {
        WebUser wu = RequestUtils.getWebUser(request);
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<SubjectUser> list = ei.getDataList(SubjectUser.class);

            Map<String, User> userMap = new HashMap<String, User>();
            List<SubjectUser> saveList = new ArrayList<SubjectUser>();
            Integer schoolId = wu.getUser().getSchoolId();
            for (SubjectUser subjectUser : list) {
                if (StringUtils.isBlank(subjectUser.getLoginName())) {
                    failureMsg.append("<br/> " + subjectUser.getLoginName() + "," + subjectUser.getSubjectCode()
                            + MarkerExcelError.NAMENULL.getName());
                    failureNum++;
                    continue;
                }
                User user = userMap.get(subjectUser.getLoginName().trim());
                if (user == null) {
                    user = userService.findByLoginName(subjectUser.getLoginName().trim());
                    if (user != null && !schoolId.equals(user.getSchoolId())) {
                        failureMsg.append("<br/>用户名 " + subjectUser.getLoginName() + "," + subjectUser.getSubjectCode()
                                + MarkerExcelError.NAMEUSED.getName());
                        failureNum++;
                        continue;
                    }
                    if (user != null && isHeader && !user.getRole().equals(Role.SUBJECT_HEADER)) {
                        failureMsg.append("<br/>用户名 " + subjectUser.getLoginName()
                                + MarkerExcelError.NAMENOTHEADER.getName());
                        failureNum++;
                        continue;
                    }
                    if (user != null && !isHeader && !user.getRole().equals(Role.INSPECTOR)) {
                        failureMsg.append("<br/>用户名 " + subjectUser.getLoginName()
                                + MarkerExcelError.NAMENOTHEADER.getName());
                        failureNum++;
                        continue;
                    }
                    if (user == null) {
                        user = getUser(userMap, subjectUser.getLoginName().trim(), schoolId, isHeader);
                    }
                }
                subjectUser = getSubjectUser(subjectUser.getSubjectCode(), user.getId());
                saveList.add(subjectUser);
            }
            successNum = subjectUserService.batchSave(saveList);
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条记录！");
            }
            String message = "已成功导入 " + successNum + " 条 ";
            addMessage(redirectAttributes, message + failureMsg);
            RequestUtils.setLog(request, message);
        } catch (Exception e) {
            log.error("Batch import subject user error!", e);
            addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    private SubjectUser getSubjectUser(String subjectCode, Integer userId) {
        SubjectUser subjectUser = subjectUserService.findBySubjectCodeAndUserId(subjectCode, userId);
        if (subjectUser == null) {
            subjectUser = new SubjectUser();
            subjectUser.setSubjectCode(subjectCode);
            subjectUser.setUserId(userId);
        }
        return subjectUser;
    }

    private User getUser(Map<String, User> saveMap, String loginName, Integer schoolId, boolean isHeader) {
        User user = saveMap.get(loginName);
        if (user == null) {
            user = new User();
            user.setLoginName(loginName);
            user.setName(loginName);
            user.setPassword(EncryptUtils.md5(USER_PASSWORD));
            user.setRole(isHeader ? Role.SUBJECT_HEADER : Role.INSPECTOR);
            user.setSchoolId(schoolId);
            user.setEnable(true);
            user.setCreatedTime(new Date());
            user.setSource(UserSource.INTERNAL);
            userService.save(user);
            saveMap.put(loginName, user);
        }
        return user;
    }
}
