TimelimitAction.java

package com.mycim.webapp.actions.timelimit;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.exception.SystemIllegalArgumentException;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.file.excel.im.ExcelImport;
import com.mycim.framework.file.excel.im.ExcelParser;
import com.mycim.framework.file.excel.im.ExcelRow;
import com.mycim.framework.jdbc.Page;
import com.mycim.framework.utils.beans.PropertyUtils;
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.math.NumberUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.NamedSpaceList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.ReferenceDetailNames;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.consts.VersionStatus;
import com.mycim.valueobject.prp.TimeLimitSetup;
import com.mycim.valueobject.sys.ReferenceFileDetail;
import com.mycim.webapp.Constants;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.PrpSetupAction;
import com.mycim.webapp.forms.TimeLimitForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

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

/**
 * Q-Time
 *
 * @author Johnson.Wang
 * @version 6.0.0
 * @date 2019/9/6
 **/
public class TimelimitAction extends PrpSetupAction {

    private static final Integer PAGESIZE = 20;

    private static final String TIMELIMIT_TYPE_M = "M";

    private static final String LIMIT_TYPE_DESC_TRACK_IN = "Track In";

    private static final String LIMIT_TYPE_DESC_TRACK_OUT = "Track Out";

    private static final String TIME_TYPE_DESC_MIN_TIME = "MinTime";

    private static final String TIME_TYPE_DESC_MAX_TIME = "MaxTime";

    private static final String METHOD_TYPE_KEY = "METHOD_TYPE_KEY";

    private static final String METHOD_CREATE = "create";

    private static final String METHOD_MODIFY = "modify";


    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {

        request.setAttribute("processVersion", request.getParameter("startProcessVersion"));
        request.setAttribute("returnStatus", request.getParameter("returnStatus"));
        request.setAttribute("isReturnList", request.getParameter("isReturnList"));

        //当create与modify操作发生异常时,会执行此init方法,需要跳转到原页面去
        String methodType = (String) request.getAttribute(METHOD_TYPE_KEY);
        if (METHOD_CREATE.equals(methodType) || METHOD_MODIFY.equals(methodType)) {
            return mapping.findForward("form");
        }

        return mapping.getInputForward();
    }

    /**
     * 查询当前流程所有已有数据项
     *
     * @param theform
     * @param request
     * @param response
     * @return
     */
    public Map<String, Object> queryTimeLimitSetupList(TimeLimitForm theform, HttpServletRequest request,
                                                       HttpServletResponse response) {

        String processId = StringUtils.trim(theform.getProcessId());
        String productId = StringUtils.trim(theform.getProductId());
        getProcessVersionList(theform);
        Assert.isFalse(StringUtils.isEmpty(processId) && theform.getProcessVersion() == null,
                       Errors.create().key(MessageIdList.TIME_LIMIT_MISSING_PROCESS_VERSION)
                             .content("Please input process and version.").build());
        Assert.isFalse(!StringUtils.isEmpty(processId) && theform.getProcessVersion() == null,
                       Errors.create().key(MessageIdList.TIME_LIMIT_MISSING_PROCESSVERSION)
                             .content("Please input processversion.").build());
        int processVersion = theform.getProcessVersion().intValue();
        processVersion = processVersion == 0 ? -1 : processVersion;
        String status = theform.getStatus();

        int pageNo = theform.getCurrentPage();
        pageNo = pageNo <= 0 ? 1 : pageNo;
        int pageSize = theform.getPageSize();
        pageSize = pageSize <= 0 ? 10 : pageSize;

        Assert.isFalse(StringUtils.isEmpty(processId) || processVersion <= 0,
                       Errors.create().key(MessageIdList.TIME_LIMIT_MISSING_PROCESS_VERSION)
                             .content("Please input " + "process and " + "version.").build());

        //导出所有到excel
        if ("ALL".equalsIgnoreCase(request.getParameter("exportType"))) {
            pageNo = 1;
            pageSize = Integer.MAX_VALUE;
            productId = "";
        }
        Page page = new Page(pageNo, pageSize);
        if ("EDIT".equalsIgnoreCase(status)) {
            page = prpService.getTimeLimitSetupForTempWithShow(page, productId, processId, processVersion);
        } else {
            page = prpService.getTimeLimitSetupForActiveWithShow(page, productId, processId, processVersion);
        }

        Map<String, Object> results = new HashMap<>();

        results.put("pageSize", page.getNextPage());
        results.put("pageNum", page.getPageNo());
        results.put("maxPage", page.getTotalPages());
        results.put("startRowNum", page.getStartRow());

        results.put("isFirstPage", page.isFirstPage());
        results.put("hasPreviousPage", page.isHasPrePage());
        results.put("isLastPage", page.isLastPage());
        results.put("hasNextPage", page.isHasNextPage());

        results.put("list", page.getResults());

        return results;
    }

