AutoMonitorJobAction.java

package com.mycim.webapp.actions;

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.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.math.NumberUtils;
import com.mycim.utils.CheckRegexUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.automonitor.dto.AutoMonitorJobDTO;
import com.mycim.valueobject.automonitor.dto.LotAutoMonitorQueryDTO;
import com.mycim.valueobject.automonitor.dto.MonitorJobQueryDTO;
import com.mycim.valueobject.automonitor.entity.*;
import com.mycim.valueobject.automonitor.util.AutoMonitorOperationConstants;
import com.mycim.valueobject.automonitor.util.AutoMonitorUtils;
import com.mycim.valueobject.automonitor.util.MonitorJobStatusConts;
import com.mycim.valueobject.consts.PcdStatus;
import com.mycim.valueobject.ems.Carrier;
import com.mycim.valueobject.ems.Equipment;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.Unit;
import com.mycim.webapp.WebUtils;
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.*;

public class AutoMonitorJobAction extends AutoMonitorAction {

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

    public Map getMonitorCarrierInfo(Map map) {
        String lotId = MapUtils.getString(map, "lotId");
        Lot lot = lotQueryService.getLot(lotId);
        Assert.state(Objects.nonNull(lot) && lot.getLotRrn() > 0,
                     Errors.create().key(MessageIdList.LOT_LOT_NOT_EXIST_OR_CAST).content("Lot not exsit").build());

        String monitorCarrierId = MapUtils.getString(map, "monitorCarrierId");
        Carrier monitorCarrier = carrierService.getCarrier(LocalContext.getFacilityRrn(), monitorCarrierId);
        Assert.state(Objects.nonNull(monitorCarrier),
                     Errors.create().key(MessageIdList.CARRIER_CARRIER_UNAVAILABLE).build());

        List<MonitorCarrierMapping> mappings = lotAutoMonitorInqService.getMonitorCarrierMappings(monitorCarrier.getInstanceRrn());
        map.put("msg", mappings);
        return map;
    }

    public Map queryEqptMonitorItemTypeList(Map<String, Object> params) {
        List<Map<String, String>> typeList = new ArrayList<>();
        String eqptId = MapUtils.getString(params, "eqptId");
        Equipment equipment = emsService.getEquipment(eqptId, LocalContext.getFacilityRrn());
        if (Objects.nonNull(equipment)) {
            List<String> itemTypeList = autoMonitorItemInqService.getAutoMonitorItemTypeList(equipment.getInstanceRrn());

            for (String itemType : itemTypeList) {
                Map<String, String> map = new HashMap<>();
                map.put("key", itemType);
                map.put("value", itemType);
                typeList.add(map);
            }
            params.put("list", typeList);
            params.put("success", true);
        }
        return params;
    }

