LotTransHistoryAction.java

package com.mycim.webapp.actions.lot.lottranshistory;

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.time.DateUtils;
import com.mycim.framework.utils.msg.JsonUtils;
import com.mycim.utils.WipUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.wip.Lot;
import com.mycim.webapp.Constants;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.util.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 批次事务历史
 *
 * @author weike.li
 * @version 6.0.0
 * @date 2019/9/9
 **/
public class LotTransHistoryAction extends WipSetupAction {

    private static final String RESET_PAGE_FLAG = "resetPageFlag";

    private static final String FROM_URL_FLAG = "fromUrlFlag";

    private static final String NUM_ONE = "1";

    private static final String THIS_PAGE = "thisPage";

    private static final String PAGE_SIZE = "pageSize";

    private static final String[] ADJUST_LOT_FIELDS = {"createCategory", "lotType", "splitMergeFlag", "lotOwner",
            "dueDate", "customerId", "shippingCode", "outerOrderNO", "outOrderType", "lotComments"};

    private static final String PAGE = "PAGE";



    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {
        Map upMap = new HashMap();
        boolean navFlag = request.getParameter("nav") != null;
        String lotTransId = request.getParameter("lotTransId");
        Map lotInfo = new HashMap();

        upMap.put("lotRrn", navFlag ? 0L : (Long) lotInfo.get("lotRrn"));
        upMap.put("lotId", navFlag ? "" : (String) lotInfo.get("lotId"));

        if (lotTransId != null && !"".equals(lotTransId)) {
            upMap.put("lotTransId", lotTransId);
        }

        request.setAttribute("map", upMap);
        request.setAttribute("lotInfo", lotInfo);
        request.setAttribute("lotId", lotInfo.get("lotId"));
        request.setAttribute("carrierId", lotInfo.get("carrierId"));
        Map map = (Map) request.getAttribute("map");
        if (StringUtils.equals(WebUtils.getParameter(FROM_URL_FLAG, request), NUM_ONE)) {
            request.setAttribute("fromUrlFlag", "1");
        }

        int fixSize = 20;
        int current = 1;

        List list = new ArrayList();

        request.setAttribute("list", list);
        request.setAttribute("current", current);
        request.setAttribute("lastPageSize",
                             (lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue()) % fixSize);
        request.setAttribute("pageSize", fixSize);
        request.setAttribute("maxPage",
                             (lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() % fixSize == 0) ?
                                     lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() / fixSize :
                                     lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() / fixSize + 1);
        return mapping.findForward(Constants.QUERY_KEY);
    }

    public ActionForward query(ActionMapping mapping, HttpServletRequest request) {
        if (StringUtils.equals(WebUtils.getParameter(FROM_URL_FLAG, request), NUM_ONE)) {
            request.setAttribute("fromUrlFlag", "1");
        }
        Map map = getMapForGetHistList(request);
        map.put("showAll", "1");
        boolean flag = MapUtils.getBoolean(map, "flag");
        int fixSize = 20;

        int pageSize = fixSize;
        int current = 1;

        if (request.getParameter(THIS_PAGE) != null) {
            current = new Integer((String) request.getParameter("thisPage")).intValue();
        }
        // 切换tab的时候,重置当前页为第一页
        if (StringUtils.isNotBlank(WebUtils.getParameter(RESET_PAGE_FLAG, request))) {
            current = 1;
        }

        if (NUM_ONE.equals(request.getParameter("currentForCompare"))) {
            current = 1;
        }

        /*if (request.getParameter(PAGE_SIZE) != null && (request.getParameter(PAGE_SIZE).length()) != 0) {
            pageSize = new Integer((String) request.getParameter("pageSize")).intValue();
        }*/

        List list1 = getHistList(map, flag, pageSize, current);
        request.setAttribute("list", list1);
        request.setAttribute("current", current);
        request.setAttribute("pageSize", fixSize);
        long lotRrn = MapUtils.getLong(map, "lotRrn");
        int rowCount = lotQueryService.qryLotTransHistoryCount(lotRrn);
        int maxPage = (rowCount + pageSize - 1) / pageSize;
        int lastPageSize = rowCount % pageSize;
        request.setAttribute("lastPageSize", lastPageSize);
        request.setAttribute("maxPage", maxPage);
        /*request.setAttribute("lastPageSize", (lotQueryService.getCount("LOT_TRANS_HISTORY", map)
        .longValue())
                                             % fixSize);
        request.setAttribute("pageSize", fixSize);
        request.setAttribute("maxPage", (lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue()
                                         % fixSize == 0) ? lotQueryService.getCount("LOT_TRANS_HISTORY",
                                                                                    map).longValue()
                                                           / fixSize : lotQueryService.getCount(
                "LOT_TRANS_HISTORY", map).longValue() / fixSize + 1);*/
        return mapping.findForward(Constants.QUERY_KEY);
    }