    /**
     * 查询路程所有激活的版本
     *
     * @param theform
     * @return
     */
    public List<Integer> getProcessVersionList(TimeLimitForm theform) {
        return prpService.getAvailableProcessVersions(theform.getProductId(), theform.getProcessId());
    }

    public Boolean checkHasActiveSetup(TimeLimitForm theform) {

        String processId = StringUtils.trim(theform.getProcessId());
        int processVersion = theform.getProcessVersion();
        processVersion = processVersion == 0 ? -1 : processVersion;

        String responseMsg;

        return prpService.hasActiveTimeLimitSetupThis(null, processId, processVersion);
    }

    public ActionForward forwardToAddTimeLimitForm(ActionMapping mapping, TimeLimitForm theform) {
        TimeLimitSetup timeLimitSetup = new TimeLimitSetup(StringUtils.EMPTY, NamedSpaceList.DEFAULT_KEY,
                                                           ObjectList.TIMELIMIT_KEY);
        timeLimitSetup.setStatus(VersionStatus.UNFROZEN_KEY);

        PropertyUtils.copyProperties(theform, timeLimitSetup);

        //theform.setStartProductId(theform.getProductId());
        theform.setStartProcessId(theform.getProcessId());
        theform.setStartProcessVersion(theform.getProcessVersion());
        theform.setProductRrn(theform.getProductRrn());

        theform.setTransId(Constants.CREATE_KEY);

        return mapping.findForward("form");
    }

    public ActionForward createTimeLimitSetup(ActionMapping mapping, TimeLimitForm theform, HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
        //标记进入了 createTimeLimitSetup 方法
        request.setAttribute(METHOD_TYPE_KEY, METHOD_CREATE);

        validateTimeLimitSetup(theform);

        TimeLimitSetup timeLimitSetup = new TimeLimitSetup(StringUtils.EMPTY, NamedSpaceList.DEFAULT_KEY,
                                                           ObjectList.TIMELIMIT_KEY);
        timeLimitSetup.setStatus(VersionStatus.UNFROZEN_KEY);

        Long timeLimitRrn = null;
        PropertyUtils.copyProperties(timeLimitSetup, theform);
        String timeLimitId = theform.getInstanceId();
        prpService.checkTimeLimitSetupRepeat(timeLimitSetup);
        if (StringUtils.isEmpty(timeLimitId) || StringUtils.isBlank(timeLimitId)) {
            timeLimitRrn = prpService.createTimeLimitSetupTmp(timeLimitSetup);
        } else {
            timeLimitSetup.copyNamedObject(
                    new TimeLimitSetup(StringUtils.trimToUpperCase(timeLimitId), NamedSpaceList.DEFAULT_KEY,
                                       ObjectList.TIMELIMIT_KEY));
            timeLimitSetup.setTimeLimitType(TIMELIMIT_TYPE_M);
            timeLimitSetup.setTransId(TransactionNames.CREATE_KEY);
            timeLimitRrn = prpService.insertTimeLimitSetupTmp(timeLimitSetup);

        }
        theform.setTimeLimitRrn(timeLimitRrn);

        request.setAttribute("isCreate", "Y");
        return forwardToEditTimeLimitForm(mapping, theform, request, response);
    }

    public void activeTimeLimitSetup(TimeLimitForm theform, HttpServletRequest request, HttpServletResponse response) {
        String processId = theform.getProcessId();
        int processVersion = theform.getProcessVersion();

        prpService.activeTimeLimitSetup(processId, processVersion);
    }

