EmployeeCertificationMaintain.java

package com.mycim.webapp.actions.EmployeeCertificationMaintain;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.beans.BeanUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.ems.EmployeeCertification;
import com.mycim.valueobject.ems.Equipment;
import com.mycim.valueobject.security.User;
import com.mycim.webapp.Constants;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.EmployeeCertificationInfoForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 操作工执照管理
 *
 * @author weike.li
 * @version 6.0.0
 * @date 2019/11/20
 **/
public class EmployeeCertificationMaintain extends EmsSetupAction {

    private final static String DISMISSIONGROUP = "NO_ENTER";

    private final static String NUM_ONE = "1";

    private final static String NUM_ZERO = "0";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {
        return mapping.getInputForward();
    }

    public ActionForward query(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        long facilityRrn = LocalContext.getFacilityRrn();

        EmployeeCertificationInfoForm theform = (EmployeeCertificationInfoForm) form;
        String userId = StringUtils.trimToUpperCase(theform.getUserId());
        Assert.isFalse(StringUtils.isEmpty(userId),
                       Errors.create().key(MessageIdList.EMPLOYEE_MISSING_USER).content("用户号不能为空").build());

        User user = securityService.getUser(userId, facilityRrn);

        long instanceRrn = getInstanceRrn(DISMISSIONGROUP, facilityRrn, ObjectList.USERGROUP_KEY);

        Relation relation = new Relation(user.getInstanceRrn(), instanceRrn, LinkTypeList.USER_USERGROUP_KEY);
        relation = baseService.getRelation(relation);
        Assert.isFalse(relation != null,
                       Errors.create().key(MessageIdList.EMPLOYEE_LEFT).content("员工:{}已离职!").args(userId).build());

        // 模糊查询搜索框设备
        String searchEngineerGroup = theform.getSearchEngineerGroup();
        String searchEqptGroup = theform.getSearchEqptGroup();
        String searchEntityId = theform.getSearchEntityId();

        // 查询用户当前认证的设备
        List<EmployeeCertification> emps = emsService
                .getEmployeeCertifications(user.getInstanceRrn(), searchEngineerGroup, searchEqptGroup, searchEntityId);

        request.setAttribute("emps", emps);
        theform.setEquipmentId("");

        return mapping.findForward(Constants.MODIFY_KEY);
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        String certificationRrn = request.getParameter("certificationRrn");
        Assert.isFalse(StringUtils.isEmpty(certificationRrn),
                       Errors.create().key(MessageIdList.EMPLOYEE_DELETE_ERROR).content("删除认证设备错误!").build());
        String userId  = LocalContext.getUserId();
        emsService.deleteEmployeeCertification(Long.valueOf(certificationRrn),userId);
        return query(mapping, form, request);
    }

    public ActionForward batchDelete(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        String employee = WebUtils.getParameter("employee", request);
        String certification = WebUtils.getParameter("certificationArray", request);

        Assert.isFalse(StringUtils.isBlank(certification),
                       Errors.create().key(MessageIdList.EMPLOYEE_SELECT_CERTIFICATION).content("请选择要删除的认证!").build());
        String[] certificationArray = certification.split(",");
        checkEmployeeValidity(employee);

        emsService.batchDeleteEmployeeCertification(certificationArray);
        return query(mapping, form, request);
    }