    public ActionForward reset(ActionMapping mapping, HttpServletRequest request) {

        Map upMap = new HashMap();
        Map lotInfo = new HashMap();

        upMap.put("lotRrn", 0L);
        upMap.put("lotId", "");

        request.setAttribute("map", upMap);
        request.setAttribute("lotInfo", lotInfo);
        request.setAttribute("lotId", lotInfo.get("lotId"));
        request.setAttribute("carrierId", lotInfo.get("carrierId"));
        Map map = (Map) request.getAttribute("map");

        int fixSize = 10;
        int current = 1;

        List list = new ArrayList();
        request.setAttribute("list", list);
        request.setAttribute("current", current);
        request.setAttribute("lastPageSize",
                             (lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue()) % fixSize);
        request.setAttribute("pageSize", fixSize);
        request.setAttribute("maxPage",
                             (lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() % fixSize == 0) ?
                                     lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() / fixSize :
                                     lotQueryService.getCount("LOT_TRANS_HISTORY", map).longValue() / fixSize + 1);
        return mapping.findForward(Constants.QUERY_KEY);
    }

    public ActionForward export(ActionMapping mapping, ActionForm theform, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Map<String, Object> titles = WebUtils.getExportTitles(request);
        titles.put("title", "Lot Transaction History");
        Map map = getMapForGetHistList(request);
        String qty1 = MapUtils.getString(map, "qty1");
        String productId = MapUtils.getString(map, "productId");
        String lotId = MapUtils.getString(map, "lotId");
        titles.put("lot_value", "Lot Id:" + lotId);
        titles.put("qty_value", "Qty:" + qty1);
        titles.put("product_value", "Product Id:" + productId);
        boolean flag = MapUtils.getBoolean(map, "flag");

        String exportType = WebUtils.getExportType(request);
        Integer thisPage = WebUtils.getParameterInt("thisPage", request);
        Integer pageSize = WebUtils.getParameterInt("pageSize", request);
        Page page;
        if (StringUtils.equalsIgnoreCase(exportType, PAGE)) {
            page = getPage(false, pageSize, thisPage, 15, 1);
        } else {
            page = getPage(true, pageSize, thisPage, 15, 1);
            map.put("showAll", 1);
        }

        // 导出
        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        String fileName = "LotTransHist" + exportDateTime + ".xlsx";
        Integer pageSize2 = NumberUtils.convertNumberToTargetClass(page.getPageSize(), Integer.class);
        Integer thisPage2 = NumberUtils.convertNumberToTargetClass(page.getPageNo(), Integer.class);
        List<Map> data = getHistList(map, flag, pageSize2, thisPage2);

        WebUtils.exportExcel(fileName, titles, data, TemplateLocation.LOT_TRANS_HIST, response);

        return WebUtils.NULLActionForward;
    }