    /**
     * 修改跨境时间限制设置
     *
     * @param mapping
     * @param theform
     * @return
     */
    public ActionForward modifyTimeLimiSetup(ActionMapping mapping, TimeLimitForm theform, HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        //标记进入了 modifyTimeLimiSetup 方法
        request.setAttribute(METHOD_TYPE_KEY, METHOD_MODIFY);

        validateTimeLimitSetup(theform);

        TimeLimitSetup timeLimitSetup = prpService.getTimeLimitSetup(theform.getInstanceId());

        PropertyUtils.copyProperties(timeLimitSetup, theform);

        timeLimitSetup.setTransId(Constants.UPDATE_KEY);
        timeLimitSetup.setTransPerformedby(LocalContext.getUserId());
        timeLimitSetup.setTimeLimitId(StringUtils.trimToUpperCase(theform.getInstanceId()));


        //prpService.checkTimeLimitSetupRepeat(timeLimitSetup);
        prpService.updateTimeLimitSetupTmp(timeLimitSetup);

        theform.setTimeLimitRrn(timeLimitSetup.getInstanceRrn());

        request.setAttribute("isModified", "Y");
        return forwardToEditTimeLimitForm(mapping, theform, request, response);
    }

    public ActionForward forwardToEditTimeLimitForm(ActionMapping mapping, TimeLimitForm theform,
                                                    HttpServletRequest request, HttpServletResponse response) {

        Long timeLimitRrn = theform.getTimeLimitRrn();
        Assert.isFalse(timeLimitRrn == null || timeLimitRrn <= 0,
                       Errors.create().content("Parameter missing. Please try " + "again after re-login.").build());

        Map<String, Object> timelimitInfo = prpService.getTimeLimitSetupForShow(timeLimitRrn);

        PropertyUtils.copyProperties(theform, timelimitInfo);

        theform.setStartProductId(theform.getProductId());
        theform.setStartProcessId(theform.getProcessId());
        theform.setProductRrn(theform.getProductRrn());
        theform.setStartReseq(MapUtils.getString(timelimitInfo, "startFlowSeq"));
        theform.setEndReseq(MapUtils.getString(timelimitInfo, "endFlowSeq"));


        String fromFlag = request.getParameter("fromflag");

        theform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute("returnStatus", theform.getStatus());
        request.setAttribute("fromflag", fromFlag);
        return mapping.findForward("form");
    }

    public ActionForward viewHistory(ActionMapping mapping, TimeLimitForm theform, HttpServletRequest request,
                                     HttpServletResponse response) {
        request.setAttribute("returnStatus", request.getParameter("status"));
        return mapping.findForward("history");
    }

    public Map<String, Object> getRouteAndOperationIdByFlowSeq(TimeLimitForm theform, HttpServletRequest request,
                                                               HttpServletResponse response) {
        String processId = theform.getProcessId();
        int processVersion = theform.getProcessVersion();
        String flowSeq = theform.getFlowSeq();

        Assert.isFalse(StringUtils.isEmpty(processId) || StringUtils.isEmpty(flowSeq),
                       Errors.create().key(MessageIdList.TIME_LIMIT_ERROR_PARAMETER)
                             .content("Parameter" + " " + "error." + " Please" + " check " + "and try" + " again!")
                             .build());
        Map<String,Object> resultMap=prpService.getRouteAndOperationIdByFlowSeq(processId, processVersion, flowSeq);
        resultMap.put("success",true);
        return resultMap;
    }