    public Map updateButtonFlag(Map map) {
        Map result = new HashMap<>();
        try {
            Long userRrn = LocalContext.getUserRrn();
            String buttonFlag = MapUtils.getString(map, "updateButtonFlag");
            if (NUM_ONE.equals(buttonFlag) || NUM_ZERO.equals(buttonFlag)) {
                long facilityRrn = LocalContext.getFacilityRrn();
                emsService.updateCertificationFlag(facilityRrn, buttonFlag,userRrn);
                result.put("success", true);
            } else {
                result.put("alertIcon", 2);
                result.put("success", false);
                result.put("message", "illegal input");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("alertIcon", 1);
            result.put("message", "There is a mistake. Please try again later");
        }
        return result;
    }

    public Map queryButtonFlag() {
        Map result = new HashMap(3);
        try {
            String buttonFlag = emsService.getCertificationFlag(LocalContext.getFacilityRrn());
            result.put("value", buttonFlag);
        } catch (Exception e) {
            result.put("value", "-1");
            result.put("message", "There is a mistake. Please try again later");
        }

        return result;
    }

    public ActionForward export(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response,
                                ActionForm form) throws Exception {
        query(mapping, form, request);
        List<EmployeeCertification> emps = (List<EmployeeCertification>) request.getAttribute("emps");

        int i = 1;
        List<Map> result = new ArrayList<>();
        for (EmployeeCertification emp : emps) {
            Map temp = BeanUtils.copyBeanToMap(emp);
            temp.put("count", i++);

            temp.put("date", emp.getExpiryDate());
            temp.put("effectiveDate", emp.getEffectiveDate());
            result.add(temp);
        }
        Map<String, Object> titles = WebUtils.getExportTitles(request);

        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        String fileName = "EmployeeCertification_" + exportDateTime + ".xlsx";
        WebUtils.exportExcel(fileName, titles, result, TemplateLocation.EMPLOYEE_CERTIFICATION, response);
        return WebUtils.NULLActionForward;
    }

    public ActionForward addCertification(ActionMapping mapping, EmployeeCertificationInfoForm theform,
                                          HttpServletRequest request) throws Exception {
        String userId = StringUtils.trimToUpperCase(theform.getUserId());
        long facilityRrn = LocalContext.getFacilityRrn();
        Assert.isFalse(StringUtils.isEmpty(userId),
                       Errors.create().key(MessageIdList.USER_MISSING).content("用户为空").build());

        User user = securityService.getUser(userId, facilityRrn);

        long instanceRrn = getInstanceRrn(DISMISSIONGROUP, facilityRrn, ObjectList.USERGROUP_KEY);

        Relation relation = new Relation(user.getInstanceRrn(), instanceRrn, LinkTypeList.USER_USERGROUP_KEY);
        relation = baseService.getRelation(relation);
        Assert.isFalse(relation != null,
                       Errors.create().key(MessageIdList.EMPLOYEE_LEFT).content("员工:{}已离职!").args(userId).build());

        EmployeeCertification emp = new EmployeeCertification();
        // 用户号
        emp.setUserRrn(user.getInstanceRrn());
        // 设备
        String entityId = StringUtils.trimToUpperCase(theform.getEntityId());
        // 有效截止日期
        String expiryDate = theform.getExpiryDate();
        String engineerGroup = theform.getEngineerGroup();
        String entityGroup = theform.getEqptGroup();

        Assert.isTrue(StringUtils.isNotEmpty(expiryDate),
                      Errors.create().key(MessageIdList.EMPLOYEE_MISSING_DATE).content("有效截止日期不能为空!").build());
        Date nowTime = DateUtils.parseDate(DateUtils.getNowTime(DateUtils.DATE_FORMAT4DAY), DateUtils.DATE_FORMAT4DAY);
        Date date = DateUtils.parseDate(expiryDate, DateUtils.DATE_FORMAT4DAY);
        Assert.isFalse(date.before(nowTime),
                       Errors.create().key(MessageIdList.EMPLOYEE_ERROR_DATE).content("有效截止日期不能小于当前日期!").build());

        Assert.isFalse(
                StringUtils.isEmpty(entityId) && StringUtils.isEmpty(engineerGroup) && StringUtils.isEmpty(entityGroup),
                Errors.create().key(MessageIdList.EMPLOYEE_MISSING_DATA).content("区域、设备组号、设备号不能全都为空!").build());

        // 获取满足Area、 Entity Group ID、Entity ID三个条件的所有设备
        List<Equipment> eqptList = emsService
                .getEquipmentByEmployeeCertification(facilityRrn, engineerGroup, entityGroup, entityId);

        Assert.isFalse(CollectionUtils.isEmpty(eqptList),
                       Errors.create().key(MessageIdList.EMPLOYEE_MISSING_EQUIPMENT).content("没有找到设备!").build());

        for (Equipment eqpt : eqptList) {
            EmployeeCertification ec = new EmployeeCertification();
            ec.setUserRrn(user.getInstanceRrn());
            ec.setExpiryDate(expiryDate);
            ec.setEntityRrn(eqpt.getInstanceRrn());
            emsService.insertOrUpdateEmployeeCertification(ec);
        }

        theform.setEntityId("");
        theform.setExpiryDate("");
        theform.setEngineerGroup("");
        theform.setEqptGroup("");

        // 模糊查询搜索框设备
        String searchEngineerGroup = theform.getSearchEngineerGroup();
        String searchEqptGroup = theform.getSearchEqptGroup();
        String searchEntityId = theform.getSearchEntityId();

        // 查询用户当前认证的设备
        List<EmployeeCertification> emps = emsService
                .getEmployeeCertifications(user.getInstanceRrn(), searchEngineerGroup, searchEqptGroup, searchEntityId);

        request.setAttribute("emps", emps);
        theform.setEquipmentId("");

        return mapping.findForward(Constants.MODIFY_KEY);
    }

    private void checkEmployeeValidity(String employee) {
        long facilityRrn = LocalContext.getFacilityRrn();
        Assert.isFalse(StringUtils.isBlank(employee),
                       Errors.create().key(MessageIdList.USER_MISSING).content("用户为空").build());

        User user = securityService.getUser(employee, facilityRrn);
        Assert.isFalse(user == null || user.getInstanceRrn() < 1,
                       Errors.create().key(MessageIdList.LOGIN_MISSING_USER).content("用户不存在,请检查").build());


        Assert.isFalse(securityService.checkUserExistedUserGroups(user.getInstanceRrn(), DISMISSIONGROUP),
                       Errors.create().key(MessageIdList.EMPLOYEE_LEFT).content("员工:{}已离职!").args(employee).build());
    }

}