EqpMonitorProcessBatchAction.java

package com.mycim.webapp.actions.dmmprocess;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
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.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.ObjectList;
import com.mycim.valueobject.prp.EqpMonitorProcessExcelDataForm;
import com.mycim.valueobject.prp.EqpMonitorStep;
import com.mycim.valueobject.prp.Operation;
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.forms.EqpMonitorWorkflowForm;
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.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;

public class EqpMonitorProcessBatchAction extends EqpMonitorWorkFlowAction {

    /**
     * import action the excel data for display;
     *
     * @param mapping
     * @param theform
     * @param request
     * @return
     */
    public ActionForward doImportExcel(ActionMapping mapping, EqpMonitorWorkflowForm theform,
                                       HttpServletRequest request) throws Exception {
        FormFile upFile = theform.getFormFile();
        String fileName = upFile.getFileName();
        Assert.isFalse(StringUtils.isEmpty(fileName), Errors.create().key(MessageIdList.SPEC_PLEASE_SELECT_EXCEL)
                                                            .content("Please select the Excel file to import!")
                                                            .build());
        List<EqpMonitorProcessExcelDataForm> list = getImpData(upFile);
        List<EqpMonitorStep> dmmStepList = new ArrayList<EqpMonitorStep>();
        List<String> array = new ArrayList<>();
        String modelType = "";
        String waferNum = "";
        Long modelRrn = WebUtils.getParameterLong("modelRrn", request);
        List<Operation> dmmOperations = getDMMStep(list.size());
        for (EqpMonitorProcessExcelDataForm step : list) {
            int i = 0;
            StringBuffer stringStep = new StringBuffer();
            EqpMonitorStep dmmStep = new EqpMonitorStep();
            dmmStep.setStepRrn(dmmOperations.get(i).getInstanceRrn());
            dmmStep.setModelRrn(modelRrn);
            stringStep.append("{\"seq\":" + "\"" + step.getSeq() + "\",");
            stringStep.append("\"recipe\":" + (StringUtils.isBlank(step.getRecipe()) ? "\"" : "\"" + step.getRecipe()) +
                                      "\",");
            stringStep.append("\"measurationFlag\":" +
                                      ((!StringUtils.equalsIgnoreCase(step.getIsProduction(), "Y")) ? "\"" : "\"Y") +
                                      "\",");
            stringStep.append("\"entityGroupId\":" + (StringUtils.isBlank(step.getEqptGroupId()) ? "\"" :
                    "\"" + step.getEqptGroupId()) + "\",");
            stringStep.append("\"eqptId\":" + (StringUtils.isBlank(step.getEqptId()) ? "\"" : "\"" + step.getEqptId()) +
                                      "\",");
            stringStep.append("\"parameterSetId\":" + (StringUtils.isBlank(step.getParameterSetId()) ? "\"" :
                    "\"" + step.getParameterSetId()) + "\",");
            stringStep.append("\"operationId\":" +
                                      (StringUtils.isBlank(step.getStepId()) ? "\"" : "\"" + step.getStepId()) + "\",");
            stringStep.append("\"operationDesc\":" + (StringUtils.isBlank(step.getStepDescription()) ? "\"" :
                    "\"" + step.getStepDescription()) + "\",");
            stringStep.append("\"contaimnation\":" + (StringUtils.isBlank(step.getContaminlationLevel()) ? "\"" :
                    "\"" + step.getContaminlationLevel()) + "\",");
            stringStep.append("\"processLocation\":" + (StringUtils.isBlank(step.getProcessLocation()) ? "\"" :
                    "\"" + step.getProcessLocation()) + "\",");
            stringStep.append("\"stageId\":" + (StringUtils.isBlank(step.getStage()) ? "\"" : "\"" + step.getStage()) +
                                      "\",");
            stringStep.append("\"stepSeq\":" +
                                      (StringUtils.isBlank(step.getStepSeq()) ? "\"" : "\"" + step.getStepSeq()) +
                                      "\"}");

            dmmStep.setModelSeq(NumberUtils.toInt(step.getSeq()));
            dmmStep.setRecipeId(step.getRecipe());
            dmmStep.setMeasurationFlag(StringUtils.equalsIgnoreCase(step.getIsProduction(), "Y") ? 1 : null);
            dmmStep.setEntityGroupId(step.getEqptGroupId());
            dmmStep.setEqptId(step.getEqptId());
            dmmStep.setParameterSetId(step.getParameterSetId());
            dmmStep.setOperationId(step.getStepId());
            dmmStep.setOperationDesc(step.getStepDescription());
            dmmStep.setContaimnation(step.getContaminlationLevel());
            dmmStep.setProcessLocation(step.getProcessLocation());
            dmmStep.setStageId(step.getStage());
            dmmStep.setStepSeq(step.getStepSeq());
            dmmStep.setDmmType(step.getType());
            dmmStep.setWaferNum(step.getWaferNum());

            if (StringUtils.isBlank(modelType)) {
                modelType = StringUtils.isBlank(step.getType()) ? "" : step.getType();
            }
            if (StringUtils.isBlank(waferNum)) {
                waferNum = StringUtils.isBlank(step.getWaferNum()) ? "" : step.getWaferNum();
            }
            array.add(stringStep.toString());
            dmmStepList.add(dmmStep);
            i++;
        }
        request.setAttribute("stepList", array);
        request.setAttribute("cacheDMMStepList", WebUtils.getCacheObj2String(dmmStepList));
        request.setAttribute("modelType", modelType);
        request.setAttribute("waferNum", waferNum);
        request.setAttribute("importFlag", "importFlag");
        return mapping.findForward(Constants.INIT_KEY);
    }