    public Map<String, Object> queryHistory(Map<String, Object> reqMap, HttpServletRequest request,
                                            HttpServletResponse response) {
        int pageNo = NumberUtils.toInt(MapUtils.getString(reqMap, "currentPage"));
        pageNo = pageNo <= 0 ? 1 : pageNo;
        int pageSize = NumberUtils.toInt(MapUtils.getString(reqMap, "pageSize"));
        pageSize = pageSize <= 0 ? 10 : pageSize;

        Map<String, Object> condition = new HashMap<>();

        condition.put("processId", StringUtils.trim(MapUtils.getString(reqMap, "processId")));
        condition.put("processVersion", MapUtils.getInteger(reqMap, "processVersion"));
        condition.put("productId", StringUtils.trim(MapUtils.getString(reqMap, "productId")));
        condition.put("effectiveDateFrom", MapUtils.getString(reqMap, "effectiveDateFrom"));
        condition.put("effectiveDateTo", MapUtils.getString(reqMap, "effectiveDateTo"));

        Page page = prpService.getTimeLimitSetupHistoryForPage(pageSize, pageNo, condition);

        Map<String, Object> results = new HashMap<>();

        results.put("pageSize", page.getNextPage());
        results.put("pageNum", page.getPageNo());
        results.put("maxPage", page.getTotalPages());
        results.put("startRowNum", page.getStartRow());

        results.put("isFirstPage", page.isFirstPage());
        results.put("hasPreviousPage", page.isHasPrePage());
        results.put("isLastPage", page.isLastPage());
        results.put("hasNextPage", page.isHasNextPage());

        results.put("list", page.getResults());

        return results;
    }

    public void unfrozenTimeLimitSetup(TimeLimitForm theform, HttpServletRequest request,
                                       HttpServletResponse response) {
        String processId = theform.getProcessId();
        int processVersion = theform.getProcessVersion();

        prpService.unfrozenTimeLimitSetup(processId, processVersion);
    }

    public void deleteTimeLimitSetup(ActionMapping mapping, TimeLimitForm theform, HttpServletRequest request,
                                     HttpServletResponse response) {

        if (theform.getTimeLimitRrn() != null && theform.getTimeLimitRrn() > 0) {
            prpService.deleteTimelimitSetup(theform.getTimeLimitRrn());
        } else if (StringUtils.isNotEmpty(theform.getInstanceId())) {
            prpService.deleteTimelimitSetup(theform.getInstanceId());
        } else {
            throw new SystemIllegalArgumentException(Errors.create().key(MessageIdList.TIME_MISSING_FAILED_DELETE)
                                                           .content("Can not find QTime. failed to delete!").build());
        }

    }

    public void frozenTimeLimitSetup(TimeLimitForm theform, HttpServletRequest request, HttpServletResponse response) {

        String processId = theform.getProcessId();
        int processVersion = theform.getProcessVersion();

        prpService.frozenTimeLimitSetup(processId, processVersion);
    }

    public ActionForward export(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        String laguage = I18nUtils.getCurrentLanguage().toString();
        TimeLimitForm theform = (TimeLimitForm) form;

        Map<String, Object> titles = WebUtils.getExportTitles(request);
        if (StringUtils.equalsIgnoreCase("CN", laguage)) {
            titles.put("timeLimitList", "时间限制列表");
            titles.put("processId", "工艺流程号:" + theform.getProcessId());
            titles.put("processVer", "工艺流程号版本:" + theform.getProcessVersion());
        } else {
            titles.put("timeLimitList", "TimeLimit List");
            titles.put("processId", "Process Id:" + theform.getProcessId());
            titles.put("processVer", "Process Version:" + theform.getProcessVersion());
        }
        // 导出
        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        List<Map> data = (List<Map>) queryTimeLimitSetupList(theform, request, response).get("list");
        for (int i = 0; i < data.size(); i++) {
            Map map = data.get(i);
            map.put("seq", i + 1);
        }
        String fileName = "Timelimit_" + exportDateTime + ".xlsx";
        WebUtils.exportExcel(fileName, titles, data, TemplateLocation.TIME_LIMIT, response);
        return WebUtils.NULLActionForward;
    }

    public String importByExcel(TimeLimitForm theform) throws Exception {
        FormFile uploadFile = theform.getUploadFile();
        String fileName = uploadFile.getFileName();
        Assert.isFalse(StringUtils.isEmpty(fileName) || !StringUtils.endsWith(fileName, ".xlsx"),
                       Errors.create().key(MessageIdList.SPEC_PLEASE_SELECT_EXCEL)
                             .content("Please select the Excel file(xlsx) to import!").build());
        List<Map> importList = buildImportList(uploadFile);
        checkImporList(importList, theform);
        prpService.importTimeLimitSetup(importList);
        return "x";
    }

