ReticleManagerImpl.java

package com.mycim.server.reticle.manager.imp;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.jdbc.Page;
import com.mycim.framework.oid.IDGenerators;
import com.mycim.framework.oid.type.IDNames;
import com.mycim.framework.oid.type.SequenceNames;
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.server.base.manager.EventManager;
import com.mycim.server.base.manager.NamedObjectManager;
import com.mycim.server.base.manager.RelationManager;
import com.mycim.server.base.manager.TransactionLogManager;
import com.mycim.server.ems.manager.EntityManager;
import com.mycim.server.ems.manager.EquipmentManager;
import com.mycim.server.reticle.dao.ReticleDAO;
import com.mycim.server.reticle.manager.LocationInqManager;
import com.mycim.server.reticle.manager.ReticleManager;
import com.mycim.server.status.manager.StatusManager;
import com.mycim.server.wip.manager.LotManager;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.NamedObject;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.bas.TransactionLog;
import com.mycim.valueobject.consts.EntityEnum;
import com.mycim.valueobject.consts.EventName;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.ems.*;
import com.mycim.valueobject.wip.TransReason;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

@Service
@Transactional
public class ReticleManagerImpl implements ReticleManager {

    private final static String RECIPE_KEY = "RECIPE";

    private static final String NUM_ONE = "1";

    @Autowired
    ReticleDAO reticleDAO;

    @Autowired
    NamedObjectManager namedObjectManager;

    @Autowired
    RelationManager relationManager;

    @Autowired
    EntityManager entityManager;

    @Autowired
    EquipmentManager equipmentManager;

    @Autowired
    EventManager eventManager;

    @Autowired
    StatusManager statusManager;

    @Autowired
    TransactionLogManager transactionLogManager;

    @Autowired
    LotManager lotManager;

    @Autowired
    LocationInqManager locationInqManager;

    @Override
    public long insertReticle(Entity entity) {
        long instanceRrn = entityManager.insertEntity(entity);
        reticleDAO.insertReticle(entity);
        // 添加光罩 时,初始化其状态
        long eventRrn = namedObjectManager
                .getNamedObjectRrn(EventName.INIT_RTL, entity.getNamedSpace(), ObjectList.EVENT_KEY);
        Assert.isFalse(eventRrn == 0, Errors.create().content("Event: {} not found").args(EventName.INIT_RTL).build());
        initializeReticleStatus(entity.getInstanceRrn(), entity.getObjectType(), eventRrn, entity.getTransPerformedby(),
                                new HashMap());
        Reticle reticle = new Reticle();
        reticle.copyNamedObject(entity);
        reticle.setTransRrn(entity.getLastTransRrn());
        reticle.setTransSequence(1L);
        // update 操作不更新reticle 状态
        String currentStatus = entityManager.getEntityCurrentStatus(reticle.getInstanceRrn());
        reticle.setPrevEntityStatus(StringUtils.EMPTY);
        reticle.setCurrentEntityStatus(currentStatus);
        addReticleH(reticle);
        return instanceRrn;
    }

    @Override
    public void updateReticle(Entity entity) {
        entityManager.updateEntity(entity);
        reticleDAO.updateReticle(entity);
        Reticle reticle = new Reticle();
        reticle.copyNamedObject(entity);
        reticle.setTransRrn(entity.getLastTransRrn());
        reticle.setTransSequence(1L);
        List<EntityStatus> entityStatuses = entityManager.getEntityStatuss(reticle.getInstanceRrn());
        String entityStatus = "";
        for (EntityStatus status : entityStatuses) {
            entityStatus = status.getCurrentStatus();
        }
        reticle.setCurrentEntityStatus(entityStatus);
        reticle.setPrevEntityStatus(reticle.getCurrentEntityStatus());
        addReticleH(reticle);
    }

    @Override
    public void updateReticleStatus(Entity entity) {
        reticleDAO.updateReticleStatus(entity);
    }