    public void downloadTemplate(ActionMapping mapping, ActionForm theform, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        String fileName = "dmm_step_import_template-version.xls";
        WebUtils.exportExcel(fileName, new HashMap<>(), new ArrayList(), TemplateLocation.DMMPROCESS_IMPORT_TEMPLATE, 1,
                             1, response);
    }

    public ActionForward exportDMMProcessInfo(ActionMapping mapping, EqpMonitorWorkflowForm theform,
                                              HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
        Map argMap = new HashMap();
        argMap.put("cacheDMMStepList", request.getParameter("cacheDMMStepList"));
        argMap.put("modelRrn", request.getParameter("modelRrn"));
        argMap.put("version", request.getParameter("version"));
        Map dataInfo = getStepsInfo(argMap);
        List<Map> data = (List<Map>) dataInfo.get("stepList");
        // 导出
        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        String fileName = "dmmProcessStep" + exportDateTime + ".xls";
        Map<String, Object> titles = WebUtils.getExportTitles(request);
        WebUtils.exportExcel(fileName, titles, data, TemplateLocation.DMM_PROCESS_STEP, response);
        return WebUtils.NULLActionForward;
    }

    private List<EqpMonitorProcessExcelDataForm> getImpData(FormFile upFile) throws Exception {
        List<EqpMonitorProcessExcelDataForm> dmmProcessExcelDataForms = new ArrayList<>();
        long facilityRrn = LocalContext.getFacilityRrn();
        Long refFileRrn = this
                .getInstanceRrn("$$DMMPROCESS_EXCEL_IMPORT_FORM", facilityRrn, ObjectList.REFERENCE_FILE_KEY);
        Collection refFiles = sysService.getReferenceFileDetails(refFileRrn);
        ReferenceFileDetail referenceFileDetail = null;
        Map<String, ReferenceFileDetail> refFileMap = new HashMap<String, ReferenceFileDetail>();
        for (Object each : refFiles) {
            referenceFileDetail = (ReferenceFileDetail) each;
            refFileMap.put(referenceFileDetail.getData1Value(), referenceFileDetail);
        }

        List<Map> results = new ExcelImport().attributeFrom(0).attributeTo(0).tableFrom(1)
                                             .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) {

                                                     if (StringUtils.isBlank(excelRow.getString(0))) {
                                                         return null;
                                                     }
                                                     Map map = new HashMap();
                                                     map.put("type", excelRow.getString(0));
                                                     map.put("seq", excelRow.getString(1));
                                                     map.put("stepSeq", excelRow.getString(2));
                                                     map.put("stepId", excelRow.getString(3));
                                                     map.put("stage", excelRow.getString(4));
                                                     map.put("stepDescription", excelRow.getString(5));
                                                     map.put("eqptGroupId", excelRow.getString(6));
                                                     map.put("eqptId", excelRow.getString(7));
                                                     map.put("isProduction", excelRow.getString(8));
                                                     map.put("recipe", excelRow.getString(9));
                                                     map.put("parameterSetId", excelRow.getString(10));
                                                     map.put("contaminlationLevel", excelRow.getString(11));
                                                     map.put("processLocation", excelRow.getString(12));
                                                     map.put("waferNum", excelRow.getString(13));

                                                     return map;
                                                 }
                                             }).file(upFile.getInputStream()).getTableDataList();

        Assert.isFalse(CollectionUtils.isEmpty(results),
                       Errors.create().key(MessageIdList.DMM_IMPORT_DMMPROCESS_CHECK).content("导入数据有误!请检查!").build());

        for (int i = 0; i < results.size(); i++) {
            EqpMonitorProcessExcelDataForm item = new EqpMonitorProcessExcelDataForm();
            item = validateAndImport(results, i, refFileMap, facilityRrn, item);
            boolean valid = item.isValid();
            Assert.isTrue(valid, Errors.create().key(MessageIdList.DMM_IMPORT_DMMPROCESS_CHECK).content("导入数据有误!请检查!")
                                       .build());
            item.setValid(valid);
            dmmProcessExcelDataForms.add(item);
        }
        return dmmProcessExcelDataForms;
    }


    /**
     * read a single line of the excel file;
     *
     * @param list
     * @param rowIndex
     * @param refFileMap
     * @param facility
     * @param item
     * @return
     * @throws Exception
     */
    private EqpMonitorProcessExcelDataForm validateAndImport(List<Map> list, int rowIndex,
                                                             Map<String, ReferenceFileDetail> refFileMap, Long facility,
                                                             EqpMonitorProcessExcelDataForm item) throws Exception {
        String language = I18nUtils.getCurrentLanguage().toString();
        boolean valid = true;
        Class<? extends EqpMonitorProcessExcelDataForm> itemClass = item.getClass();
        Field[] fields = itemClass.getDeclaredFields();
        String fieldName = null;
        ReferenceFileDetail ref = null;
        PropertyDescriptor pd = null;
        String value = null;
        for (int i = 0; i < fields.length; i++) {
            fieldName = fields[i].getName();
            ref = refFileMap.get(fieldName);
            if (ref != null) {
                value = MapUtils.getString(list.get(rowIndex), fieldName);
                if (StringUtils.isNotBlank(value)) {
                    value = StringUtils.isNotBlank(ref.getData3Value()) ? value.trim().toUpperCase() : value;
                }
                pd = new PropertyDescriptor(fieldName, itemClass);
                pd.getWriteMethod().invoke(item, value);
                if (StringUtils.isNotBlank(ref.getData2Value()) && StringUtils.isBlank(value)) {
                    valid = false;
                }
                if (StringUtils.equalsIgnoreCase("recipe", ref.getData1Value())) {
                    //如果模板中的recipe不为空时,需要校验是否存在于数据库中
                    if (StringUtils.isNotBlank(value)) {
                        // 验证数据库中有没有该参数
                        long recipeRrn = getInstanceRrn(value, LocalContext.getFacilityRrn(), ObjectList.RECIPE_KEY);
                        if (recipeRrn <= 0) {
                            valid = false;
                        }
                    }
                }

                if (StringUtils.equalsIgnoreCase("eqptGroupId", ref.getData1Value())) {
                    //如果模板中的设备组不为空时,需要校验是否存在于数据库中
                    if (StringUtils.isNotBlank(value)) {
                        // 验证数据库中有没有该参数
                        long eqpTypeRrn = getInstanceRrn(value, LocalContext.getFacilityRrn(),
                                                         ObjectList.ENTITYGROUP_KEY);
                        if (eqpTypeRrn <= 0) {
                            valid = false;
                        }
                    }
                }

                if (StringUtils.equalsIgnoreCase("eqptId", ref.getData1Value())) {
                    //如果模板中的设备不为空时,需要校验是否存在于数据库中
                    if (StringUtils.isNotBlank(value)) {
                        // 验证数据库中有没有该参数
                        long eqpTypeRrn = getInstanceRrn(value, LocalContext.getFacilityRrn(), ObjectList.ENTITY_KEY);
                        if (eqpTypeRrn <= 0) {
                            valid = false;
                        }
                    }
                }

                if (StringUtils.equalsIgnoreCase("parameterSetId", ref.getData1Value())) {
                    //如果模板中的参数集不为空时,需要校验是否存在于数据库中
                    if (StringUtils.isNotBlank(value)) {
                        // 验证数据库中有没有该参数
                        long parameterSetRrn = getInstanceRrn(value, LocalContext.getFacilityRrn(),
                                                              ObjectList.PARAMETERSET_KEY);
                        if (parameterSetRrn <= 0) {
                            valid = false;
                        }
                    }
                }
            }
        }
        item.setValid(valid);
        return item;
    }

}