    public void downloadTemplate(HttpServletResponse response) throws Exception {
        String currentLanguage = I18nUtils.getCurrentLanguage().toString();
        String fileName = "QTime_import_template.xlsx";
        if (currentLanguage.equalsIgnoreCase("en")) {
            WebUtils.exportExcel(fileName, new HashMap<>(), new ArrayList(), TemplateLocation.QTIME_IMP_TEMPLATE_EN, 1,
                                 1, response);
        } else {
            WebUtils.exportExcel(fileName, new HashMap<>(), new ArrayList(), TemplateLocation.QTIME_IMP_TEMPLATE, 1, 1,
                                 response);
        }
    }

    public void checkImporList(List<Map> impList, TimeLimitForm theform) {
        Assert.isFalse(CollectionUtils.isEmpty(impList),
                       Errors.create().content("Import Error! No data found").build());
        String processId = StringUtils.trimToUpperCase(theform.getProcessId());
        Assert.isFalse(StringUtils.isEmpty(processId) || theform.getProcessVersion() == null ||
                               theform.getProcessVersion() <= 0,
                       Errors.create().key(MessageIdList.TIME_LIMIT_MISSING_PROCESS_VERSION)
                             .content("Please input process and version.").build());
        long processRrn = getInstanceRrn(processId, LocalContext.getFacilityRrn(), ObjectList.WFL_KEY);
        Assert.isFalse(processRrn <= 0, Errors.create().key(MessageIdList.PROCESS_VALID_ID)
                                              .content("The Process Id is not a valid Process").build());
        int processVersion = theform.getProcessVersion();

        Set<String> qtimeIds = new HashSet<>();
        List limitTypesDesc = Arrays.asList(LIMIT_TYPE_DESC_TRACK_IN, LIMIT_TYPE_DESC_TRACK_OUT);
        List timeTypesDesc = Arrays.asList(TIME_TYPE_DESC_MIN_TIME, TIME_TYPE_DESC_MAX_TIME);
        for (Map map : impList) {
            // module check
            String module = MapUtils.getString(map, "module");
            if (StringUtils.isNotBlank(module)) {
                ReferenceFileDetail referenceFileDetail = getReferenceFileDetail(ReferenceDetailNames.HOLD_GROUP,
                                                                                 module, LocalContext.getFacilityRrn());

                Assert.isFalse(referenceFileDetail == null, Errors.create().content(
                        "Import error.Can not find this " + "module" + "! in the $HOLD_GROUP").build());
            }

            Assert.isTrue(StringUtils.equalsIgnoreCase(processId, MapUtils.getString(map, "processId")),
                          Errors.create().content("Import error. processId {} is incorrect, It should be {}")
                                .args(MapUtils.getString(map, "processId"), processId).build());
            Assert.isFalse(processVersion != MapUtils.getIntValue(map, "processVersion"),
                           Errors.create().content("Import error" + ". processVersion {} is incorrect, It should be {}")
                                 .args(MapUtils.getIntValue(map, "processVersion"), processId).build());
            String qtimeId = StringUtils.trimToUpperCase(MapUtils.getString(map, "timeLimitId"));
            if (StringUtils.isNotEmpty(qtimeId)) {
                Assert.isTrue(qtimeIds.add(qtimeId),
                              Errors.create().content("Import error. The QTime ID {} is repeated in " + "excel !")
                                    .args(qtimeId).build());
                TimeLimitSetup timeLimitSetup = prpService.getTimeLimitSetup(qtimeId);
                if (timeLimitSetup != null && timeLimitSetup.getInstanceRrn() > 0) {
                    String startProcessId = "";
                    int startProcessVersion = 0;
                    if (timeLimitSetup.getStartProcessRrn() != null &&
                            timeLimitSetup.getStartProcessVersion() != null) {
                        startProcessId = getInstanceId(timeLimitSetup.getStartProcessRrn());
                        startProcessVersion = timeLimitSetup.getStartProcessVersion();
                    }
                    Assert.isTrue(StringUtils.equalsIgnoreCase(processId, startProcessId) &&
                                          processVersion == startProcessVersion, Errors.create().content(
                            "Import error. The QTime ID {} already exist and belong to processId " + "{} , " +
                                    "processVersion {}").args(qtimeId, startProcessId, startProcessVersion).build());
                }
            }
            Assert.isTrue(limitTypesDesc.contains(MapUtils.getString(map, "limitType")),
                          Errors.create().content("Import error." + " limitType {} is incorrect, It should be {} or {}")
                                .args(MapUtils.getString(map, "limitType"), limitTypesDesc.get(0),
                                      limitTypesDesc.get(1)).build());
            Assert.isTrue(timeTypesDesc.contains(MapUtils.getString(map, "timeType")),
                          Errors.create().content("Import error. " + "timeType {} is incorrect, It should be {} or {}")
                                .args(MapUtils.getString(map, "limitType"), timeTypesDesc.get(0), timeTypesDesc.get(1))
                                .build());
            String timelimit = MapUtils.getString(map, "timelimit");
            Assert.isFalse(StringUtils.countMatches(timelimit, ":") != 2, Errors.create().content(
                    "Import error. QTime {}" + " " + "is incorrect, QTime" + " must be HH:MM:SS " + "format!")
                                                                                .content(timelimit).build());
        }
    }