    public Map getMonitorJobList(Map map) {
        int pageSize = MapUtils.getIntValue(map, "limit");
        int pageNo = MapUtils.getIntValue(map, "page");

        MonitorJobQueryDTO queryDTO = new MonitorJobQueryDTO();
        queryDTO.setEqptId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "eqptId")));
        queryDTO.setItemType(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "itemType")));
        queryDTO.setProductId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "productId")));
        queryDTO.setCarrierId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "carrierId")));
        queryDTO.setLotId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "lotId")));

        List<String> queryJobStatus = new ArrayList<>();
        Object jobStatusObj = MapUtils.getObject(map, "jobStatus");
        if(jobStatusObj instanceof List) {
            List<String> jobStatusList = (List<String>) jobStatusObj;
            for (String status : jobStatusList) {
                if (StringUtils.equals(MonitorJobStatusConts.CLOSE_KEY, status)) {
                    jobStatusList.addAll(Arrays.asList(MonitorJobStatusConts.getCloseJobStatus()));
                }

                if (!jobStatusList.contains(status)) {
                    jobStatusList.add(status);
                }
            }
            queryJobStatus.addAll(jobStatusList);
        } else if(jobStatusObj instanceof String) {
            queryJobStatus.add((String)jobStatusObj);
        }
        queryDTO.setJobStatus(queryJobStatus);

        Page page = new Page(pageNo, pageSize);
        page = lotAutoMonitorInqService.getMonitorJobListPage(page, queryDTO);

        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("totalItems", page.getTotalItems());
        pageMap.put("items", page.getResults());
        return pageMap;
    }

    public Map getJobHistoryList(Map map) {
        int pageSize = MapUtils.getIntValue(map, "limit");
        int pageNo = MapUtils.getIntValue(map, "page");

        MonitorJobQueryDTO queryDTO = new MonitorJobQueryDTO();
        queryDTO.setEqptId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "eqptId")));
        queryDTO.setItemType(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "itemType")));
        queryDTO.setProductId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "productId")));
        queryDTO.setCarrierId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "carrierId")));
        queryDTO.setLotId(CheckRegexUtils.formatSearchString(MapUtils.getString(map, "lotId")));

        Page page = new Page(pageNo, pageSize);
        page = lotAutoMonitorInqService.getAutoMonitorJobHistoryPage(page, queryDTO);

        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("totalItems", page.getTotalItems());
        pageMap.put("items", page.getResults());
        return pageMap;
    }

    public Map queryMonitorItem(Map map) {
        String itemType = MapUtils.getString(map, "itemType");
        String eqptId = MapUtils.getString(map, "eqptId");
        Equipment equipment = emsService.getEquipment(eqptId, LocalContext.getFacilityRrn());
        if(Objects.nonNull(equipment)) {
            Long eqptRrn = equipment.getInstanceRrn();
            AutoMonitorItem item = autoMonitorItemInqService.getAutoMonitorActiveItem(eqptRrn, itemType);
            Map result = BeanUtils.copyBeanToMap(item);
            map.put("msg", result);
            map.put("success", true);
        }
        return map;
    }

    public Map getUnitList(Map map) {
        String lotId = MapUtils.getString(map, "lotId");
        Lot lot = lotQueryService.getLot(lotId);
        List resultList = new ArrayList();
        if (lot != null) {
            List<Unit> unitList = wipQueryService.getUnitList(lot.getLotRrn());
            unitList.sort(new Comparator<Unit>() {
                @Override
                public int compare(Unit o1, Unit o2) {
                    return o1.getPositionInCarrier().intValue() - o2.getPositionInCarrier().intValue();
                }
            });

            // List<String> vioUnitIdList = spcService.getLastSpcResultVioUnitIdList(lot.getLotRrn());

            for (Unit unit : unitList) {
                Map tempMap = MapUtils.newHashMap();
                tempMap.put("unitId", unit.getUnitId());
                tempMap.put("position", unit.getPositionInCarrier());
                tempMap.put("unitRrn", unit.getUnitRrn());
                tempMap.put("isVioUnit", NumberUtils.LONG_ZERO);
                tempMap.put("isUsedUnit", unit.getAutoMonitorUsedFlag() ? NumberUtils.LONG_ONE : NumberUtils.LONG_ZERO);
                resultList.add(tempMap);
            }
            map.put("msg", resultList);
            map.put("success", true);

        }
        return map;
    }

    public Map saveMonitorJob(Map map) {
        AutoMonitorJobDTO autoMonitorJobDTO = buildAutoMonitorJobDTO(map);

        // 卡控当前cst类型必须和目标cst相同
        if (autoMonitorJobDTO.getMonitorCarrierRrn() != null &&
                StringUtils.isNotEmpty(autoMonitorJobDTO.getMonitorCarrierRrn().toString())) {
            Carrier parentCst = carrierService.getCarrier(autoMonitorJobDTO.getParentLot().getCarrierRrn());
            Carrier targetCst = carrierService.getCarrier(autoMonitorJobDTO.getMonitorCarrierRrn());

            Assert.state(StringUtils.equalsIgnoreCase(parentCst.getObjectSubtype(), targetCst.getObjectSubtype()),
                         Errors.create().content("Carrier Type is not correct!").build());

            Assert.state(StringUtils.equals(targetCst.getCarrierStatus(), PcdStatus.FREE_KEY) ||
                                 StringUtils.equals(targetCst.getCarrierStatus(), PcdStatus.ASSEMBLY_KEY),
                         Errors.create().key(MessageIdList.CARRIER_STATUS_INVALID).args(targetCst.getInstanceId())
                               .build());
        }

        // 锁 lot
        Long lockLotRrn = autoMonitorJobDTO.getParentLot().getLotRrn();
        Long lotRrn = lotAutoMonitorReqService.saveMonitorJob(autoMonitorJobDTO, lockLotRrn);

        map.put("success", true);
        return map;
    }

    public Map cancelMonitorJob(Map map) {
        AutoMonitorJobDTO autoMonitorJobDTO = new AutoMonitorJobDTO();

        String lotId = MapUtils.getString(map, "lotId");
        Long baseLotRrn = MapUtils.getLong(map, "baseLotRrn");

        Lot parentLot = lotInqService.getLot(baseLotRrn);
        autoMonitorJobDTO.setParentLot(parentLot);

        Lot childLot = lotInqService.getLot(lotId);
        autoMonitorJobDTO.setChildLot(childLot);

        LotAutoMonitorInfo monitorInfo = lotAutoMonitorInqService.getLotAutoMonitorInfo(childLot.getLotRrn());
        Assert.state(monitorInfo.getMonitorCarrierRrn() == null ||
                             monitorInfo.getMonitorCarrierRrn().longValue() != monitorInfo.getCarrierRrn().longValue(),
                     Errors.create().key(MessageIdList.AUTOMONITOR_LOT_NEED_BACK).args(childLot.getLotId()).build());

        // 锁
        List<Long> lockLotRrns = new ArrayList<>();
        lockLotRrns.add(parentLot.getLotRrn());
        lockLotRrns.add(childLot.getLotRrn());

        lotAutoMonitorReqService.cancelMonitorJob(autoMonitorJobDTO, lockLotRrns);

        return map;
    }

    public Map getJobInfo(Map map) {
        Map<String, Object> returnInfo = MapUtils.newHashMap();
        Long lotRrn = MapUtils.getLong(map, "lotRrn");
        LotMonitorJobStore store = lotAutoMonitorInqService.getMonitorJob(lotRrn);

        Boolean canCancelJob = false;
        if(AutoMonitorUtils.checkJobStatusCanCancel(store.getJobStatus())) {
            canCancelJob = true;
        }

        List<AutoMonitorUnitInfo> unitList = lotAutoMonitorInqService.getAutoMonitorUnitInfoList(lotRrn);
        List<Map> unitArray = new ArrayList();
        List<Map> monitorUnitArray = new ArrayList<>();
        for(AutoMonitorUnitInfo unitInfo:unitList) {
            unitArray.add(BeanUtils.copyBeanToMap(unitInfo));

            Map monitorShowMap = BeanUtils.copyBeanToMap(unitInfo);
            monitorShowMap.put("position",MapUtils.getIntValue(monitorShowMap,"monitorCarrierPosition"));
            monitorUnitArray.add(monitorShowMap);
        }

        returnInfo.put("jobStore", store);
        returnInfo.put("unitList", unitArray);
        returnInfo.put("monitorMapping", monitorUnitArray);
        returnInfo.put("canCancelJob",canCancelJob);
        return returnInfo;
    }

    private AutoMonitorJobDTO buildAutoMonitorJobDTO(Map map) {
        AutoMonitorJobDTO autoMonitorJobDTO = new AutoMonitorJobDTO();

        String lotId = MapUtils.getString(map, "lotId");
        Lot parentLot = lotInqService.getLot(lotId);
        autoMonitorJobDTO.setParentLot(parentLot);

        Assert.state(StringUtils.equals(AutoMonitorOperationConstants.PARENT_IN_USE_STAGE, parentLot.getStageId()),
                     Errors.create().key(MessageIdList.AUTOMONITOR_LOT_STAGE_NOT)
                           .args(AutoMonitorOperationConstants.PARENT_IN_USE_STAGE).build());

        String selectedUnits = MapUtils.getString(map, "selectedUnits");
        List<Unit> parentUnitList = wipQueryService.getUnitList(parentLot.getLotRrn());
        List<Unit> unitList = new ArrayList<>();
        for (Unit unit : parentUnitList) {
            if (StringUtils.contains(selectedUnits, unit.getUnitId())) {
                unitList.add(unit);
            }
        }
        autoMonitorJobDTO.setUnitList(unitList);

        String eqptId = MapUtils.getString(map, "equipmentId");
        Equipment equipment = emsService.getEquipment(eqptId, LocalContext.getFacilityRrn());
        Assert.state(Objects.nonNull(equipment),
                     Errors.create().key(MessageIdList.EQUIPMENT_ID_NOT_EXIST).build());

        String itemType = MapUtils.getString(map, "itemType");
        Assert.state(StringUtils.isNotBlank(itemType),
                     Errors.create().key(MessageIdList.AUTOMONITOR_ITEM_TYPE_NULL).build());

        Long eqptRrn = equipment.getInstanceRrn();
        AutoMonitorItem monitorItem = autoMonitorItemInqService.getAutoMonitorActiveItem(eqptRrn, itemType);
        autoMonitorJobDTO.setMonitorItem(monitorItem);

        Assert.state(parentLot.getProductRrn().longValue() == monitorItem.getProductRrn().longValue(),
                     Errors.create().key(MessageIdList.AUTOMONITOR_LOT_PRODUCT_INVALID).build());

        Assert.state(monitorItem.getQty().intValue() == unitList.size(),
                     Errors.create().key(MessageIdList.AUTOMONITOR_ITEM_QTY_NOT_MATCH).args(monitorItem.getQty())
                           .build());

        if (monitorItem.getMonitorCarrierFlag()) {
            String monitorCarrierId = MapUtils.getString(map, "monitorCarrierId");
            Carrier monitorCarrier = carrierService.getCarrier(LocalContext.getFacilityRrn(),monitorCarrierId);
            Assert.state(Objects.nonNull(monitorCarrier),
                         Errors.create().key(MessageIdList.CARRIER_CARRIER_UNAVAILABLE).build());

            Assert.state(monitorCarrier.getInstanceRrn() != parentLot.getCarrierRrn().longValue(),
                         Errors.create().key(MessageIdList.AUTOMONITOR_MONITOR_CARRIER_SAME).build());

            List<MonitorCarrierMapping> carrierMappings = lotAutoMonitorInqService
                    .getMonitorCarrierMappings(monitorCarrier.getInstanceRrn());
            List<Long> lotRrns = new ArrayList<>();
            for (MonitorCarrierMapping carrierMapping : carrierMappings) {
                if (!lotRrns.contains(carrierMapping.getLotRrn())) {
                    lotRrns.add(carrierMapping.getLotRrn());
                }
            }

            if (StringUtils.equals(AutoMonitorUtils.AutoMonitorItemMonitorCarrierType.SINGLE.toString(),
                                   monitorItem.getMonitorCarrierType())) {
                Assert.state(CollectionUtils.isEmpty(lotRrns),
                             Errors.create().key(MessageIdList.AUTOMONITOR_MONITOR_CARRIER_TYPE)
                                   .args(AutoMonitorUtils.AutoMonitorItemMonitorCarrierType.SINGLE.toString()).build());
            }
            if (CollectionUtils.isNotEmpty(lotRrns)) {
                LotAutoMonitorQueryDTO queryDTO = new LotAutoMonitorQueryDTO();
                queryDTO.setLotRrns(lotRrns);
                List<LotAutoMonitorInfo> monitorInfos = lotAutoMonitorInqService.getLotMonitorLotList(queryDTO);
                for (LotAutoMonitorInfo lotMonitorInfo : monitorInfos) {
                    Assert.state(autoMonitorJobDTO.getMonitorItem().getEqptRrn().longValue() ==
                                         lotMonitorInfo.getMainEqptRrn().longValue(),
                                 Errors.create().key(MessageIdList.AUTOMONITOR_ITEM_EQPT_DIFFERENT)
                                       .args(autoMonitorJobDTO.getMonitorItem().getEqptId(),
                                             lotMonitorInfo.getMainEqptId()).build());

                    AutoMonitorItem _monitorItem = autoMonitorItemInqService
                            .getAutoMonitorItem(lotMonitorInfo.getMainEqptRrn(), lotMonitorInfo.getItemType());
                    Assert.state(Objects.isNull(_monitorItem) || !StringUtils
                                         .equals(AutoMonitorUtils.AutoMonitorItemMonitorCarrierType.SINGLE.toString(),
                                                 _monitorItem.getMonitorCarrierType()),
                                 Errors.create().key(MessageIdList.AUTOMONITOR_MONITOR_CARRIER_TYPE)
                                       .args(AutoMonitorUtils.AutoMonitorItemMonitorCarrierType.SINGLE.toString())
                                       .build());
                }
            }

            autoMonitorJobDTO.setMonitorCarrierRrn(monitorCarrier.getInstanceRrn());
            autoMonitorJobDTO.setMonitorCarrierId(monitorCarrierId);

            List<Unit> monitorCarrierUnitList = new ArrayList<>();
            String monitorCarrierList = MapUtils.getString(map, "monitorCarrierList");
            if (StringUtils.isNotBlank(monitorCarrierList)) {
                List array = (List) map.get("monitorCarrierList");
                for (int i = 0; i < array.size(); i++) {
                    Map unitInfo = (Map) array.get(i);

                    Unit unit = new Unit();
                    unit.setUnitId(MapUtils.getString(unitInfo, "unitId"));
                    unit.setUnitRrn(MapUtils.getLong(unitInfo, "unitRrn"));
                    unit.setPositionInCarrier(MapUtils.getIntValue(unitInfo, "position"));
                    unit.setLotRrn(NumberUtils.toLong(MapUtils.getString(unitInfo, "lotRrn")));
                    monitorCarrierUnitList.add(unit);
                }
                autoMonitorJobDTO.setMonitorCarrierUnitList(monitorCarrierUnitList);
            }
        }

        Lot childLot = new Lot();
        BeanUtils.copyProperties(parentLot, childLot);
        childLot.setLotRrn(0);
        childLot.setLotId(getChildLotId(parentLot.getLotId(), LocalContext.getFacilityRrn()));
        childLot.setQty1(new Double(unitList.size()));
        childLot.setCarrierSharedFlag(childLot.getLotId());
        childLot.setCarrierRrn(parentLot.getCarrierRrn());
        childLot.setCarrierId(parentLot.getCarrierId());
        autoMonitorJobDTO.setChildLot(childLot);

        return autoMonitorJobDTO;
    }

}