    @Override
    public long updateReticleStatus(List<EntityStatus> entityStatuss, HashMap map) {
        Long entityRrn = (Long) map.get("entityrrn");
        long transRrn = statusManager.updateEntityStatus(entityStatuss, map);
        Boolean reticleHistFlag = MapUtils.getBooleanValue(map, "reticleHistFlag", true);// 只有reticle pd in out
        // 才会等于false

        Entity entity = entityManager.getEntity(new Entity(entityRrn));

        String currentStatus = entityManager.getEntityCurrentStatus(entityRrn);
        if (reticleHistFlag && StringUtils.equalsIgnoreCase(entity.getObjectType(), ObjectList.RETICLE_KEY)) {
            // 前一状态时 in_pd,要同步修改pd time
            if (StringUtils.equals(currentStatus, EventName.RTL_STATUS_IN_PD) ||
                    StringUtils.equals(currentStatus, EventName.INIT)) {
                Entity reticle = new Entity(entityRrn);
                reticle.setPdTime(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
                reticle.setCurrentUseTimes(0);
                reticle.setLastUpdateTimestamp((Timestamp) MapUtils
                        .getObject(map, "lastUpdateTime", new Timestamp(System.currentTimeMillis())));
                entityManager.updateReticlePDTime(reticle);
            }
            entityManager.addEntityH(transRrn, entityRrn);
            Reticle reticleH = new Reticle();
            reticleH.copyNamedObject(entity);
            reticleH.setTransRrn(transRrn);
            reticleH.setTransSequence(1L);
            reticleH.setPrevEntityStatus(currentStatus);
            currentStatus = entityManager.getEntityCurrentStatus(entityRrn);
            reticleH.setCurrentEntityStatus(currentStatus);
            reticleH.setLastUpdateTimestamp(
                    (Timestamp) MapUtils.getObject(map, "lastUpdateTime", new Timestamp(System.currentTimeMillis())));
            addReticleH(reticleH);
        }
        return transRrn;
    }

    @Override
    public long initializeReticleStatus(Long entityRrn, String entityType, Long eventRrn, String userId,
                                        Map commentMap) {
        // AF当光罩初始化时 使用次数归0 ---->begin
        String currentStatus = entityManager.getEntityCurrentStatus(entityRrn);
        if (StringUtils.equalsIgnoreCase(entityType, ObjectList.RETICLE_KEY)) {
            List<Event> events = (List) eventManager.getEvents(eventRrn);
            Event event = events.get(0);
            String instanceId = event.getInstanceId();
            if (StringUtils.equalsIgnoreCase(instanceId, EventName.INIT_RTL)) {
                Map equipmentExtMap = equipmentManager.getEquipmentExtMap(entityRrn);
                if (!equipmentExtMap.isEmpty()) {
                    entityManager.setReticleCurrentUseTimes(entityRrn, 0);
                }
            }
        }
        // ---->光罩 初始化 end
        long transRrn = entityManager.initializeEntityStatus(entityRrn, entityType, eventRrn, userId, commentMap);

        if (StringUtils.equalsIgnoreCase(entityType, ObjectList.RETICLE_KEY)) {
            Entity entity = entityManager.getEntity(new Entity(entityRrn));
            entityManager.addEntityH(transRrn, entityRrn);
            Reticle reticleH = new Reticle();
            reticleH.copyNamedObject(entity);
            reticleH.setTransRrn(transRrn);
            reticleH.setTransSequence(1L);
            reticleH.setPrevEntityStatus(currentStatus);
            reticleH.setTransId(EventName.INIT_RTL);
            currentStatus = entityManager.getEntityCurrentStatus(entityRrn);
            reticleH.setCurrentEntityStatus(currentStatus);
            reticleH.setLastUpdateTimestamp((Timestamp) MapUtils
                    .getObject(commentMap, "lastUpdateTime", new Timestamp(System.currentTimeMillis())));
            addReticleH(reticleH);
        }
        return transRrn;
    }

    @Override
    public void addReticleH(Reticle reticle) {
        reticleDAO.addReticleH(reticle);
    }

    @Override
    public List<Relation> getReticles(long rectileFamilyRrn) {
        List<Relation> reticles = new ArrayList();
        // get the collection of relation,
        List<Relation> list = relationManager
                .getRelationsUseToRrn(rectileFamilyRrn, LinkTypeList.RETICLE_TO_RETICLEFAMILY_KEY);
        int i = 0;
        for (Relation relation : list) {
            // use the relation to get the user information
            NamedObject namedObject = namedObjectManager.getNamedObject(relation.getFromRrn().longValue());

            if (relation != null && namedObject != null) {
                // copy the namedObject information into the relation
                relation.copyNamedObject(namedObject);
                relation.setSequenceNumber(new Integer(++i));
                // add the relation into the collection.
                reticles.add(relation);
            }
        }
        return reticles;
    }

    @Override
    public List<Map> getHoldReasons(long instanceRrn) {
        return reticleDAO.getHoldReasons(instanceRrn);
    }

    @Override
    public void holdReticle(HashMap transInfo) {
        long instanceRrn = Long.parseLong((String) transInfo.get("instanceRrn"));
        String transPerformedBy = (String) transInfo.get("transPerformedBy");
        long holdBy = Long.parseLong((String) transInfo.get("holdBy"));
        String holdPassword = (String) transInfo.get("holdPassword");
        TransReason transReason = (TransReason) transInfo.get("transReason");

        TransactionLog transactionLog = transactionLogManager
                .startTransactionLog(transPerformedBy, TransactionNames.HOLD_KEY);
        long transRrn = transactionLog.getTransRrn();

        // step1: update namedobject
        namedObjectManager.holdObject(instanceRrn);
        // step2: insert into multiple_Hold
        reticleDAO.insertMultipleHold(instanceRrn, RECIPE_KEY, holdBy, holdPassword, transRrn);
        // step3: insert into trans_reason
        reticleDAO.insertTransReason(transRrn, instanceRrn, transReason, 1);

        transactionLogManager.markTransactionLog(transactionLog);
    }

    @Override
    public void releaseReticle(HashMap transInfo) {
        long instanceRrn = Long.parseLong((String) transInfo.get("instanceRrn"));
        String transPerformedBy = (String) transInfo.get("transPerformedBy");
        Collection releaseReasons = (Collection) transInfo.get("releaseReasons");
        String superFlag = (String) transInfo.get("superFlag");
        String transNames = TransactionNames.RELEASE_KEY;
        TransReason transReason = (TransReason) transInfo.get("transReason");

        if (NUM_ONE.equals(superFlag)) {
            transNames = TransactionNames.SUPERRELEASE_KEY;
        }

        TransactionLog transactionLog = transactionLogManager.startTransactionLog(transPerformedBy, transNames);
        Object[] releaseReasonArray = releaseReasons.toArray();

        for (int i = 0; i < releaseReasonArray.length; i++) {
            HashMap releaseReason = (HashMap) releaseReasonArray[i];
            reticleDAO.deleteMultipleHold(instanceRrn, Long.parseLong((String) releaseReason.get("sequenceNumber")));
        }
        if (!reticleDAO.isMultipleHoldExisted(instanceRrn)) {
            namedObjectManager.releaseObject(instanceRrn);
            reticleDAO.insertTransReason(transactionLog.getTransRrn(), instanceRrn, transReason, 1);
        }
        transactionLogManager.markTransactionLog(transactionLog);
    }

    @Override
    public void reticleInAndOut(Map transInfo) {
        String transformedBy = MapUtils.getString(transInfo, "userId");
        Entity reticle = (Entity) transInfo.get("reticle");
        Entity eqpt = (Entity) transInfo.get("eqpt");
        String transId = MapUtils.getString(transInfo, "transId");
        Boolean pdFlag = MapUtils.getBooleanValue(transInfo, "pdFlag");
        Long eventRrn = MapUtils.getLong(transInfo, "eventRrn");

        TransactionLog transactionLog = transactionLogManager.startTransactionLog(transformedBy, transId);

        String reticleStatus = entityManager.getEntityCurrentStatus(reticle.getInstanceRrn());
        Assert.isFalse(StringUtils.equalsIgnoreCase(EntityEnum.IDLE.getValue(), reticleStatus) &&
                               StringUtils.equalsIgnoreCase(EntityEnum.RELEASE.getValue(), reticleStatus),
                       Errors.create().content(
                               "Recticle: {} has been changed " + "by others,please check " + "reticle's history")
                             .args(reticle.getInstanceId()).build());
        reticle.setLastUpdateTimestamp(transactionLog.getTransStartTimestamp());
        if (StringUtils.equalsIgnoreCase(transId, TransactionNames.RTL_MOVEIN_KEY)) {
            reticle.setPrevLocationRrn(reticle.getLocationRrn());

            reticle.setLocationRrn(eqpt.getInstanceRrn());
        } else {
            Long prevLocationRrn = reticle.getPrevLocationRrn();
            reticle.setPrevLocationRrn(reticle.getLocationRrn());
            reticle.setLocationRrn(prevLocationRrn);
            //当触发清洗记录动作,更新实际清洗数
            if (StringUtils.equals(reticleStatus, EventName.RTL_STATUS_IN_PD)) {
                Reticle reticleInfo = new Reticle();
                reticleInfo = getReticleInfo(reticle.getInstanceId(), reticle.getReticleFamilyRrn());
                reticleInfo.setCleanCount(reticleInfo.getCleanCount() + 1);
                updateReticleCleanCount(reticleInfo);
            }
            if (pdFlag) {
                reticle.setPdTime(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
                reticle.setCurrentUseTimes(0);
                entityManager.updateReticlePDTime(reticle);
            }
        }


        this.updateReticleLotcation(reticle);

        entityManager.addEntityH(transactionLog.getTransRrn(), reticle.getInstanceRrn());

        HashMap param = new HashMap();
        param.put("reticleHistFlag", false);

        if (pdFlag) {
            entityManager.logEvent(reticle.getInstanceRrn(), eventRrn, transformedBy, param);
        }

        Reticle reticleH = new Reticle();
        reticleH.copyNamedObject(reticle);
        reticleH.setTransRrn(transactionLog.getTransRrn());
        reticleH.setTransSequence(1L);
        String currentStatus = entityManager.getEntityCurrentStatus(reticle.getInstanceRrn());
        reticleH.setPrevEntityStatus(reticle.getCurrentStatus());
        reticleH.setCurrentEntityStatus(currentStatus);
        reticleH.setEqptRrn(eqpt.getInstanceRrn());
        reticleH.setLastUpdateTimestamp(transactionLog.getTransStartTimestamp());
        reticleH.setTransId(transId);
        reticleDAO.addReticleH(reticleH);

        HashMap map = new HashMap();
        map.put("transrrn", transactionLog.getTransRrn());
        map.put("eventrrn", eventRrn);
        entityManager.insertEntityEventHistoty(map);

        transactionLogManager.markTransactionLog(transactionLog);
    }

    @Override
    public Page qryReticleHistory(long reticleRrn, String startDateStr, String endDateStr, Page page) {
        reticleDAO.qryReticleHistory(reticleRrn, startDateStr, endDateStr, page);

        List<Map> results = (List<Map>) page.getResults();

        for (Map map : results) {
            long tmpRrn;

            tmpRrn = MapUtils.getLongValue(map, "location_rrn");
            map.put("lotcationId", getLocationId(tmpRrn));

            tmpRrn = MapUtils.getLongValue(map, "prv_location_rrn");
            map.put("prevLotcationId", getLocationId(tmpRrn));
        }

        page.setResults(results);
        return page;
    }

    @Override
    public Page qryReticleFamilyHistory(long reticleFamilyRrn, String startDateStr, String endDateStr, Page page) {
        return reticleDAO.qryReticleFamilyHistory(reticleFamilyRrn, startDateStr, endDateStr, page);
    }

    @Override
    public long insertLocationSingle(Location location) {

        TransactionLog transactionLog = transactionLogManager
                .startTransactionLog(location.getTransPerformedby(), TransactionNames.CREATE_KEY);
        long instanceRrn = 0;
        if (location.getInstanceRrn() <= 0) {
            int count = reticleDAO.getLocationCount(location);
            if (count <= 0) {
                instanceRrn = namedObjectManager.insertNamedObject(location, transactionLog.getTransRrn());
                location.setInstanceRrn(instanceRrn);
            }
        }

        int i = new Integer(location.getLocationR()).intValue();
        int k = location.getLocationP().intValue();
        int c = new Integer(location.getLocationC()).intValue();
        for (int r = 1; r <= i; r++) {
            for (int p = 1; p <= k; p++) {
                int locationCount = reticleDAO
                        .getLocationCount(location.getLocationType(), location.getLocationIdMain(), r, p);
                if (locationCount <= 0) {
                    // insert into LOCATION table
                    instanceRrn = Long.valueOf(
                            IDGenerators.get(IDNames.SEQUENCE).generateId(SequenceNames.MODULE_SEQ_OBJECT_RRN));
                    transactionLog = transactionLogManager
                            .startTransactionLog(location.getTransPerformedby(), TransactionNames.CREATE_KEY);
                    String locationId = location.getLocationIdMain() + "--" + r + "-" + p;
                    location.setLocationId(locationId);
                    reticleDAO
                            .insertLocation(instanceRrn, location.getLocationType(), location.getLocationIdMain(), r, c,
                                            p, location.getMaxQty(), location);
                    reticleDAO.insertLocationHis(instanceRrn, transactionLog);
                }
            }
        }
        transactionLogManager.markTransactionLog(transactionLog);
        return instanceRrn;
    }

    @Override
    public Location getLocation(Location location) {
        NamedObject namedObject = namedObjectManager.getNamedObject(location);

        if (namedObject == null) {
            return null;
        }

        // get the object rrn from named object
        long instanceRrn = namedObject.getInstanceRrn();

        location.copyNamedObject(namedObject);

        return location;
    }

    @Override
    public List<Map> getReticleByLotUse(Long reticleRrn) {
        return reticleDAO.getReticleByLotUse(reticleRrn);
    }

    @Override
    public void handleOverdueReticle() {
        String userId = "SYSTEM";

        List<Map> allReticle = this.getAllReticleOverdueTime();

        Event event = null;
        if (allReticle != null && !allReticle.isEmpty()) {
            long facilityRrn = LocalContext.getFacilityRrn();

            long eventRrn = namedObjectManager
                    .getNamedObjectRrn(EventName.RTL_WAIT_PD, facilityRrn, ObjectList.EVENT_KEY);
            Assert.isFalse(eventRrn <= 0, Errors.create().content("没有配置{}事件,请配置").args(EventName.RTL_WAIT_PD).build());
            event = new Event(EventName.RTL_WAIT_PD,
                              namedObjectManager.getNamedSpace(facilityRrn, ObjectList.EVENT_KEY),
                              ObjectList.EVENT_KEY);
            event.setInstanceRrn(eventRrn);
            event.setEntityType(ObjectList.RETICLE_KEY);
            event = eventManager.getEvent(event);

        }

        for (Map map : allReticle) {
            Timestamp overdueTime = (Timestamp) map.get("overdueTime");
            Long reticleRrn = MapUtils.getLong(map, "reticleRrn");

            String currentReticleStaus = entityManager.getEntityCurrentStatus(reticleRrn);

            if (overdueTime != null) {
                if (System.currentTimeMillis() > overdueTime.getTime()) {
                    //autoHoldReticleByClean(event, reticleRrn, userId);
                }
            }
            String pdFlag = MapUtils.getString(map, "pdFlag", StringUtils.EMPTY);

            if (StringUtils.equalsIgnoreCase(pdFlag, EntityEnum.PDFLAG_T.getValue()) &&
                    (StringUtils.equalsIgnoreCase(currentReticleStaus, EntityEnum.IDLE.getValue()) ||
                            StringUtils.equalsIgnoreCase(currentReticleStaus, EntityEnum.RELEASE.getValue()) ||
                            StringUtils.equalsIgnoreCase(currentReticleStaus, EntityEnum.RUN.getValue()))) {


                int currentUseTimes = MapUtils.getIntValue(map, "currentUseTimes");
                int maxUseTimes = MapUtils.getIntValue(map, "maxUseTimes");
                Long processTime = 0L;
                String cycleTime = MapUtils.getString(map, "processTime");
                if ((map.get("pdTime") != null && !StringUtils.isBlank((String) map.get("pdTime")))) {
                    if (!StringUtils.isBlank(cycleTime) && !cycleTime.contains(":")) {
                        int n = Integer.parseInt(cycleTime);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(
                                DateUtils.parse(MapUtils.getString(map, "pdTime"), DateUtils.DATE_FORMAT4DATE));
                        calendar.add(5, n);
                        Date d = calendar.getTime();
                        processTime = DateUtils
                                .parse(DateUtils.formatDate(d, DateUtils.DATE_FORMAT4DATE), DateUtils.DATE_FORMAT4DATE)
                                .getTime();
                    } else {
                        processTime = DateUtils.parse(MapUtils.getString(map, "pdTime"), DateUtils.DATE_FORMAT4DATE)
                                               .getTime() +
                                DateUtils.getSecondsTime(MapUtils.getString(map, "processTime")) * 1000L;
                    }
                } else {
                    if (!StringUtils.isBlank(cycleTime) && !cycleTime.contains(":")) {
                        int n = Integer.parseInt(cycleTime);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(
                                DateUtils.parse(MapUtils.getString(map, "createDate"), DateUtils.DATE_FORMAT4DATE));
                        calendar.add(5, n);
                        Date d = calendar.getTime();
                        processTime = DateUtils
                                .parse(DateUtils.formatDate(d, DateUtils.DATE_FORMAT4DATE), DateUtils.DATE_FORMAT4DATE)
                                .getTime();
                    } else {
                        processTime = DateUtils.parse(MapUtils.getString(map, "createDate"), DateUtils.DATE_FORMAT4DATE)
                                               .getTime() +
                                DateUtils.getSecondsTime(MapUtils.getString(map, "processTime")) * 1000L;
                    }
                }
                if (processTime <= System.currentTimeMillis() || currentUseTimes >= maxUseTimes) {
                    autoWaitPDReticleByClean(event, reticleRrn, userId);
                    lotManager.holdLotForReticleWaitPD(reticleRrn);
                }
            }
        }
    }

    @Override
    public List<Map> getAllReticleOverdueTime() {
        return reticleDAO.getAllReticleOverdueTime();
    }

    @Override
    public void updateReticleLotcation(Entity entity) {
        reticleDAO.updateReticleLotcation(entity);
    }

    @Override
    public void autoWaitPDReticleByClean(Event event, Long reticleRrn, String userId) {
        List<EventModel> eventModels = eventManager.getEventModels(event.getInstanceRrn(), reticleRrn);
        List<EntityStatus> entityStatuss = new ArrayList();
        Entity entity = new Entity();
        entity.setInstanceRrn(reticleRrn);
        entity = entityManager.getEntity(entity);

        Reticle reticle = new Reticle();
        BeanUtils.copyProperties(entity, reticle);

        reticle.setPrevEntityStatus(entityManager.getEntityCurrentStatus(reticleRrn));

        if (reticle.getReticleMoveinFlag() != null && reticle.getReticleMoveinFlag()) {
            reticle.setEqptRrn(reticle.getLocationRrn());
        }
        for (Object obj : eventModels) {
            EventModel instance = (EventModel) obj;
            EntityStatus entityStatus = new EntityStatus();
            entityStatus.setCurrentStatus(instance.getTargetStatus());
            entityStatus.setStatusGroupId(instance.getStatusGroupId());
            entityStatus.setStatusBefore(instance.getCurrentStatus());

            reticle.setCurrentEntityStatus(instance.getTargetStatus());

            entityStatus.setEntityRrn(reticleRrn);
            entityStatuss.add(entityStatus);
        }
        boolean boo = false;
        boo = statusManager.checkEnableLogEvent(event.getInstanceRrn(), reticleRrn);

        if (boo) {
            String reason = "";
            if (StringUtils.equals("9", reticle.getMaskSize())) {
                reason = "Reticle : " + reticle.getInstanceId() + " need mask clean.";
            } else {
                reason = "Reticle : " + reticle.getInstanceId() + " need print down";
            }
            HashMap map = new HashMap();
            map.put("event", event);
            map.put("user", userId);
            map.put("comments", reason);
            map.put("comments1", "");
            map.put("comments2", "");
            map.put("entityrrn", reticleRrn);
            statusManager.updateEntityStatusForReticle(entityStatuss, map, reticle);
        }
    }

    @Override
    public Page qryReticleByPage(Page page, Map<String, Object> argMap) {
        if (StringUtils.isNotBlank(MapUtils.getStringCheckNull(argMap, "reticleId"))) {
            argMap.put("reticleId",
                       StringUtils.replace(MapUtils.getString(argMap, "reticleId"), "*", "%").toString().toUpperCase());
        }
        if (StringUtils.isNotBlank(MapUtils.getStringCheckNull(argMap, "reticleFamilyId"))) {
            argMap.put("reticleFamilyId",
                       StringUtils.replace(MapUtils.getString(argMap, "reticleFamilyId"), "*", "%").toString()
                                  .toUpperCase());
        }

        long facilityRrn = MapUtils.getLongValue(argMap, "facilityRrn");
        if (facilityRrn > 0) {
            String referenceFileNamedSpace = namedObjectManager
                    .getNamedSpace(facilityRrn, ObjectList.REFERENCE_FILE_KEY);
            String reticleNamedSpace = namedObjectManager.getNamedSpace(facilityRrn, ObjectList.RETICLE_KEY);
            argMap.put("referenceFileNamedSpace", referenceFileNamedSpace);
            argMap.put("reticleNamedSpace", reticleNamedSpace);
        }
        return reticleDAO.qryReticleByPage(page, argMap);
    }

    @Override
    public Reticle getReticleInfo(String reticleId, long facilityRrn) {
        Page reticleMappingPage = new Page(1, 1);

        Map<String, Object> args = new HashMap<String, Object>();
        args.put("reticleId", reticleId);

        String referenceFileNamedSpace = namedObjectManager.getNamedSpace(facilityRrn, ObjectList.REFERENCE_FILE_KEY);
        String reticleNamedSpace = namedObjectManager.getNamedSpace(facilityRrn, ObjectList.RETICLE_KEY);
        args.put("referenceFileNamedSpace", referenceFileNamedSpace);
        args.put("reticleNamedSpace", reticleNamedSpace);

        Page p = reticleDAO.qryReticleByPage(reticleMappingPage, args);
        if (reticleMappingPage != null && CollectionUtils.isNotEmpty(reticleMappingPage.getResults())) {
            Iterator<Reticle> it = reticleMappingPage.getResults().iterator();
            while (it.hasNext()) {
                return it.next();
            }
        }
        return new Reticle();

    }

    @Override
    public void manualReticlePD(Entity entity) {
        String cycleTime = entity.getProcessTime();
        String processTime = DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT4DATE);
        String currentStatus = entityManager.getEntityCurrentStatus(entity.getInstanceRrn());
        String overdueTime;
        //如果process time不为空
        if (StringUtils.isNotEmpty(cycleTime)) {
            int n = Integer.parseInt(cycleTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(DateUtils.parse(processTime, DateUtils.DATE_FORMAT4DATE));
            calendar.add(5, n);
            Date d = calendar.getTime();
            overdueTime = DateUtils.formatDate(d, DateUtils.DATE_FORMAT4DAY);
        } else {
            overdueTime = DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT4DAY);
        }
        entity.setPdTime(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
        entity.setOverdueTime(overdueTime);
        entity.setCurrentUseTimes(0);
        reticleDAO.manualReticlePD(entity);
    }

    @Override
    public void deleteReticle(Reticle reticle) {
        reticleDAO.deleteReticle(reticle);
    }

    @Override
    public void updateReticleCleanCount(Reticle reticle) {
        reticleDAO.updateReticleCleanCount(reticle);
    }

    @Override
    public Reticle getReticleById(String reticleId) {
        Reticle reticle= reticleDAO.getReticleById(reticleId);
        if (reticle != null) {
            Long locationRrn = reticle.getLocationRrn();
            Long prevLocationRrn = reticle.getPrevLocationRrn();
            String locationId = getLocationId(locationRrn);
            String prevLocationId = getLocationId(prevLocationRrn);
            reticle.setLocationId(locationId);
            reticle.setPrevLocationId(prevLocationId);
        }
        return reticle;
    }

    @Override
    public void updateReticleLocationAndPLocation(Reticle reticle, String locationId) {
        TransactionLog transactionLog = transactionLogManager
                .startTransactionLog(LocalContext.getUserId(), TransactionNames.MODIFY_KEY);
        Reticle updateReticle = new Reticle(reticle.getInstanceRrn());
        updateReticle.setPrevLocationRrn(reticle.getLocationRrn());
        updateReticle.setLastUpdateTimestamp(transactionLog.getTransStartTimestamp());
        if (StringUtils.isNotBlank(locationId)) {
            Location location = locationInqManager.getLocationById(locationId);

            Assert.state(location != null,
                         Errors.create().key(MessageIdList.STOCK_LOCATION_NOT_HAS).args(locationId).build());

            Assert.state(StringUtils.equalsIgnoreCase(ObjectList.RETICLE_ERACK, location.getLocationType()),
                         Errors.create().key(MessageIdList.STOCK_MUST_RETICLE_ERACK).build());

            updateReticle.setLocationRrn(location.getInstanceRrn());
        } else {
            updateReticle.setLocationRrn(0L);
        }
        Reticle reticleInfo = getReticleInfo(reticle.getInstanceId(), LocalContext.getFacilityRrn());
        reticleInfo.setTransRrn(transactionLog.getTransRrn());
        reticleInfo.setTransSequence(1L);
        reticleInfo.setLastUpdateTimestamp(transactionLog.getTransStartTimestamp());
        // 增加历史记录
        this.addReticleH(reticleInfo);
        entityManager.addEntityH(transactionLog.getTransRrn(), reticle.getInstanceRrn());
        // 修改 reticle表中的location 与 plocation 以及 修改 entity中的 location与plocation
        reticleDAO.updateReticleLotcation(updateReticle);
        transactionLogManager.markTransactionLog(transactionLog);
    }

    public List<EventModel> getEventModelofEvent(Event event, Long entityRrn) {
        List<EventModel> eventModels = eventManager.getEventModelofEvent(event);
        List<EntityStatus> status = entityManager.getEntityStatuss(entityRrn.longValue());
        Iterator it = eventModels.iterator();
        while (it.hasNext()) {
            EventModel eventModel = (EventModel) it.next();
            String statusGroup = eventModel.getStatusGroupId();
            Iterator stats_it = status.iterator();
            while (stats_it.hasNext()) {
                EntityStatus entityStatus = (EntityStatus) stats_it.next();
                if (statusGroup != null && statusGroup.equalsIgnoreCase(entityStatus.getStatusGroupId())) {
                    eventModel.setCurrentStatus(entityStatus.getCurrentStatus());
                    break;
                }
            }
        }
        return eventModels;
    }

    private String getLocationId(Long rrn) {
        String tmpStr = null;
        if (rrn > 0) {
            tmpStr = reticleDAO.getLocationId(rrn);
            if (StringUtils.isEmpty(tmpStr)) {
                tmpStr = namedObjectManager.getInstanceId(rrn);
            }
        }
        return StringUtils.trimToEmpty(tmpStr);
    }

}