    private List<Map> buildImportList(FormFile upFile) throws Exception {
        List<Map> results = new ExcelImport().attributeFrom(0).attributeTo(0).tableFrom(3)
                                             .mapper(new ExcelParser<Object, Map>() {

                                                 @Override
                                                 public Object attributeMapper(List<ExcelRow> attributeRows,
                                                                               int attributeFrom, int attributeTo) {
                                                     return null;
                                                 }

                                                 @Override
                                                 public Map tableRowMapper(ExcelRow excelRow, int rowNum,
                                                                           Object attributeDatas) {

                                                     Assert.isFalse(rowNum < 4, Errors.create().content(
                                                             "Import error: no data " + "was found!").build());

                                                     if (StringUtils.isBlank(excelRow.getString(0))) {
                                                         return null;
                                                     }

                                                     Map map = new HashMap();
                                                     map.put("rowNum", rowNum);
                                                     //序号
                                                     map.put("seq", excelRow.getString(0));
                                                     //时间限制号
                                                     map.put("timeLimitId", excelRow.getString(1));
                                                     //产品名
                                                     map.put("productId", excelRow.getString(2));
                                                     //工艺流程号
                                                     map.put("processId", excelRow.getString(3));
                                                     //工艺流程版本
                                                     map.put("processVersion", excelRow.getString(4));
                                                     //开始路径号
                                                     map.put("startRouteId", excelRow.getString(5));
                                                     //开始步骤号
                                                     map.put("startOperationId", excelRow.getString(6));
                                                     //开始序号
                                                     map.put("startFlowSeq", excelRow.getString(7));
                                                     //结束路径
                                                     map.put("endRouteId", excelRow.getString(8));
                                                     //结束步骤
                                                     map.put("endOperationId", excelRow.getString(9));
                                                     //End Seq
                                                     map.put("endFlowSeq", excelRow.getString(10));
                                                     //时间限制(HH:MM:SS)
                                                     map.put("timelimit", excelRow.getString(11));
                                                     //计算类型
                                                     map.put("limitType", excelRow.getString(12));
                                                     //时间类型
                                                     map.put("timeType", excelRow.getString(13));
                                                     //模块
                                                     map.put("module", excelRow.getString(14));
                                                     return map;
                                                 }
                                             }).file(upFile.getInputStream()).getTableDataList();
        return results;
    }

    /**
     * 检查即将插入的数据
     *
     * @param theform
     */
    private void validateTimeLimitSetup(TimeLimitForm theform) {

        validateBaseInfo(theform);

        validateTechnologyInfo(theform);

        Assert.isFalse(theform.getTimeLimit() == null || theform.getTimeLimit().length() == 0 ||
                               DateUtils.getSecondsTime(theform.getTimeLimit().trim()) == 0,
                       Errors.create().key(MessageIdList.TIME_NOT_VALID_TIME).content("Time limit is not a valid time")
                             .build());

        Assert.isFalse(theform.getTimeType() == null ||
                               !("1".equals(theform.getTimeType()) || "0".equals(theform.getTimeType())),
                       Errors.create().key(MessageIdList.TIME_TYPE_ERROR)
                             .content("Time Type is error! Please Check Setup!").build());

        Assert.isFalse(theform.getLimitType() == null ||
                               !("1".equals(theform.getLimitType()) || "0".equals(theform.getLimitType())),
                       Errors.create().key(MessageIdList.TIME_LIMIT_TYPE_ERROR)
                             .content("Limit Type is error! Please Check Setup!").build());

        Assert.isFalse(StringUtils.isBlank(theform.getModule()),
                       Errors.create().key(MessageIdList.TIME_MODULE_NOT_NULL).content("Module can not be empty!")
                             .build());
    }