    private List getHistList(Map map, boolean flag, int pageSize, int current) {
        List list = flag ? new ArrayList() : lotQueryService.qryLotTransHistory(map, current, pageSize);
        if (CollectionUtils.isNotEmpty(list)) {
            map.put("showAll", "1");

            //List<Map> detailList = lotQueryService.qryAllLotAdjustDetail(MapUtils.getLong(map, "lotRrn"));
            Lot lot = lotQueryService.getLot(MapUtils.getString(map, "lotId"), LocalContext.getFacilityRrn());

            for (Object obj : list) {
                Map<String, Object> transHistorMap = (Map<String, Object>) obj;
                String targetUnitId = MapUtils.getString(transHistorMap, "targetUnitId");
                if (StringUtils.isNotBlank(targetUnitId)) {
                    targetUnitId = StringUtils.substring(targetUnitId, StringUtils.indexOf(targetUnitId, "("));
                    transHistorMap.put("splitLotIdAndUnitId",
                                       MapUtils.getString(transHistorMap, "targetLotId") + targetUnitId);
                } else {
                    transHistorMap.put("splitLotIdAndUnitId", "");
                }

                long transRrn = MapUtils.getLongValue(transHistorMap, "transRrn");

               /* Map<String, Object> adjust = null;
                for (Map<String, Object> detail : detailList) {
                    if (transRrn < MapUtils.getLongValue(detail, "transRrn")) {
                        adjust = detail;
                    } else {
                        break;
                    }
                }*/

                Map<String, Object> adjust = lotQueryService.qryAdjustTransHistory(transRrn, lot.getLotRrn());
                if (MapUtils.isNotEmpty(adjust)) {
                    adjust = JsonUtils.toMap(MapUtils.getString(adjust, "adjustAfter"));
                } else {
                    adjust = new HashMap<>();
                    BeanUtils.copyBeanToMap(adjust, lot);
                }
                for (String key : ADJUST_LOT_FIELDS) {
                    transHistorMap.put(key, MapUtils.getString(adjust, key));
                }
                String hotflag = MapUtils.getString(transHistorMap, "hotFlag");
                String priority = MapUtils.getString(transHistorMap, "priority");
                //如果为空  就取上一次adjust之后的
                if (StringUtils.isBlank(hotflag) || StringUtils.isBlank(priority)) {
                    Map priorityMap = lotQueryService.queryPriorityBeforeLastAdjust(lot.getLotRrn(), transRrn);
                    if (priorityMap != null) {
                        transHistorMap.put("priority2", MapUtils.getString(priorityMap, "hotFlag") + "-" +
                                MapUtils.getString(priorityMap, "priority"));
                    }
                } else {
                    transHistorMap.put("priority2", hotflag + "-" + priority);
                }
                String transCommentsId = MapUtils.getString(transHistorMap, "trans_id");
                String transComments = MapUtils.getString(transHistorMap, "transComments");
                transHistorMap
                        .put("transCommets", StringUtils.equals("ADDCOMMENT", transCommentsId) ? "" : transComments);
                transHistorMap
                        .put("lotCommets", StringUtils.equals("ADDCOMMENT", transCommentsId) ? transComments : "");

                String transId = MapUtils.getString(transHistorMap, "trans_id");

                if(StringUtils.equals(TransactionNames.DATA_COLLECTION_KEY, transId)) {
                    String url = lotQueryService.getDataCollectionUrlForDataCollectionTrans(transRrn, MapUtils.getInteger(transHistorMap, "transSequence"));
                    if(StringUtils.isNotBlank(url)) {
                        transHistorMap.put("transComments", url);
                    }
                }

                transHistorMap.put("autoMonitorChildLotId",
                                   StringUtils.equals(TransactionNames.MONITOR_JOB_CREATE_KEY, transId) ? MapUtils
                                           .getString(transHistorMap, "transCommets") : "");

                String transModule=MapUtils.getString(transHistorMap,"transModule");
                if (StringUtils.isNotBlank(transModule)&& WipUtils.AUTO.equals(transModule)){
                    String transPerformedBy = MapUtils.getString(transHistorMap, "trans_performed_by")+"("+transModule+")";
                    transHistorMap.put("trans_performed_by",transPerformedBy);
                }
            }
        }

        List list1 = new ArrayList();
        for (Object obj : list) {
            Map tempMap = (Map) obj;
            Map<String, String> m = MapUtils.convertToMapOfString(tempMap);
            list1.add(m);
        }
        return list1;
    }

