NpwCreateLotSaveAction.java

package com.mycim.webapp.actions.createlot;

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.i18n.Languages;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.MiscUtils;
import com.mycim.framework.utils.beans.BeanUtils;
import com.mycim.framework.utils.beans.PropertyUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.utils.WipUtils;
import com.mycim.valueobject.LocationNames;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.NamedObject;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.ems.Carrier;
import com.mycim.valueobject.inv.LotInventoryDO;
import com.mycim.valueobject.inv.Order;
import com.mycim.valueobject.prp.Item;
import com.mycim.valueobject.prp.Operation;
import com.mycim.valueobject.prp.ProcessLoopInfo;
import com.mycim.valueobject.prp.SapphireProduct;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.LotSapphreInfo;
import com.mycim.valueobject.wip.LotStatus;
import com.mycim.valueobject.wip.PlanLot;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.NpwSetupAction;
import com.mycim.webapp.forms.LotInfoFormNpw;
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.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class NpwCreateLotSaveAction extends NpwSetupAction {

    protected static final String WAITING_KEY = "WAITING";

    protected static final String DUMMY_KEY = "DUMMY";

    private static final String LOT_PLAN_START = "lotPlanStart";

    private static final int LESS = -1;

    private static final int EQUAL = 0;

    private static final int MORE = 1;

    protected static String TRUE = "1";

    protected static String FALSE = "0";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        request.setAttribute("disableFlag", "true");
        theform.setScreenStatus("LOT_PLAN_START");
        request.setAttribute("disableFlag", "true");
        request.setAttribute("isshow", "FALSE");
        request.setAttribute("productRrn", 0);
        return mapping.findForward(LOT_PLAN_START);
    }
    // TODO  这个方法里面用到的if相关代码已经分离出来成为独立的方法了,其他代码目前投片逻辑没有用到
    /*public ActionForward npwCreateLotSave(ActionMapping mapping, ActionForm form, HttpServletRequest
    request,
                                 HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        LotInfoFormNpw theform = (LotInfoFormNpw) form;

        Lot lot = null;
        if (request.getParameter("selectFlag") != null) {
            String lotType = theform.getLotType();
            if ("PP".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Production Lot");

            } else if ("PC".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Customer Pilot Lot");

            } else if ("PB".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Customer Pilot Lot");

            } else if ("PA".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Customer Pilot Lot");

            } else if ("PE".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Probe Lot");

            } else if ("EE".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Engineer Lot");

            } else if ("EL".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Sort Loop Lot");

            } else if ("TT".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("TD Developing Lot");

            } else if ("TL".equalsIgnoreCase(lotType)) {
                theform.setCreateCategoryDetail("Sort Loop Lot");
            }
            return (mapping.findForward("confimLotId"));
        } else if (request.getParameter(Constants.CANCEL_KEY) != null) {

            request.setAttribute("create_lot_flag", "true");

            if (mapping.getAttribute() != null) {
                request.removeAttribute(mapping.getAttribute());
            }

            theform.setByPlanLotFlag("product");
            theform.setCreatedPlanLotId("");
            theform.setLotId("");
            request.removeAttribute(SessionNames.LOT_KEY);
            String isshow = (String) request.getAttribute("isshow");
            if ("FALSE".equalsIgnoreCase(isshow)) {
                return mapping.findForward("setupfalse");
            } else if ("TRUE".equalsIgnoreCase(isshow)) {
                return mapping.findForward("setuptrue");
            } else {
                return mapping.findForward("setup");
            }
        } else if (request.getParameter(Constants.MAIN_KEY) != null) {
            request.setAttribute("create_lot_flag", "true");
            lot = (Lot) request.getAttribute(SessionNames.LOT_KEY);
                PropertyUtils.copyProperties(theform, lot);
                theform.setProcessStepIdVersion(((lot.getProcessStepIdVersion().split("\\|"))[1]).split(",
                ")[0]);

            request.setAttribute("productRrn", lot.getProductRrn());
            theform.setDueDateS(timestampToString(lot.getDueDate()));

            return mapping.findForward("lotPlanStart");
        } else if (request.getParameter("confimed") != null) {
            theform.setLotId(theform.getLotId());
            theform.setQty1(theform.getQty1());
            theform.setCreatedPlanLotId(theform.getCreatedPlanLotId());
            theform.setPages(theform.getPages());
            theform.setTrackUnitFlag(theform.getTrackUnitFlag());
            theform.setKeepUnitHistoryFlag(theform.getKeepUnitHistoryFlag());
            theform.setCreatedPlanLotRrn(theform.getCreatedPlanLotRrn());
            theform.setByPlanLotFlag(theform.getByPlanLotFlag());

            long lotOwnerRrn = 0;
            lotOwnerRrn = this.getInstanceRrn(theform.getLotOwner().toUpperCase().trim(),
                                              this.getNamedSpace("USER", facilityRrn), "USER");
            if (lotOwnerRrn == 0) {
                throw new WebException("lotplan.lotowner_cannot_be_empty", "Lot owner cannot be empty");
            }

            User userList = new User();
            userList.setInstanceRrn(lotOwnerRrn);
                userList = securityService.getUser(userList);

            if (userList.getUserName() != null) {
                theform.setLotOwner(theform.getLotOwner().toUpperCase().trim() + " " + userList.getUserName
                ());
            } else {
                theform.setLotOwner(theform.getLotOwner().toUpperCase().trim());
            }
            return mapping.findForward("detail");
        } else if (request.getParameter("cancelLotPlanNext") != null) {
            theform.setLotId("");
            request.removeAttribute(SessionNames.LOT_KEY);
            return mapping.findForward("cancelLotPlanNext");
        } else if (request.getParameter(Constants.CREATE_KEY) != null) {

            long _lotRrn = 0;
                lot = (Lot) request.getAttribute(SessionNames.LOT_KEY);
                if (StringUtils.isNotBlank(lot.getCustomerWaferId())
                    && isValidUnitId(lot.getCustomerWaferId(), facilityRrn)) {
                    throw new WebException("npwcreatelot.unitId_already_exists", "晶圆号已经存在!");
                }
                _lotRrn = lotQueryService.getLotRrn(lot.getLotId());

            if (_lotRrn > 0) {
                throw new WebException("npwcreatelot.lot_already_exists", "Lot existed!");
            }

            *//*Collection rawMaterials = lot.getMaterialinfo();*//*
            Collection rawMaterials = null;
            HashMap transInfo = new HashMap();
            transInfo.put("startFlag", lot.getStartedFlag());
            lot.setLotOwner(theform.getLotOwner());
            lot.setSplitMergeFlag(LocationNames.initLotFlagName(lot.getProcessId()));
            transInfo.put("lot", lot);
            transInfo.put("lotid", lot.getLotId());
            transInfo.put("qty", lot.getQty1() + "");
            transInfo.put("fromoperation", "3333");
            transInfo.put("tooperation", lot.getOperationId());
            transInfo.put("productRrn", lot.getProductRrn());
            //
            String temp = lot.getProcessStepVersion();
            String route = "";
            if (temp != null) {
                int i = 0;
                int j = 0;
                i = temp.indexOf("|");

                // find first '|'
                if (i != -1) {
                    j = temp.indexOf("|", i + 1);

                    // find se '|'
                    // string is aaa|bbb|cccc
                    if (j > 0) {
                        route = temp.substring(i + 1, j);
                    } else if (i > 0) { // aaa|bbb
                        route = temp.substring(0, i);
                    }
                }
            }
            route = route.replace(',', '.');

            transInfo.put("toroute", route);
            transInfo.put("transPerformedby", LocalContext.getUserId());
            transInfo.put("keepUnitHistoryFlag", theform.getKeepUnitHistoryFlag());
            transInfo.put("trackUnitFlag", theform.getTrackUnitFlag());
            transInfo.put("unitList", request.getParameterValues("unitList"));

            Object[] testItems = request.getParameterValues("unitList");
            transInfo.put("positionList", getPositionList(lot.getQty1()));
            transInfo.put("rawMaterials", rawMaterials);
            for (Iterator it = rawMaterials.iterator(); it.hasNext();) {
                HashMap testItem = (HashMap) it.next();
            }

            transInfo.put("planLotRrn", lot.getCreatedPlanLotRrn());
            transInfo.put("lotComments", theform.getLotComments());

                *//*String message = createLotWorkStream(transInfo, facilityRrn, LocalContext.getUserId());

                if (message != null) {
                    request.setAttribute(ErrorDef.MYCIM_ERR_KEY, new WSIDefException(message));

                    return mapping.findForward("error");
                }*//*

                Map resultsInfo = createLot(transInfo);
                // 投片后 数据库中创建了一个母批
                createLotSapphireInfo(Long.valueOf(transInfo.get("productRrn").toString()),
                                      Long.valueOf(resultsInfo.get("lotRrn").toString()));
                request.setAttribute("lotRrn", resultsInfo.get("lotRrn"));
                if (request.getAttribute("attributeRrns") != null) {
                    transInfo = new HashMap();
                    transInfo.put("attributeRrns", request.getAttribute("attributeRrns"));
                    transInfo.put("attributeValues", request.getAttribute("attributeValues"));
                    transInfo.put("transRrn", resultsInfo.get("transRrn"));
                    transInfo.put("instanceRrn", resultsInfo.get("lotRrn"));
                    maintainTransAttributes(transInfo);
                }

                String language = "EN";

                if (request.getAttribute(SessionNames.LANGUAGE_KEY) != null) {
                    language = (String) request.getAttribute(SessionNames.LANGUAGE_KEY);
                }
                    saveLotSeqAttribute(((Long) resultsInfo.get("lotRrn")).longValue(), facilityRrn,
                                        lot.getProductRrn(), language);


        } else if (request.getParameter("cancelLotPlan") != null) {
            String lotId = theform.getLotId();
                if (lotId == null || lotId.trim().length() == 0) {
                    throw new WebException("lot.id_empty", "批次号不能为空!");
                } else {
                    lot = lotService.getLotPlan(lotId.trim().toUpperCase());
                    if (lot.getLotRrn() == 0) {
                        throw new WebException(I18nUtils.getMessage("lot.lot_not_exist_or_cast"));
                    } else {
                        lotService.deleteLotPlan(lot);
                        throw new WebException("npwcreatelot.cast_is_cancel", "批次已取消投片!");
                    }
                }

        } else if (request.getParameter("addMaterial") != null) {
            // insert into lot_plan
            String[] units = request.getParameterValues("unitList");
            Object[] confirmFlags = request.getParameterValues("confirmFlag");
            Collection rawMaterials = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);

            lot = (Lot) request.getAttribute(SessionNames.LOT_KEY);
            if (validateQty(theform.getQty1(), rawMaterials) == MORE) {
                throw new WebException("lot.materials_too_much", "Too much raw materials selected!");
            } else if (validateQty(theform.getQty1(), rawMaterials) == LESS) {
                throw new WebException("lot.materials_not_enough", "Not enough raw materials selected!");
            }

            units = parseUnitListString(units, rawMaterials, lot.getLotId());

            lot.setCustomerWaferId(Arrays.asList(units).toString().replace('[', ' ').replace(']', ' ').trim
            ().toUpperCase());
            if (StringUtils.isNotBlank(lot.getCustomerWaferId())
                && isValidUnitId(lot.getCustomerWaferId(), facilityRrn)) {
                throw new WebException("npwcreatelot.unitId_already_exists", "晶圆号已经存在!");
            }

            if (!validateUniqueUnit(units)) {
                throw new WebException("unit.id_must_unique", "Unit ID must be Unique!");
            }
            int i = 0;
            for (Iterator it = rawMaterials.iterator(); it.hasNext();) {
                HashMap item = (HashMap) it.next();
                if ((units[i] != null) && !"".equals(units[i])) {
                    // && ("true").equals(String.valueOf(confirmFlags[i]))
                    item.put("unitList", units[i++].toUpperCase());
                } else {
                    throw new WebException("unit.id_must_specified", "Units must be specified!");
                }
            }

            *//*lot.setMaterialinfo(rawMaterials);*//*
            request.setAttribute(SessionNames.LOT_KEY, lot);
                long lotRrn = lotQueryService.getLotRrn(lot.getLotId());
                Lot lotTemp = lotService.getLotPlan(lot.getLotId());
                if ((lotTemp.getLotRrn() > 0 && lotTemp.getLotRrn() != theform.getLotRrn()) || lotRrn > 0) {
                    *//*request.setAttribute(ErrorDef.MYCIM_ERR_KEY, new ValidateFailureException("Lot
                    existed!"));
                    request.setAttribute("confimLotIdFlag", "0");
                    return mapping.findForward(Constants.ERROR_KEY);*//*
                }

                lotService.insertLotPlan(lot);
            if (lot != null) {
                String lotid = lot.getLotId();
                request.setAttribute("sucLotId", lotid);
            }
            request.setAttribute("savedFlag", "true");
            return mapping.findForward("detail");
            // return mapping.findForward("setupfalse");
        } else if (request.getParameter("cancelAddMaterial") != null) {
            // 回到建批页面
                lot = (Lot) request.getAttribute(SessionNames.LOT_KEY);

                PropertyUtils.copyProperties(theform, lot);
                theform.setProcessStepIdVersion(((lot.getProcessStepIdVersion().split("\\|"))[1]).split(",
                ")[0]);
                theform.setScreenStatus("CREATE_PLAN_LOT");
                theform.setLotOwner(lot.getLotOwner().split(" ")[0]);
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
                theform.setDueDateS(sdf.format(new Date(lot.getDueDate().getTime())));
            return mapping.getInputForward();
        } else {
            RootForm rootForm = new RootForm();
            rootForm.setPages(theform.getPages());

                processItemAction(request, rootForm);
        }

            // Add by Frankylee 2007-11-20
            // Regist the lot's order info
            Order order = new Order();
            order = (Order) request.getAttribute("ordinfo");
            if (order != null && order.getOrder_Id() != null && order.getOrder_Id().trim().length() > 0) {

                HashMap lotordinfo = new HashMap();
                long lotrrn = lotQueryService.getLotRrn(lot.getLotId());
                lotordinfo.put("lot_rrn", String.valueOf(lotrrn));
                lotordinfo.put("lot_id", lot.getLotId());
                int lotqty = lot.getQty1().intValue();
                String lotqty2 = String.valueOf(lotqty);
                lotordinfo.put("lot_qty", lotqty2);
                lotordinfo.put("order_id", order.getOrder_Id());
                lotordinfo.put("order_id_market", order.getMarket_order_Id().toString().trim());
                lotordinfo.put("order_rrn", order.getOrder_RRN());
                lotordinfo.put("order_id_type", order.getOrder_id_type());
                HashMap lottrans = new HashMap();
                Lot lot2 = new Lot();
                lot2 = lotQueryService.getLot(lot.getLotId().toString().trim());
                *//*lottrans = (HashMap) this.getBaseManager().getLotTransInfo(String.valueOf(lot2
                .getLotRrn()));*//*
                lotordinfo.put("lot_trnasname", lottrans.get("trans_rrn"));
                lotordinfo.put("trans_sequence", lottrans.get("TRANS_SEQUENCE"));
                String ordertype = lotordinfo.get("order_id_type").toString().trim();
                *//*this.getInvManager().RegLotOrdInfo(lotordinfo, ordertype);*//*
                String dummySubOrderId = request.getAttribute("dummySubOrderId").toString();
                *//*if (ordertype.equalsIgnoreCase(ObjectList.ORDER_SUB_DUMMY)) {
                    this.getInvManager().UpdateSubDummyOrderRemainQty(dummySubOrderId,
                                                                      lotordinfo.get("order_id_market")
                                                                      .toString(),
                                                                      lotordinfo.get("lot_qty").toString(),
                                                                      ObjectList.ORDER_SUB_DUMMY);
                }*//*
                request.removeAttribute("ordinfo");
                request.removeAttribute("dummySubOrderId");
            }

        request.removeAttribute("sequence");
        theform.setByPlanLotFlag("product");
        theform.setCreatedPlanLotId("");

        request.setAttribute("isDummyLot", "1");
        return mapping.findForward("npwlotcurrentinfo");
    } // end of perform()*/

    public ActionForward nextPlanLot(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        request.setAttribute("facility", facilityRrn);

        Assert.isFalse(StringUtils.isNotBlank(theform.getCustomerWaferId()) &&
                               isValidUnitId(theform.getCustomerWaferId(), facilityRrn),
                       Errors.create().key(MessageIdList.NPWCREATELOT_CUSTOMER_ALREADY_EXISTS)
                             .content("客户片号已经存在。请更改客户批号!").build());

        Assert.isFalse(theform.getIntQty1() != null && theform.getIntQty1().intValue() > 25,
                       Errors.create().key(MessageIdList.NPWCREATELOT_UNITS_CANNOT_EXCEED).content("晶圆不能超过25!")
                             .build());

        if (theform.getOrder_Id() != null && theform.getOrder_Id().trim().length() > 0) {
            Order order = new Order();
            order = (Order) request.getAttribute("ordinfo");

            int remain = 0;
            int total = 0;
            int runing = 0;
            int reg_qty = 0;
            total = Integer.parseInt(order.getOrder_Qty().trim());
            runing = Integer.parseInt(order.getRuning_qty().trim());
            // remain = total - runing;
            remain = Integer.parseInt(order.getRemain_Qty().trim());
            reg_qty = theform.getQty1().intValue();
            if (reg_qty > remain) {
                request.setAttribute("confimLotIdFlag", "0");
                throw new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.NPWCREATELOT_QTY_IS_NOT_ENOUGH).content("Qty is NOT Enough!")
                              .build());
            }
            request.setAttribute("ordinfo", order);
            String dummySubOrderId = request.getAttribute("dummySubOrderId").toString();
            request.setAttribute("dummySubOrderId", dummySubOrderId);
        }
        String line = request.getParameter("lineID");


        if (theform.getCreatedPlanLotId() != null && !theform.getCreatedPlanLotId().trim().equals("")) {

            PlanLot pLot = lotService.getPlanLot(new PlanLot(facilityRrn, theform.getCreatedPlanLotId()));
            if (pLot != null) {

                if (pLot.getCreatedLotQty1() == null || pLot.getCreatedLotQty1() != null &&
                        (new Double(MiscUtils.parseSQL(pLot.getQty1()) - MiscUtils.parseSQL(pLot.getCreatedLotQty1())))
                                .compareTo(theform.getQty1()) < 0) {
                    request.setAttribute("confimLotIdFlag", "0");
                    throw new SystemIllegalArgumentException(Errors.create().content("超过订单数量!").build());
                }

            }
        }

        String lotId = null;
        boolean flag = true;

        if ((theform.getLotId() != null) && !theform.getLotId().trim().equals("")) {
            lotId = theform.getLotId().trim().toUpperCase();
            if (lotId.indexOf(",") > 0) {
                request.setAttribute("confimLotIdFlag", "0");
                throw new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.BANK_INVALID_LOT).content("Invalid lot Id!").build());
            }

            flag = false;
            request.setAttribute("id_flag", "define");
        }

        if (theform.getCarrierId() != null && !theform.getCarrierId().trim().equals("")) {
            Carrier carrier = new Carrier();
            String carrierId = theform.getCarrierId().trim().toUpperCase();
            theform.setCarrierId(carrierId);
            carrier = carrierService.getCarrier(LocalContext.getFacilityRrn(), carrierId);
            carrier.setInstanceId(carrierId);
            carrier.setObject(ObjectList.ENTITY_KEY);
            carrier.setNamedSpace(getNamedSpace(ObjectList.ENTITY_KEY, facilityRrn));

            if ((carrier == null) || (carrier.getInstanceRrn() <= 0)) {
                request.setAttribute("confimLotIdFlag", "0");

                throw new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.CARRIER_CASSETTE_EMPTY).content("晶舟号不能为空!").build());
            }

            if ((theform.getQty1() != null) &&
                    (theform.getQty1().compareTo(new Double(carrier.getAvailableSlotCount().toString())) > 0)) {
                request.setAttribute("confimLotIdFlag", "0");
                throw new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.NPWCREATELOT_AVAILABLESLOT_IS_NOT_ENOUGH).content("可用片槽不够!")
                              .build());
            }

            if (theform.getLotOwner() == null || theform.getLotOwner().trim().length() < 1) {
                request.setAttribute("confimLotIdFlag", "0");
                throw new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.LOTPLAN_LOTOWNER_CANNOT_BE_EMPTY)
                              .content("Lot owner cannot be empty").build());
            }

        }

        if ((theform.getQty1() != null) && (theform.getQty1().compareTo(new Double(0)) <= 0)) {
            request.setAttribute("confimLotIdFlag", "0");
            throw new SystemIllegalArgumentException(
                    Errors.create().key(MessageIdList.NPWCREATELOT_LOT_QUANTITY_LARGER_THAN_ZERO).content("批次数量必须大于0!")
                          .build());
        }
        if (theform.getLotOwner() == null || theform.getLotOwner().trim().length() < 1) {
            request.setAttribute("confimLotIdFlag", "0");
            throw new SystemIllegalArgumentException(Errors.create().key(MessageIdList.LOTPLAN_LOTOWNER_CANNOT_BE_EMPTY)
                                                           .content("Lot owner cannot be empty").build());
        }
        String isshow = (String) request.getAttribute("isshow");

        Lot lot = new Lot();
        String lotType = theform.getLotType();
        PropertyUtils.copyProperties(lot, theform);
        request.setAttribute("planlotrrn", lot.getCreatedPlanLotRrn());

        lot.setFacilityRrn(facilityRrn);
        lot.setLotId(lot.getLotId().trim().toUpperCase());
        theform.setLotId(lot.getLotId().trim().toUpperCase());
        lot.setQty1(theform.getQty1());
        lot.setProcessRrn(theform.getProcessRrn());
        lot.setStepSequence(new Long(TRUE));
        lot.setLotStatus(WAITING_KEY);
        if (lot.getHotFlag() == null || lot.getHotFlag().trim().equals("")) {
            lot.setHotFlag(FALSE);
        }
        lot.setQueueTimestamp(new Timestamp(System.currentTimeMillis()));

        if (theform.getDueDateS() != null && !theform.getDueDateS().trim().equalsIgnoreCase("")) {

            long nowTime = System.currentTimeMillis();

            Timestamp dueDate = DateUtils.stringToTimestamp(theform.getDueDateS() + " 00:00:00");

            if (dueDate != null) {
                if (dueDate.getTime() < nowTime) {
                    request.setAttribute("confimLotIdFlag", "0");
                    throw new SystemIllegalArgumentException(
                            Errors.create().key(MessageIdList.LOTPLAN_DUEDATE_CURRENTDATE_INCORRECT)
                                  .content("dueDate must after the current date").build());
                }
            }

            lot.setDueDate(DateUtils.stringToTimestamp(theform.getDueDateS() + " 00:00:00"));

        }
        lot.setProductRrn(new Long(
                getInstanceRrn(lot.getProductId(), getNamedSpace(ObjectList.PRODUCT_KEY, facilityRrn),
                               ObjectList.PRODUCT_KEY)));
        if (theform.getCarrierId() != null && !theform.getCarrierId().trim().equals("")) {
            lot.setCarrierRrn(new Long(
                    getInstanceRrn(lot.getCarrierId(), getNamedSpace(ObjectList.ENTITY_KEY, facilityRrn),
                                   ObjectList.ENTITY_KEY)));

            if (lot.getCarrierRrn().compareTo(new Long(0)) < 0) {
                request.setAttribute("confimLotIdFlag", "0");
                new SystemIllegalArgumentException(
                        Errors.create().key(MessageIdList.CARRIER_CASSETTE_EMPTY).content("晶舟号不能为空!").build());
            }
        }
        lot.setProcessVersion(getProcessVersion(MiscUtils.parseSQL(lot.getProcessRrn())));
        if ((theform.getCreateCategory() != null) && theform.getCreateCategory().equals(DUMMY_KEY)) {
            lot.setDummyFlag(TRUE);

        } else {
            lot.setDummyFlag(FALSE);
        }
        String trackUnitFlag = "0";
        String keepUnitHistoryFlag = "0";
        String totalProcessTime = "";
        String stageId = "";
        String layerId = "";
        Long borRrn = new Long(0);
        Long operationRrn = new Long(0);
        Integer operationVer = new Integer(0);
        Long executionRrn = new Long(0);
        String processStepVersion = null;
        String processStepIdVersion = null;
        String processStepVersion4wfl = null;

        String stepNumber = request.getParameter("stepNumber");
        Map tempInfo = getStepsInfoByLot(lot, lot.getProcessRrn(), lot.getProcessVersion(), stepNumber);

        executionRrn = (Long) tempInfo.get("executionRrn");
        operationRrn = (Long) tempInfo.get("operationRrn");

        if (!checkOperationInFacility(operationRrn, facilityRrn)) {
            request.setAttribute("confimLotIdFlag", "0");
            throw new SystemIllegalArgumentException(
                    Errors.create().key(MessageIdList.NPWCREATELOT_OPERATION_NOTBE_CURRENT_FACILITY)
                          .content("批次第一步步骤不在当前车间!").build());
        }
        if (theform.getCarrierId() != null && !theform.getCarrierId().trim().equals("")) {
            List lotsInSameCarrier = wipQueryService
                    .getLotsByEqpt(" WHERE CARRIER_RRN = ", MiscUtils.parseSQL(lot.getCarrierRrn()));

            Lot item = null;

            for (Iterator it = lotsInSameCarrier.iterator(); it.hasNext(); ) {
                item = (Lot) it.next();

                if ((item.getLotStatus() == null) || !item.getLotStatus().equals(LotStatus.WAITING)) {
                    request.setAttribute("confimLotIdFlag", "0");
                    throw new SystemIllegalArgumentException(
                            Errors.create().key(MessageIdList.NPWCREATELOT_CARRIER_SELECTED_USED).content("晶舟已被使用!")
                                  .build());
                }

                if (item.getOperationRrn().compareTo(operationRrn) != 0) {
                    request.setAttribute("confimLotIdFlag", "0");
                    throw new SystemIllegalArgumentException(
                            Errors.create().key(MessageIdList.NPWCREATELOT_CARRIER_IN_DIFFERENT_OPERATION)
                                  .content("晶舟正在进行不同的操作!").build());
                }
            }

        }
        operationVer = (Integer) tempInfo.get("operationVer");
        stageId = (String) tempInfo.get("stageId");
        layerId = (String) tempInfo.get("layerId");
        processStepVersion = (String) tempInfo.get("processStepVersion");
        processStepIdVersion = (String) tempInfo.get("processStepIdVersion");
        processStepVersion4wfl = (String) tempInfo.get("processStepVersion4wfl");

        lot.setNextOperationRrn1((Long) tempInfo.get("nextoperationRrn1"));

        if ((lot.getNextOperationRrn1() != null) && (lot.getNextOperationRrn1().compareTo(new Long(0)) > 0)) {
            lot.setNextOperationId1(getInstanceId(lot.getNextOperationRrn1().longValue()));
        }

        lot.setNextStepVersion1((String) tempInfo.get("nextprocessStepVersion1"));
        lot.setNextStepIdVersion1((String) tempInfo.get("nextprocessStepIdVersion1"));

        lot.setNextOperationRrn2((Long) tempInfo.get("nextoperationRrn2"));

        if ((lot.getNextOperationRrn2() != null) && (lot.getNextOperationRrn2().compareTo(new Long(0)) > 0)) {
            lot.setNextOperationId2(getInstanceId(lot.getNextOperationRrn2().longValue()));
        }

        lot.setNextStepVersion2((String) tempInfo.get("nextprocessStepVersion2"));
        lot.setNextStepIdVersion2((String) tempInfo.get("nextprocessStepIdVersion2"));
        tempInfo = prpService.getOperationInfo(operationRrn, operationVer);

        trackUnitFlag = (String) tempInfo.get("trackUnitFlag");
        keepUnitHistoryFlag = (String) tempInfo.get("keepUnitHistoryFlag");

        tempInfo = new HashMap();
        tempInfo.put("operationRrn", operationRrn);
        tempInfo.put("productRrn", lot.getProductRrn());
        tempInfo.put("routeRrn", WipUtils.parseRouteRrn(processStepVersion) + "");
        tempInfo.put("technologyRrn", lot.getProcessRrn());
        tempInfo.put("recipeRrn", null);
        tempInfo.put("lotRrn", null);

                /*Map resultInfo = getProcessManager().getBorbyContext(tempInfo);
                borRrn = (Long) resultInfo.get("borRrn");*/

        if ((lot.getScheduleDueDate() != null) && (lot.getDueDate() != null) &&
                lot.getScheduleDueDate().after(lot.getDueDate())) {
            lot.setLastScheduleFlag(TRUE);
        }

        lot.setProcessStepVersion(processStepVersion.toString());
        lot.setProcessStepIdVersion(processStepIdVersion.toString());
        lot.setWflStepPath(processStepVersion4wfl);
        lot.setExecutionRrn(executionRrn);
        lot.setOperationRrn(operationRrn);
        lot.setOperationVersion(operationVer);
        lot.setOperationId(this.getInstanceId(operationRrn.longValue()));
        lot.setStageId(stageId);
        lot.setLayerId(layerId);
        lot.setBorRrn(borRrn);
        lot.setBeforeStatus("");
        lot.setInputQty1(theform.getQty1());
        lot.setInputQty2(theform.getQty2());
        lot.setStartedFlag(TRUE);
        lot.setReticleGroupRrn(theform.getReticleGroupRrn());
        theform.setTrackUnitFlag(trackUnitFlag);
        theform.setKeepUnitHistoryFlag(keepUnitHistoryFlag);
        theform.setLotId(lot.getLotId());
        if (theform.getCarrierId() == null || theform.getCarrierId().trim().equals("")) {
            theform.setCarrierId(lot.getLotId());
        }
        theform.setPages(new Integer(1));

        request.setAttribute("productRrn", lot.getProductRrn());
        request.setAttribute("lotType", lot.getLotType());

        String waferType = "";

        if (lot.getLotType() != null && lot.getCreateCategory() != null) {

            if (lot.getLotType().equalsIgnoreCase("C") && lot.getCreateCategory().equalsIgnoreCase("DUMMY")) {
                waferType = "CD";
            } else if (lot.getLotType().equalsIgnoreCase("E") && lot.getCreateCategory().equalsIgnoreCase("DUMMY")) {
                waferType = "ED";
            } else if (lot.getLotType().equalsIgnoreCase("C")) {
                waferType = "CP";
            } else if (lot.getLotType().equalsIgnoreCase("E")) {
                waferType = "EP";
            }

        }

        if (theform.getReticleGroupRrn() == 0) {
            long reticleGroupRrn = dmmService.getProductDefaultReticleGroupRrn(lot.getProductRrn().longValue());
            lot.setReticleGroupRrn(reticleGroupRrn);
        } else {
            lot.setReticleGroupRrn(theform.getReticleGroupRrn());
        }

        request.setAttribute("waferType", waferType);
        theform.setProductRrn(lot.getProductRrn());
        request.setAttribute(SessionNames.LOT_KEY, lot);
        request.setAttribute(SessionNames.COLLECTION_KEY, new ArrayList());
        theform.setCacheLot(WebUtils.getCacheObj2String(lot));
        // add by steven for fmi confim lot id
        if (("TRUE".equalsIgnoreCase(isshow)) && (flag == false)) {
            request.setAttribute("confimLotIdFlag", "1");
            request.setAttribute("confimLotId", lotId);
            return (mapping.findForward("confimLotId"));
        }
        // end
        return mapping.findForward("detail");
    }

    public ActionForward addMember(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        request.setAttribute("facility", LocalContext.getFacilityRrn());
        Lot lot = (Lot) WebUtils.getCacheString2Obj(theform.getCacheLot());
        theform.setCustomerWaferId("");
        List rawMaterials = (List) WebUtils.getCacheString2Obj(theform.getCacheRawMaterials());
        if (rawMaterials == null) {
            rawMaterials = new ArrayList();
        }
        Order order = new Order();
        order = (Order) request.getAttribute("ordinfo");
        Assert.notNull(theform.getSpecifiedQty(),
                       Errors.create().key(MessageIdList.NPWCREATELOT_CONSUMED_QUANTITY_NOTBE_EMPTY)
                             .content("消耗数量不能为空!").build());

        Assert.isFalse(theform.getSpecifiedQty().compareTo(new Double(0.0)) <= 0,
                       Errors.create().key(MessageIdList.NPWCREATELOT_QUANTITY_LARGER_THAN_ZERO).content("数量必须大于0!")
                             .build());

        Assert.isTrue(validateWareHouse(theform.getWarehouseRrn(), theform.getRawMaterialId()),
                      Errors.create().key(MessageIdList.NPWCREATELOT_MATERIAL_IS_NOT_EXISTS).content("物料不存在!").build());

        Assert.isTrue(validateUniqueUnit(request.getParameterValues("unitList")),
                      Errors.create().key(MessageIdList.UNIT_ID_MUST_UNIQUE).content("Unit ID must be " + "Unique!")
                            .build());

        LotInventoryDO lotInventory = null;
        Long rawMaterialRrn = getInstanceRrn(theform.getRawMaterialId(), LocalContext.getFacilityRrn(),
                                             ObjectList.ITEM_KEY);
        lotInventory = warehouseService
                .getLotInventory(theform.getRawMaterialId(), rawMaterialRrn, theform.getWarehouseRrn());

        Assert.notNull(lotInventory,
                       Errors.create().key(MessageIdList.MATERIAL_LOT_INVENTORY_MISSING).content("库房不存在!").build());

        Map _rawMaterial;
        int i = 0;
        long offset = 0;
        String[] units = request.getParameterValues("unitList");

        boolean check = true;

        for (Iterator it = rawMaterials.iterator(); it.hasNext(); ) {
            HashMap item = (HashMap) it.next();

            offset = offset + ((Double) item.get("specifiedQty")).longValue();

            if ((units != null) && (units[i] != null) && !units[i].equals("")) {
                item.put("unitList", units[i++]);
            }

            if (((Long) item.get("wareHouseRrn")).equals(lotInventory.getWarehouseRrn()) &&
                    ((String) item.get("lotNumber")).equals(lotInventory.getLotNumber())) {
                check = false;

                break;
            }
        }

        Assert.isFalse(theform.getSpecifiedQty().compareTo(new Double(
                               lotInventory.getReceiptQty().doubleValue() - lotInventory.getIssueQty().doubleValue() +
                                       lotInventory.getAdjustQty().doubleValue())) > 0,
                       Errors.create().content("Not enough on-hand Quantity!").build());

        if (check) {
            HashMap rawMaterial = new HashMap();
            rawMaterial.put("wareHouseId", lotInventory.getWarehouseId());
            rawMaterial.put("lotNumber", lotInventory.getLotNumber());
            rawMaterial.put("wareHouseRrn", lotInventory.getWarehouseRrn());
            String unitList = "";
            if (lot.getCustomerLotId() != null && lot.getCustomerWaferId() != null) {
                String[] unitListTemp = lot.getCustomerWaferId().split("\\$");
                for (int j = new Long(offset).intValue();
                     j < new Long(offset).intValue() + theform.getSpecifiedQty().intValue() &&
                             j < unitListTemp.length; j++) {
                    String unit = unitListTemp[j];
                    unitList += unit + "$";
                }
                if (StringUtils.equalsIgnoreCase(unitList, "$")) {
                    unitList = "";
                }
                rawMaterial.put("unitList", unitList);
            } else {
                rawMaterial.put("unitList", unitList);
            }
            rawMaterial.put("confirmFlag", "false");
            rawMaterial.put("itemRrn", StringUtils.toString(lotInventory.getItemRrn()));
            rawMaterial.put("specifiedQty", theform.getSpecifiedQty());
            String lotBox1 = theform.getLotBox1().toUpperCase().trim();
            String lotBox2 = theform.getLotBox2().toUpperCase().trim();
            String lotBox3 = theform.getLotBox3().toUpperCase().trim();
            String lotBoxQty1 = theform.getLotBoxQty1().toUpperCase().trim();
            String lotBoxQty2 = theform.getLotBoxQty2().toUpperCase().trim();
            String lotBoxQty3 = theform.getLotBoxQty3().toUpperCase().trim();
            rawMaterial.put("lotBox",
                            lotBox1 + "(" + lotBoxQty1 + ");" + lotBox2 + "(" + lotBoxQty2 + ");" + lotBox3 + "(" +
                                    lotBoxQty3 + ")");
            if (theform.getSpecifiedQty() != null) {
                rawMaterial.put("int_specifiedQty", theform.getSpecifiedQty().intValue() + "");
            }

            rawMaterial.put("offset", new Long(offset));
            rawMaterial.put("onHandQty", new Double(
                    lotInventory.getReceiptQty().doubleValue() - lotInventory.getIssueQty().doubleValue() +
                            lotInventory.getAdjustQty().doubleValue()));
            rawMaterials.add(rawMaterial);

            Assert.isFalse(validateQty(theform.getQty1(), rawMaterials) == MORE,
                           Errors.create().key(MessageIdList.LOT_MATERIALS_TOO_MUCH)
                                 .content("Too much raw " + "materials " + "selected!").build());

            request.setAttribute(SessionNames.COLLECTION_KEY, rawMaterials);
            request.setAttribute(SessionNames.LOT_KEY, lot);
            theform.setCacheRawMaterials(WebUtils.getCacheObj2String(rawMaterials));

        }

        theform.setRawMaterialId("");
        theform.setSpecifiedQty(null);

        if (order != null) {
            if (order.getOrder_Id() != null || order.getOrder_Id().length() != 0) {
                theform.setOrder_Id(order.getOrder_Id());
                theform.setOrder_Remain_Qty(order.getRemain_Qty());
                theform.setRuning_qty(order.getRuning_qty());
            }
        }

        return mapping.findForward("detail");
    }

    public ActionForward createPlanLot(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        // insert into lot_plan
        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        String[] units = request.getParameterValues("unitList");
        Object[] confirmFlags = request.getParameterValues("confirmFlag");
        List rawMaterials = (List) WebUtils.getCacheString2Obj(theform.getCacheRawMaterials());

        Lot lot = (Lot) WebUtils.getCacheString2Obj(theform.getCacheLot());
        Assert.isFalse(validateQty(theform.getQty1(), rawMaterials) == MORE,
                       Errors.create().key(MessageIdList.LOT_MATERIALS_TOO_MUCH)
                             .content("Too much raw materials " + "selected!").build());
        Assert.isFalse(validateQty(theform.getQty1(), rawMaterials) == LESS,
                       Errors.create().key(MessageIdList.LOT_MATERIALS_NOT_ENOUGH)
                             .content("Not enough raw materials " + "selected!").build());

        units = parseUnitListString(units, rawMaterials, lot.getLotId());

        lot.setCustomerWaferId(
                Arrays.asList(units).toString().replace('[', ' ').replace(']', ' ').trim().toUpperCase());
        Assert.isFalse(StringUtils.isNotBlank(lot.getCustomerWaferId()) &&
                               isValidUnitId(lot.getCustomerWaferId(), LocalContext.getFacilityRrn()),
                       Errors.create().key(MessageIdList.NPWCREATELOT_UNITID_ALREADY_EXISTS).content("晶圆号已经存在!")
                             .build());

        Assert.isTrue(validateUniqueUnit(units),
                      Errors.create().key(MessageIdList.UNIT_ID_MUST_UNIQUE).content("Unit ID must be Unique!")
                            .build());
        int i = 0;
        for (Iterator it = rawMaterials.iterator(); it.hasNext(); ) {
            HashMap item = (HashMap) it.next();
            Assert.isTrue((units[i] != null) && !"".equals(units[i]),
                          Errors.create().key(MessageIdList.UNIT_ID_MUST_SPECIFIED).content("Units must be specified!")
                                .build());
            // && ("true").equals(String.valueOf(confirmFlags[i]))
            item.put("unitList", units[i++].toUpperCase());
        }

        lot.setMaterialinfo(WebUtils.getCacheObj2String(rawMaterials));
        request.setAttribute(SessionNames.COLLECTION_KEY, rawMaterials);
        request.setAttribute(SessionNames.LOT_KEY, lot);
        theform.setCacheLot(WebUtils.getCacheObj2String(lot));
        long lotRrn = lotQueryService.getLotRrn(lot.getLotId());
        Lot lotTemp = lotService.getLotPlan(lot.getLotId());
        if ((lotTemp.getLotRrn() > 0 && lotTemp.getLotRrn() != theform.getLotRrn()) || lotRrn > 0) {
            request.setAttribute("confimLotIdFlag", "0");
            throw new SystemIllegalArgumentException(
                    Errors.create().key(MessageIdList.NPWCREATELOT_LOT_ALREADY_EXISTS).content("Lot existed!").build());
        }

        lotService.insertLotPlan(lot);
        if (lot != null) {
            String lotid = lot.getLotId();
            request.setAttribute("sucLotId", lotid);
        }
        request.setAttribute("savedFlag", "true");
        WebUtils.setSuccessMsg(request);
        return mapping.findForward("detail");
        // return mapping.findForward("setupfalse");

    }

    public ActionForward deleteMember(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        List rawMaterials = (List) WebUtils.getCacheString2Obj(theform.getCacheRawMaterials());
        Lot lot = (Lot) WebUtils.getCacheString2Obj(theform.getCacheLot());

        Map _rawMaterial;
        int i = 0;
        long offset = 0;
        String[] units = request.getParameterValues("unitList");

        for (Iterator it = rawMaterials.iterator(); it.hasNext(); ) {
            HashMap item = (HashMap) it.next();

            if ((units != null) && (units[i] != null) && !units[i].equals("")) {
                item.put("unitList", units[i++]);
            }

            item.put("offset", new Long(offset));
            offset = offset + ((Double) item.get("specifiedQty")).longValue();

            if (((Long) item.get("wareHouseRrn")).equals(new Long(request.getParameter("warehouseRrn"))) &&
                    ((String) item.get("lotNumber")).equals(request.getParameter("lotNumber"))) {
                it.remove();
            }
        }
        request.setAttribute(SessionNames.COLLECTION_KEY, rawMaterials);
        theform.setCacheRawMaterials(WebUtils.getCacheObj2String(rawMaterials));
        request.setAttribute(SessionNames.LOT_KEY, lot);
        request.setAttribute("facility", LocalContext.getFacilityRrn());

        return mapping.findForward("detail");
    }

    public ActionForward queryLotForCarrier(ActionMapping mapping, LotInfoFormNpw theform, HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        request.setAttribute("disableFlag", "true");
        theform.setScreenStatus("LOT_PLAN_START");
        String lotId = theform.getLotId().trim().toUpperCase();
        Lot lot = lotService.getLotPlan(lotId);
        Assert.notNull(lot.getProductRrn(),
                       Errors.create().key(MessageIdList.LOT_LOTRRN_NOT_FOUND).content("产品不存在!").build());
        Item product = new Item(lot.getProductId(), getNamedSpace(ObjectList.PRODUCT_KEY, facilityRrn),
                                ObjectList.PRODUCT_KEY);
        product = prpService.getItem(product);
        Assert.isFalse(StringUtils.equalsIgnoreCase("DUMMY", product.getObjectType()) != true ||
                               StringUtils.equalsIgnoreCase("M", lot.getLotType()) != true,
                       Errors.create().key(MessageIdList.NPWCREATELOT_TYPE_NOT_BE_DUMMY_CARRIER)
                             .content("非DUMMY批次不能使用DUMMY指定晶舟!").build());
        Collection reticleGroups = prpService.getProductReticleGroups(lot.getProductRrn().longValue());
        request.setAttribute(SessionNames.RETICLE_GROUP, reticleGroups);
        PropertyUtils.copyProperties(theform, lot);
        theform.setDueDateS(timestampToString(lot.getDueDate()));
        theform.setProcessStepIdVersion(((lot.getProcessStepIdVersion().split("\\|"))[1]).split(",")[0]);
        theform.setOrderNO(lot.getOuterOrderNO() != null ? "1" : "0");
        String c = theform.getCreateCategory();
        if ("PROD".equalsIgnoreCase(c)) {
            request.setAttribute("id_flag", "auto");
        } else if ("DUMMY".equalsIgnoreCase(c) || "MONITOR".equalsIgnoreCase(c)) {
            request.setAttribute("id_flag", "mdauto");
        } else if ("CVMONITOR".equalsIgnoreCase(c)) {
            request.setAttribute("id_flag", "cvmauto");
        }

        String lotType = theform.getLotType();
        if ("PP".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Production Lot");

        } else if ("PC".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Customer Pilot Lot");

        } else if ("PB".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Customer Pilot Lot");

        } else if ("PA".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Customer Pilot Lot");

        } else if ("PE".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Probe Lot");

        } else if ("EE".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Engineer Lot");

        } else if ("EL".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Sort Loop Lot");

        } else if ("TT".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("TD Developing Lot");

        } else if ("TL".equalsIgnoreCase(lotType)) {
            theform.setCreateCategoryDetail("Sort Loop Lot");

        }

        if (lot.getCustomerLotId() != null) {
            request.setAttribute("id_flag", "define");
        }
        request.setAttribute("lineID", theform.getLotId().substring(0, 1));
        theform.setCacheLot(WebUtils.getCacheObj2String(lot));
        request.setAttribute(SessionNames.LOT_KEY, lot);

        String createCategoryDesc = sysService
                .referenceDetailExchange("$LOT_CREATE_CATEGORY", theform.getCreateCategory(), "", "data_1_value");
        theform.setLotType(createCategoryDesc);

        request.setAttribute("productRrn", lot.getProductRrn());
        request.setAttribute("isshow", "FALSE");
        return mapping.findForward(LOT_PLAN_START);

    }

    public ActionForward nextPlanLotForCarrier(ActionMapping mapping, LotInfoFormNpw theform,
                                               HttpServletRequest request,
                                               HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String lotId = theform.getLotId().trim().toUpperCase();
        String carrierId = theform.getCarrierId();
        Lot lot = lotService.getLotPlan(lotId);
        PropertyUtils.copyProperties(theform, lot);

        if (!StringUtils.equalsIgnoreCase(theform.getScreenStatus(), "CREATE_PLAN_LOT")) {
            long carrierRrn = carrierService.getAvailableCarrierRrnById(facilityRrn, carrierId);
            Carrier carrier = new Carrier();
            carrier.setInstanceRrn(carrierRrn);
            carrier = carrierService.getCarrier(carrierRrn);
            Assert.isFalse(carrier.getAvailableSlotCount() < lot.getQty1(),
                           Errors.create().key(MessageIdList.NPWCREATELOT_AVAILABLESLOT_IS_NOT_ENOUGH)
                                 .content("可用片槽不够!").build());
            lot.setCarrierRrn(carrierRrn);
            lot.setCarrierId(carrierId);
            request.setAttribute("carrierId", carrierId);
            Assert.isFalse(lot.getMaterialinfo().isEmpty(),
                           Errors.create().key(MessageIdList.NPWCREATELOT_MATERIAL_IS_NOT_EXISTS).content("物料不存在!")
                                 .build());
        }

        request.setAttribute("productRrn", lot.getProductRrn());
        request.setAttribute("lotType", lot.getLotType());

        String waferType = "";
        if (lot.getLotType() != null && lot.getCreateCategory() != null) {

            if (lot.getLotType().equalsIgnoreCase("C") && "DUMMY".equalsIgnoreCase(lot.getCreateCategory())) {
                waferType = "CD";
            } else if (lot.getLotType().equalsIgnoreCase("E") && "DUMMY".equalsIgnoreCase(lot.getCreateCategory())) {
                waferType = "ED";
            } else if (lot.getLotType().equalsIgnoreCase("C")) {
                waferType = "CP";
            } else if (lot.getLotType().equalsIgnoreCase("E")) {
                waferType = "EP";
            }

        }

        String stepNumber = request.getParameter("stepNumber");
        Map tempInfo = getStepsInfoByLot(lot, lot.getProcessRrn(), lot.getProcessVersion(), stepNumber);

        Long operationRrn = (Long) tempInfo.get("operationRrn");

        Assert.isTrue(checkOperationInFacility(operationRrn, facilityRrn),
                      Errors.create().key(MessageIdList.NPWCREATELOT_OPERATION_NOTBE_CURRENT_FACILITY)
                            .content("批次第一步步骤不在当前车间!").build());
        Integer operationVer = (Integer) tempInfo.get("operationVer");
        tempInfo = prpService.getOperationInfo(operationRrn, operationVer);

        String trackUnitFlag = (String) tempInfo.get("trackUnitFlag");
        String keepUnitHistoryFlag = (String) tempInfo.get("keepUnitHistoryFlag");

        theform.setTrackUnitFlag(trackUnitFlag);
        theform.setKeepUnitHistoryFlag(keepUnitHistoryFlag);

        if ((lot.getScheduleDueDate() != null) && (lot.getDueDate() != null) &&
                lot.getScheduleDueDate().after(lot.getDueDate())) {
            lot.setLastScheduleFlag(TRUE);
        }

        theform.setPages(new Integer(1));

        request.setAttribute("waferType", waferType);
        theform.setCacheLot(WebUtils.getCacheObj2String(lot));
        theform.setCacheLot(WebUtils.getCacheObj2String(lot));
        request.setAttribute(SessionNames.LOT_KEY, lot);
        request.setAttribute(SessionNames.COLLECTION_KEY, new ArrayList());
        String[] attributeRrns = request.getParameterValues("attributeRrn");
        String[] attributeValues = request.getParameterValues("attributeValue");
        request.setAttribute("attributeRrns", attributeRrns);
        request.setAttribute("attributeValues", attributeValues);
        request.setAttribute("sequence", "1");

        boolean flag = true;
        if (lot.getLotId().indexOf(",") > 0) {
            flag = false;
            request.setAttribute("id_flag", "define");

        }
        if (flag == false) {
            request.setAttribute("confimLotIdFlag", "1");
            request.setAttribute("confimLotId", lot.getLotId());
            return (mapping.findForward("confimLotId"));
        }
        request.setAttribute("unitList", theform.getCustomerWaferId());

        if (lot.getMaterialinfo() != null) {
            theform.setCacheRawMaterials(lot.getMaterialinfo());
            request.setAttribute(SessionNames.COLLECTION_KEY, WebUtils.getCacheString2Obj(lot.getMaterialinfo()));
        }

        return mapping.findForward("detail");

    }

    public ActionForward createLotForCarrier(ActionMapping mapping, LotInfoFormNpw theform, HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        long _lotRrn = 0;
        Lot lot = (Lot) WebUtils.getCacheString2Obj(theform.getCacheLot());
        Assert.isFalse(StringUtils.isNotBlank(lot.getCustomerWaferId()) &&
                               isValidUnitId(lot.getCustomerWaferId(), facilityRrn),
                       Errors.create().key(MessageIdList.NPWCREATELOT_UNITID_ALREADY_EXISTS).content("晶圆号已经存在!")
                             .build());
        _lotRrn = lotQueryService.getLotRrn(lot.getLotId());

        Assert.isFalse(_lotRrn > 0,
                       Errors.create().key(MessageIdList.NPWCREATELOT_LOT_ALREADY_EXISTS).content("Lot existed!")
                             .build());

        Collection rawMaterials = (Collection) WebUtils.getCacheString2Obj(lot.getMaterialinfo());
        HashMap transInfo = new HashMap();
        transInfo.put("startFlag", lot.getStartedFlag());
        lot.setLotOwner(theform.getLotOwner());
        lot.setSplitMergeFlag(LocationNames.initLotFlagName(lot.getProcessId()));
        transInfo.put("lot", lot);
        transInfo.put("lotid", lot.getLotId());
        transInfo.put("qty", lot.getQty1() + "");
        transInfo.put("fromoperation", "3333");
        transInfo.put("tooperation", lot.getOperationId());
        transInfo.put("productRrn", lot.getProductRrn());
        //
        String temp = lot.getProcessStepVersion();
        String route = "";
        if (temp != null) {
            int i = 0;
            int j = 0;
            i = temp.indexOf("|");

            // find first '|'
            if (i != -1) {
                j = temp.indexOf("|", i + 1);

                // find se '|'
                // string is aaa|bbb|cccc
                if (j > 0) {
                    route = temp.substring(i + 1, j);
                } else if (i > 0) { // aaa|bbb
                    route = temp.substring(0, i);
                }
            }
        }
        route = route.replace(',', '.');

        transInfo.put("toroute", route);
        transInfo.put("transPerformedby", LocalContext.getUserId());
        transInfo.put("keepUnitHistoryFlag", theform.getKeepUnitHistoryFlag());
        transInfo.put("trackUnitFlag", theform.getTrackUnitFlag());
        transInfo.put("unitList", request.getParameterValues("unitList"));

        Object[] testItems = request.getParameterValues("unitList");
        transInfo.put("positionList", getPositionList(lot.getQty1()));
        transInfo.put("rawMaterials", rawMaterials);
        for (Iterator it = rawMaterials.iterator(); it.hasNext(); ) {
            HashMap testItem = (HashMap) it.next();
        }

        transInfo.put("planLotRrn", lot.getCreatedPlanLotRrn());
        transInfo.put("lotComments", theform.getLotComments());

        String message = createLotWorkStream(transInfo, facilityRrn, LocalContext.getUserId());

        if (message != null) {
            //TODO这个报错信息是关于调用其他系统的报错
            /*request.setAttribute(ErrorDef.MYCIM_ERR_KEY, new WSIDefException(message));

            return mapping.findForward("error");*/
        }

        Map resultsInfo = createLot(transInfo);
        // 投片后 数据库中创建了一个母批
        createLotSapphireInfo(Long.valueOf(transInfo.get("productRrn").toString()),
                              Long.valueOf(resultsInfo.get("lotRrn").toString()));
        request.setAttribute("lotRrn", resultsInfo.get("lotRrn"));
        if (request.getAttribute("attributeRrns") != null) {
            transInfo = new HashMap();
            transInfo.put("attributeRrns", request.getAttribute("attributeRrns"));
            transInfo.put("attributeValues", request.getAttribute("attributeValues"));
            transInfo.put("transRrn", resultsInfo.get("transRrn"));
            transInfo.put("instanceRrn", resultsInfo.get("lotRrn"));
            maintainTransAttributes(transInfo);
        }

        saveLotSeqAttribute(((Long) resultsInfo.get("lotRrn")).longValue(), facilityRrn, lot.getProductRrn(),
                            I18nUtils.getCurrentLanguage().toString());
        //TODO:   old order programer
            /*Order order = new Order();
            order = (Order) request.getAttribute("ordinfo");
            if (order != null && order.getOrder_Id() != null && order.getOrder_Id().trim().length() > 0) {

                HashMap lotordinfo = new HashMap();
                long lotrrn = lotQueryService.getLotRrn(lot.getLotId());
                lotordinfo.put("lot_rrn", String.valueOf(lotrrn));
                lotordinfo.put("lot_id", lot.getLotId());
                int lotqty = lot.getQty1().intValue();
                String lotqty2 = String.valueOf(lotqty);
                lotordinfo.put("lot_qty", lotqty2);
                lotordinfo.put("order_id", order.getOrder_Id());
                lotordinfo.put("order_id_market", order.getMarket_order_Id().toString().trim());
                lotordinfo.put("order_rrn", order.getOrder_RRN());
                lotordinfo.put("order_id_type", order.getOrder_id_type());
                HashMap lottrans = new HashMap();
                Lot lot2 = new Lot();
                lot2 = lotQueryService.getLot(lot.getLotId().toString().trim());
                lottrans = (HashMap) wipQueryService.getLotTransInfo(String.valueOf(lot2.getLotRrn()));
                lotordinfo.put("lot_trnasname", lottrans.get("trans_rrn"));
                lotordinfo.put("trans_sequence", lottrans.get("TRANS_SEQUENCE"));
                String ordertype = lotordinfo.get("order_id_type").toString().trim();
                this.getInvManager().RegLotOrdInfo(lotordinfo, ordertype);
                String dummySubOrderId = session.getAttribute("dummySubOrderId").toString();
                if (ordertype.equalsIgnoreCase(ObjectList.ORDER_SUB_DUMMY)) {
                    this.getInvManager().UpdateSubDummyOrderRemainQty(dummySubOrderId,
                                                                      lotordinfo.get("order_id_market")
                                                                      .toString(),
                                                                      lotordinfo.get("lot_qty").toString(),
                                                                      ObjectList.ORDER_SUB_DUMMY);
                }
            }*/
        theform.setByPlanLotFlag("product");
        theform.setCreatedPlanLotId("");

        request.setAttribute("isDummyLot", "1");
        return mapping.findForward("npwlotcurrentinfo");

    }

    public ActionForward npwLotCurrentInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        String user = LocalContext.getUserId();
        Long facilityRrn = LocalContext.getFacilityRrn();

        LotInfoFormNpw theform = (LotInfoFormNpw) form;
        String lotId = request.getParameter("lotId");
        Lot lot = lotQueryService.getLot(lotId);
        org.apache.commons.beanutils.PropertyUtils.copyProperties(theform, lot);

        Operation oper = prpService.getOperation(lot.getOperationRrn().longValue());
        String nSpace = getNamedSpace("OPERATION", facilityRrn);
        if (oper.getNamedSpace().equalsIgnoreCase(nSpace)) {
            theform.setStartedFlag("true");
        } else {
            theform.setStartedFlag("false");
        }

        String recipePhysicalId = recipeService.buildRecipePhysicalId(lot.getRecipeId(), BeanUtils.copyBeanToMap(lot));
        theform.setRecipePhysicalId(recipePhysicalId);

        Timestamp dueDate = lot.getDueDate();

        request.setAttribute("priority", lot.getPriority());

        String due_date = timestampToString(dueDate);

        request.setAttribute("due_date", due_date);


        if (StringUtils.isNotBlank((String) request.getAttribute("isDummyLot"))) {
            Integer count = prpService.getProductSumLoopCount(lot.getProductRrn());
            ProcessLoopInfo loopInfo = new ProcessLoopInfo();
            loopInfo.setLoopCount(count + "");
            loopInfo.setProcessRrn(lot.getProcessRrn());
            Map<String, Object> loopCountInfo = new HashMap<String, Object>();
            loopCountInfo.put("lotRrn", lot.getLotRrn());
            loopCountInfo.put("count", count);
            loopCountInfo.put("loopInfo", loopInfo);
            loopCountInfo.put("transType", TransactionNames.NPWUNITSINIT);
            loopCountInfo.put("reasonCode", "DUMMY-CREATELOT");
            loopCountInfo.put("user", user);
            loopCountInfo.put("reason", "DUMMY投批-units usage 初始化");
            loopCountInfo.put("comments", "DUMMY投批");
            loopCountInfo.put("userRrn", LocalContext.getUserRrn());
            dmmLotService.initDMMUnitCounts(loopCountInfo);
        }
        return mapping.findForward("success");
    }

    public String timestampToString(Date date) {
        String dateString = "";

        if (date != null) {
            SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DATE_FORMAT4DAY);

            // formatter= new SimpleDateFormat("dd/MM/yyyy");
            dateString = formatter.format(date);
        }

        return dateString;
    }

    /***
     * 创建批次
     *
     * @param transInfo
     * @return
     * @throws Exception
     */
    private Map createLot(Map transInfo) throws Exception {
        Map resultsInfo = lotService.createLot(transInfo);
        Lot lot = lotQueryService.getLot(MapUtils.getLongValue(resultsInfo, "lotRrn"));
        handlePreFutureHoldByPilot(lot, WebUtils.getSystemUser(), lot.getFacilityRrn());
        return resultsInfo;
    }

    /***
     * 如果产品属于Bonding,则创建Bonding批次
     *
     * @param productRrn 产品rrn
     * @throws Exception
     */
    private void createLotSapphireInfo(Long productRrn, Long lotRrn) throws Exception {

        NamedObject object = baseService.isExisted(productRrn);
        // 如果是Bonding类型
        if (StringUtils.equals(object.getObjectType(), ObjectList.SAPPHIRE)) {
            SapphireProduct sapProduct = prpService.getSapphireProduct(productRrn);// 通过从产品RRN获得Bonding产品
            LotSapphreInfo lotSapphreInfo = new LotSapphreInfo();
            lotSapphreInfo.setLotRrn(lotRrn);
            lotSapphreInfo.setAttributeData1(sapProduct.getAttributeData1());
            lotSapphreInfo.setAttributeData2(sapProduct.getAttributeData2());
            lotSapphreInfo.setAttributeData3(sapProduct.getAttributeData3());
            lotSapphreInfo.setAttributeData4(sapProduct.getAttributeData4());
            lotSapphreInfo.setAttributeData5(sapProduct.getAttributeData5());
            lotSapphreInfo.setExpiredDate(sapProduct.getExpiredDate());
            lotSapphreInfo.setTargetCount(sapProduct.getTargetCount());
            lotSapphreInfo.setUnitDate(sapProduct.getUnitDate());
            lotSapphreInfo.setWarningCount(sapProduct.getWarningCount());
            // Bonding使用次数,初始为零
            lotSapphreInfo.setActualCount(Long.valueOf("0"));
            // 插入Bonding批次信息
            dmmLotService.insertLotSapphreInfo(lotSapphreInfo);

        }
    }

    private void saveLotSeqAttribute(long lotRrn, Long facilityRrn, Long productRrn, String language) throws Exception {
        List<Map> attributes = sysService
                .getAllAttributes(lotRrn, getNamedSpace("LOT", facilityRrn), "LOT", Languages.valueOf(language));

        List<Map> attributesResults = new ArrayList();

        HashMap attribute = null;

        if (!attributes.isEmpty()) {
            for (Iterator it = attributes.iterator(); it.hasNext(); ) {
                attribute = (HashMap) it.next();
                if (this.getInstanceRrn("FLD_PRODUCT_SERIAL_NUMBER", getNamedSpace(ObjectList.FIELD_KEY, facilityRrn),
                                        ObjectList.FIELD_KEY) ==
                        Long.parseLong(StringUtils.toString(attribute.get("FIELD_RRN")))) {
                    attribute.put("attributeValue", StringUtils.toString(getMaxSeqOfLotByProduct(productRrn) + 1));
                    attribute.put("instanceRrn", StringUtils.toString(lotRrn));
                    attribute.put("instanceVersion", "1");

                    attributesResults.add(attribute);
                }

                sysService.maintainAttribute(attributesResults);
            }
        } else {
            Map attributeValue = new HashMap();
            attributeValue.put("attributeValue", StringUtils.toString(getMaxSeqOfLotByProduct(productRrn) + 1));
            attributeValue.put("instanceRrn", StringUtils.toString(lotRrn));
            attributeValue.put("instanceVersion", "1");
            attributeValue.put("fieldRrn", Long.toString(
                    this.getInstanceRrn("FLD_PRODUCT_SERIAL_NUMBER", getNamedSpace(ObjectList.FIELD_KEY, facilityRrn),
                                        ObjectList.FIELD_KEY)));
            attributesResults.add(attributeValue);
            sysService.maintainAttribute(attributesResults);
        }
    }

    private long getMaxSeqOfLotByProduct(Long productRrn) throws Exception {
        return dmmLotService.getMaxSeqOfLotByProduct(productRrn);

    }

    private void maintainTransAttributes(Map transInfo) throws Exception {
        dmmService.insertTransAttributeValues(transInfo);
    }

    // end of createLot
    private String createLotWorkStream(Map transInfo, Long facility, String user) throws Exception {

        String message = connectMesSystem(transInfo, facility.longValue(), user);
        transInfo.put("wsname", "createLot");
        if (message == null) {
            transInfo.put("wsname", "nonStdMoveOut");
            message = connectMesSystem(transInfo, facility.longValue(), user);
        }
        return message;
    }

    private Object[] getPositionList(Double lotQty) {
        Object[] positionList = null;
        if (lotQty != null) {
            positionList = new Object[lotQty.intValue()];

            for (int i = 0; i < lotQty.intValue(); i++) {
                positionList[i] = new Long(i + 1);
            }
        }

        return positionList;
    }

    private int validateQty(Double lotQty, Collection rawMaterials) {
        double qty = 0.0;
        Double itemQty;

        for (Iterator it = rawMaterials.iterator(); it.hasNext(); ) {
            HashMap rawItem = (HashMap) it.next();
            itemQty = (Double) rawItem.get("specifiedQty");

            if (itemQty == null) {
                itemQty = new Double(0.0);
            }

            qty += itemQty.doubleValue();
        }
        if (lotQty.compareTo(new Double(qty)) > 0) {
            return LESS;
        } else if (lotQty.compareTo(new Double(qty)) < 0) {
            return MORE;
        } else {
            return EQUAL;
        }
    }

    private boolean validateWareHouse(Long warehouseRrn, String rawMaterialId) throws Exception {
        boolean flag = true;
        return true;
    }

    private boolean validateUniqueUnit(Object[] unitList) {
        boolean flag = true;
        Collection keys = new ArrayList();
        Collection _keys = null;
        String _tmpString = null;

        if (unitList != null) {
            for (int i = 0; i < unitList.length; i++) {
                _tmpString = (String) unitList[i];
                _keys = myParseString(_tmpString, "1");
                keys.addAll(_keys);

                Collection tmpKeys = new ArrayList();
                tmpKeys.addAll(keys);

                if (!validateKeys(tmpKeys)) {
                    flag = false;

                    break;
                }
            }
        }

        return flag;
    }

    private boolean validateKeys(Collection keys) {
        boolean flag = true;

        for (Iterator it = keys.iterator(); it.hasNext(); ) {
            String item = (String) it.next();
            it.remove();

            if (keys.contains(item)) {
                flag = false;

                break;
            }
        }

        return flag;
    }

    /**
     * lot--customerwaferId字符串 格式 aaaa|0$aaaa|0$aaaa|0$aaaa|0$ 转换为 [aaaa,aaaa,aaaa]
     */
    private Collection myParseString(String tempString, String index) {
        int pos0 = -1;
        int pos1 = 0;
        int pos2 = 0;
        String key;
        String _tempString;
        Collection _keys = new ArrayList();
        if (tempString != null) {
            while (tempString.indexOf("$") > 0) {
                pos1 = tempString.indexOf("$");
                _tempString = tempString.substring(pos0 + 1, pos1);

                if (_tempString.indexOf("|") > 0) {
                    pos2 = _tempString.indexOf("|");

                    if (index.equals("1")) {
                        key = StringUtils.trimToUpperCase(_tempString.substring(pos0 + 1, pos2));
                    } else {
                        key = StringUtils.trimToUpperCase(_tempString.substring(pos2 + 1, pos1));
                    }

                    _keys.add(key);
                    tempString = tempString.substring(pos1 + 1, tempString.length());
                }
            }
        }

        return _keys;
    }

    // --------------------------------------------------------------------------------------

    private String[] parseUnitListString(String[] units, Collection rawMaterials, String lotId) {

        String unitListString = "";
        for (int i = 0; i < units.length; i++) {
            unitListString += units[i];
        }

        List raw = (List) rawMaterials;
        int num = 0;
        for (int i = 0; i < units.length; i++) {
            Map map = (Map) raw.get(i);
            int qty = MapUtils.getIntValue(map, "int_specifiedQty");
            if (StringUtils.isBlank(units[i]) || StringUtils.equals("$", units[i])) {
                String unitList = "";
                for (int j = 0; j < qty; j++) {
                    String unitId = "";
                    while (true) {
                        unitId = lotId + "_" + (++num);
                        if (!StringUtils.contains(unitListString, unitId)) {
                            break;
                        }
                    }
                    unitList = unitList + unitId + "|" + "0" + "$";
                }
                units[i] = unitList;
            }
        }
        return units;
    }

}