    private void validateBaseInfo(TimeLimitForm theform) {
        if (!StringUtils.isEmpty(theform.getStartProductId())) {
            long startProductRrn = getInstanceRrn(theform.getStartProductId(), LocalContext.getFacilityRrn(),
                                                  ObjectList.PRODUCT_KEY);
            theform.setStartProductRrn(startProductRrn);
            Assert.isFalse(theform.getStartProductRrn() == 0, Errors.create().key(MessageIdList.PRODUCT_VALID_ID)
                                                                    .content("The Product Id is not a valid Product")
                                                                    .build());
        } else {
            theform.setStartProductRrn((long) 0);
        }
        if (!StringUtils.isEmpty(theform.getStartProcessId())) {
            long startProcessRrn = getInstanceRrn(theform.getStartProcessId(), LocalContext.getFacilityRrn(),
                                                  ObjectList.WFL_KEY);
            theform.setStartProcessRrn(startProcessRrn);
        }
        Assert.isFalse(theform.getStartProcessRrn() == 0, Errors.create().key(MessageIdList.PROCESS_VALID_ID)
                                                                .content("The Process Id is not a valid Process")
                                                                .build());
    }

    private void validateTechnologyInfo(TimeLimitForm theform) {
        if (theform.getStartRouteId() != null) {
            long startRouteRrn = getInstanceRrn(theform.getStartRouteId(), LocalContext.getFacilityRrn(),
                                                ObjectList.WFL_KEY);
            theform.setStartRouteRrn(startRouteRrn);
        }
        if (theform.getStartOperationId() != null) {
            long startOperationRrn = getInstanceRrn(theform.getStartOperationId(), LocalContext.getFacilityRrn(),
                                                    ObjectList.OPERATION_KEY);

            theform.setStartOperationRrn(startOperationRrn);
        }
        if (theform.getEndProductId() != null) {
            long endProductRrn = getInstanceRrn(theform.getEndProductId(), LocalContext.getFacilityRrn(),
                                                ObjectList.PRODUCT_KEY);
            theform.setEndProductRrn(endProductRrn);
        } else {
            theform.setEndProductRrn(theform.getStartProductRrn());
        }
        if (theform.getEndProcessId() != null) {
            long endProcessRrn = getInstanceRrn(theform.getEndProcessId(), LocalContext.getFacilityRrn(),
                                                ObjectList.WFL_KEY);
            theform.setEndProcessRrn(endProcessRrn);
        } else {
            theform.setEndProcessRrn(theform.getStartProcessRrn());
        }
        if (theform.getEndRouteId() != null) {
            long endRouteRrn = getInstanceRrn(theform.getEndRouteId(), LocalContext.getFacilityRrn(),
                                              ObjectList.WFL_KEY);
            theform.setEndRouteRrn(endRouteRrn);
        }
        if (theform.getEndOperationId() != null) {
            long endOperationRrn = getInstanceRrn(theform.getEndOperationId(), LocalContext.getFacilityRrn(),
                                                  ObjectList.OPERATION_KEY);
            theform.setEndOperationRrn(endOperationRrn);
        }
        if (StringUtils.equals(theform.getStartRouteId(), theform.getEndRouteId()) &&
                StringUtils.equals(theform.getStartOperationId(), theform.getEndOperationId())) {
            Assert.isFalse(true, Errors.create().key(MessageIdList.TIMELIMIT_SAME_STEP)
                                       .content("Cannot have the same stepId in q-time").build());
        }
    }

}