    private Map getMapForGetHistList(HttpServletRequest request) {
        Map upMap = new HashMap();
        Map lotInfo = null;
        boolean navFlag = request.getParameter("nav") != null;
        String lotTransId = request.getParameter("lotTransId");
        Long facility = LocalContext.getFacilityRrn();

        String lotId = WebUtils.getParameterBoolean("byCarrierId", request) ? null : WebUtils
                .getParameterUpperCase("lotId", request).trim();
        String carrierId = WebUtils.getParameterBoolean("doLotId", request) ? null : WebUtils
                .getParameterUpperCase("carrierIdQuery", request).trim();

        if (navFlag == true) {
            lotInfo = new HashMap();
            long carrierRrn = 0;
            if (StringUtils.isNotEmptyTrim(carrierId)) {
                carrierRrn = isValidEntity(facility, carrierId);
                Assert.isFalse(carrierRrn <= 0,
                               Errors.create().key(MessageIdList.CASSETTE_MISSING_ID).content("No such Cassette ID")
                                     .build());
                lotInfo = lotQueryService.getLotInfoasMap(facility, lotId, carrierRrn);
                upMap.put("lotRrn", (Long) lotInfo.get("lotRrn"));
                upMap.put("lotId", (String) lotInfo.get("lotId"));
                upMap.put("qty1", lotInfo.get("qty1"));
                upMap.put("productId", lotInfo.get("productId"));
            }
        } else {

            long carrierRrn = 0;
            if (StringUtils.isNotEmptyTrim(carrierId)) {
                carrierRrn = isValidEntity(facility, carrierId);
                Assert.isFalse(carrierRrn <= 0,
                               Errors.create().key(MessageIdList.CASSETTE_MISSING_ID).content("No such Cassette ID")
                                     .build());
            }

            Assert.isFalse(StringUtils.isEmpty(lotId) && StringUtils.isEmpty(carrierId),
                           Errors.create().key(MessageIdList.LOT_MISSING_LOTID_AND_CASSETTEID)
                                 .content("LotId " + "or" + " " + "CassetteId can't be Empty!").build());

            if (StringUtils.isNotEmpty(lotId) && StringUtils.isEmpty(carrierId)) {
                lotInfo = lotQueryService.getLotInfoasMap(facility, lotId);
            } else {
                lotInfo = lotQueryService.getLotInfoasMap(facility, lotId, carrierRrn);
            }

            Assert.isFalse(lotInfo == null,
                           Errors.create().key(MessageIdList.LOT_MISSING_ID).content("No such lotId").build());

            upMap.put("lotRrn", navFlag ? 0L : (Long) lotInfo.get("lotRrn"));
            upMap.put("lotId", navFlag ? "" : (String) lotInfo.get("lotId"));
            upMap.put("qty1", navFlag ? "" : lotInfo.get("qty1"));
            upMap.put("productId", navFlag ? "" : lotInfo.get("productId"));
        }

        if (lotTransId != null && !"".equals(lotTransId)) {
            upMap.put("lotTransId", lotTransId);
        }

        request.setAttribute("map", upMap);
        request.setAttribute("lotInfo", lotInfo);
        request.setAttribute("lotId", lotInfo.get("lotId"));
        request.setAttribute("carrierId", lotInfo.get("carrierId"));
        request.setAttribute("onlyView",
                             StringUtils.isNotBlank(request.getParameter("onlyView")) ? Boolean.TRUE : Boolean.FALSE);

        Map map = (Map) request.getAttribute("map");
        Long facilityRrn = LocalContext.getFacilityRrn();
        if (StringUtils.equals(WebUtils.getParameter(FROM_URL_FLAG, request), NUM_ONE)) {
            request.setAttribute("fromUrlFlag", "1");
        }

        lotId = request.getParameter("lotId");
        if (lotInfo == null && lotId != null && lotId.length() > 1) {
            lotInfo = lotQueryService.getLotInfoasMap(facilityRrn.longValue(), lotId);
            request.setAttribute("lotInfo", lotInfo);
            map = new HashMap();
            map.put("lotId", lotInfo.get("lotId"));
            map.put("lotRrn", lotInfo.get("lotRrn"));
            map.put("qty1", lotInfo.get("qty1"));
            map.put("productId", lotInfo.get("productId"));
        }
        if (map == null) {
            map = new HashMap();
        }
        boolean flag = lotInfo == null;
        map.put("flag", flag);
        return map;
    }

    private long isValidEntity(Long facility, String id) {
        return baseService.getNamedObjectRrn(id, getNamedSpace(ObjectList.ENTITY_KEY, facility), ObjectList.ENTITY_KEY);
    }

    private Page getPage(boolean isExportAll, Integer pageSize, Integer currentPage, Integer defaultpageSize,
                         Integer defaultcurrentPage) {
        Page page = new Page();
        currentPage = currentPage == 0 ? defaultcurrentPage : currentPage;
        pageSize = pageSize == 0 ? defaultpageSize : pageSize;
        if (isExportAll) {
            page.setPageNo(1);
            page.setPageSize(Integer.MAX_VALUE);
        } else {
            page.setPageNo(currentPage);
            page.setPageSize(pageSize);
        }
        return page;
    }

}