Junjie
2025-11-19 40d95599c1ac6ef89d465e031132d9c627a7f0bc
src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java
@@ -1,41 +1,58 @@
package com.zy.asrs.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.core.common.Cools;
import com.core.exception.CoolException;
import com.zy.asrs.entity.LocMast;
import com.zy.asrs.entity.WaitPakin;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.mapper.WaitPakinMapper;
import com.zy.asrs.entity.*;
import com.zy.asrs.mapper.BasCrnErrorMapper;
import com.zy.asrs.mapper.WrkMastMapper;
import com.zy.asrs.service.LocMastService;
import com.zy.asrs.service.WrkDetlService;
import com.zy.asrs.service.*;
import com.zy.asrs.utils.Utils;
import com.zy.common.model.LocTypeDto;
import com.zy.common.model.MatDto;
import com.zy.common.model.SearchLocParam;
import com.zy.common.model.StartupDto;
import com.zy.common.service.CommonService;
import com.zy.common.utils.CollectionUtils;
import com.zy.common.utils.HttpHandler;
import com.zy.common.utils.News;
import com.zy.common.utils.RedisUtil;
import com.zy.core.CrnThread;
import com.zy.core.DevpThread;
import com.zy.core.cache.MessageQueue;
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.SlaveType;
import com.zy.core.model.DevpSlave;
import com.zy.core.model.Task;
import com.zy.core.enums.*;
import com.zy.core.model.*;
import com.zy.core.model.command.LedCommand;
import com.zy.core.model.command.LiftCommand;
import com.zy.core.model.protocol.CrnProtocol;
import com.zy.core.model.protocol.LiftProtocol;
import com.zy.core.model.protocol.StaProtocol;
import com.zy.core.properties.SlaveProperties;
import com.zy.core.thread.BarcodeThread;
import com.zy.core.thread.DevpThread;
import com.zy.core.thread.LedThread;
import com.zy.core.thread.SiemensDevpThread;
import com.zy.system.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.*;
/**
 * 立体仓库WCS系统主流程业务
 * Created by vincent on 2020/8/6
 */
@Slf4j
@Service("mainService")
public class MainServiceImpl {
    public static final long COMMAND_TIMEOUT = 5 * 1000;
    @Autowired
    private CommonService commonService;
@@ -44,106 +61,883 @@
    @Autowired
    private WrkMastMapper wrkMastMapper;
    @Autowired
    private WrkMastLogService wrkMastLogService;
    @Autowired
    private WrkDetlService wrkDetlService;
    @Autowired
    private WaitPakinMapper waitPakinMapper;
    private WrkDetlLogService wrkDetlLogService;
    @Autowired
    private LocMastService locMastService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private StaDescService staDescService;
    @Autowired
    private BasCrnpService basCrnpService;
    @Autowired
    private BasDevpService basDevpService;
    @Autowired
    private LocDetlService locDetlService;
    @Autowired
    private BasErrLogService basErrLogService;
    @Autowired
    private BasCrnErrorMapper basCrnErrorMapper;
    @Autowired
    private WrkMastService wrkMastService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${wms.url}")
    private String wmsUrl;
    /**
     * 组托
     * 入库站,根据条码扫描生成入库工作档,工作状态 2
     */
    @Transactional
    public void generateStoreWrkFile() {
    public synchronized void generateStoreWrkFile(Integer mark) {
        // 根据输送线plc遍历
        for (DevpSlave devp : slaveProperties.getDevp()) {
            // 遍历入库口
            for (DevpSlave.InSta inSta : devp.getInSta()) {
                // 获取条码
            for (DevpSlave.Sta inSta : devp.getInSta()) {
                // 获取条码扫描仪信息
                BarcodeThread barcodeThread = (BarcodeThread) SlaveConnection.get(SlaveType.Barcode, inSta.getBarcode());
                String barcode = barcodeThread.getBarcode();
                // 获取入库站信息
                DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
                StaProtocol staProtocol = devpThread.getStation().get(inSta.getStaNo());
                // 判断是否满足入库条件
                if (staProtocol.isAutoing() && staProtocol.isLoading() && staProtocol.isInreq1()
                        && !staProtocol.isEmptyMk() && staProtocol.isInreq1() && staProtocol.getWorkNO() ==0
                        && staProtocol.isPakMk() && !Cools.isEmpty(barcode)) {
                    // 判断重复工作档
                    WrkMast wrkMast = wrkMastMapper.selectPakInStep1(inSta.getStaNo(), barcode);
                    if (wrkMast != null) {
                        log.warn("工作档中已存在该站状态为1的数据,工作号-{}", wrkMast.getWrkNo());
                        continue;
                    }
                    // 获取入库通知档
                    List<WaitPakin> waitPakins = waitPakinMapper.selectList(new EntityWrapper<WaitPakin>().eq("barcode", barcode));
                    // 工作号
                    int workNo = commonService.getWorkNo(0);
                    // 检索库位
                    List<String> matNos = waitPakins.stream().map(WaitPakin::getMatnr).distinct().collect(Collectors.toList());
                    StartupDto startupDto = commonService.getLocNo(1, 1, inSta.getStaNo(), matNos);
                    String locNo = startupDto.getLocNo();
                    if (!waitPakins.isEmpty()) {
                        // 插入工作明细档
                        wrkDetlService.createWorkDetail(workNo, waitPakins, barcode);
                    } else {
                        log.warn("无此入库条码数据---{}", barcode);
                        continue;
                    }
                    // 插入工作主档
                    wrkMast = new WrkMast();
                    wrkMast.setWrkNo(workNo);
                    wrkMast.setIoTime(new Date());
                    wrkMast.setWrkSts(2L); // 工作状态:2.设备上走
                    wrkMast.setIoType(1); // 入出库状态:1.入库
                    wrkMast.setIoPri(10D); // 优先级:10
                    wrkMast.setCrnNo(startupDto.getCrnNo());
                    wrkMast.setSourceStaNo(startupDto.getSourceStaNo());
                    wrkMast.setStaNo(startupDto.getStaNo());
                    wrkMast.setLocNo(startupDto.getLocNo());
                    wrkMast.setBarcode(barcode); // 托盘码
                    wrkMast.setFullPlt("Y"); // 满板:Y
                    wrkMast.setPicking("N"); // 拣料
                    wrkMast.setExitMk("N"); // 退出
                    wrkMast.setEmptyMk("N"); // 空板
                    wrkMast.setLinkMis("N");
//                    wrkMast.setCtnType(sourceStaNo.getCtnType()); // 容器类型
                    // 操作人员数据
                    wrkMast.setAppeTime(new Date());
                    wrkMast.setModiTime(new Date());
                    Integer insert = wrkMastMapper.insert(wrkMast);
                    if (insert == 0) {
                        throw new CoolException("保存工作档失败");
                    }
                    // 更新目标库位状态
                    LocMast locMast = locMastService.selectById(startupDto.getLocNo());
                    locMast.setLocSts("S"); // S.入库预约
                    locMast.setModiTime(new Date());
                    if (!locMastService.updateById(locMast)){
                        throw new CoolException("改变库位状态失败");
                    }
                    // 更新站点信息 且 下发plc命令
                    barcodeThread.setBarcode("");
                    staProtocol.setWorkNO(workNo);
                    staProtocol.setStaNo(startupDto.getStaNo());
                    staProtocol.setPakMk(false);
                    staProtocol.setInreq1(false);
                    boolean result = MessageQueue.offer(SlaveType.Devp, devp.getId(), new Task<>(4, staProtocol));
                    if (!result) {
                        throw new CoolException("更新plc站点信息失败");
                    }
                if (barcodeThread == null) {
                    continue;
                }
                // 获取入库站信息
                SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
                StaProtocol staProtocol = devpThread.getStation().get(inSta.getStaNo());
                if (staProtocol == null) {
                    continue;
                } else {
                    staProtocol = staProtocol.clone();
                }
                //LED
                LedThread ledThread = (LedThread) SlaveConnection.get(SlaveType.Led, inSta.getLed());
                // 判断是否满足入库条件
                if (!staProtocol.isLoading()) {
                    continue;
                }
                if (staProtocol.isAutoing()
                        && staProtocol.isInEnable()
                        && !staProtocol.isEmptyMk()
                        && staProtocol.getWorkNo() == 9999
                        && staProtocol.isPakMk()) {
                    News.warnNoLog("" + mark + " - 0" + " - 开始执行");
                    String barcode = barcodeThread.getBarcode();
                    if (!Cools.isEmpty(barcode)) {
                        News.info("" + mark + " - 1" + " - {}号条码扫描器检测条码信息:{}", inSta.getBarcode(), barcode);
                        if ("NG".endsWith(barcode) || "NoRead".equals(barcode) || "empty".equals(barcode)) {
                            News.info("" + mark + " - 2" + " - 扫码失败1 ===>> {}号条码扫描器检测条码信息:{},站点:{}", inSta.getBarcode(), barcode, inSta.getStaNo());
                            // led 异常显示
                            if (ledThread != null) {
                                String errorMsg = "扫码失败,请重试";
                                MessageQueue.offer(SlaveType.Led, inSta.getLed(), new Task(5, errorMsg));
                            }
                            continue;
                        }
                    } else {
                        News.info("" + mark + " - 3" + " - 扫码失败2 ===>> {}号条码扫描器检测条码信息:{},站点:{}", inSta.getBarcode(), barcode, inSta.getStaNo());
                        // led 异常显示
                        if (ledThread != null) {
                            String errorMsg = "扫码失败,请重试";
                            MessageQueue.offer(SlaveType.Led, inSta.getLed(), new Task(5, errorMsg));
                        }
                        continue;
                    }
                    // 判断重复工作档
                    WrkMast wrkMast = wrkMastMapper.selectPakInStep1(inSta.getStaNo(), barcode);
                    //过滤判断,防止拣料再入库货物,经过入库站再入库时,被退回到退库站
                    WrkMast wrkMast1 = wrkMastMapper.selectPakInStepBarcode(barcode);
                    if (wrkMast1 != null) {
                        if (wrkMast1.getIoType() == 103 || wrkMast1.getIoType() == 107 || wrkMast1.getIoType() == 104) {
                            continue;
                        }
                    }
                    if (wrkMast != null) {
                        News.error("" + mark + " - 4" + " - 工作档中已存在该站状态为( 2.设备上走 )的数据,工作号={}", wrkMast.getWrkNo());
                        // led 异常显示
                        if (ledThread != null) {
                            String errorMsg = "工作档已存在该条码号===>>" + barcode;
                            MessageQueue.offer(SlaveType.Led, inSta.getLed(), new Task(5, errorMsg));
                        }
                        continue;
                    }
                    LiftProtocol liftProtocol = devpThread.getLiftStatus();
                    if(liftProtocol == null) {
                        continue;
                    }
                    if (liftProtocol.getMode() != 1) {
                        continue;
                    }
                    if (liftProtocol.getDeviceStatus() != 0) {
                        continue;
                    }
                    if (liftProtocol.getWorkNo() > 0) {
                        continue;
                    }
                    try {
                        LocTypeDto locTypeDto = new LocTypeDto(staProtocol);
                        SearchLocParam param = new SearchLocParam();
                        param.setBarcode(barcode);
                        param.setIoType(1);
                        param.setSourceStaNo(inSta.getStaNo());
                        param.setLocType1(locTypeDto.getLocType1());
                        String response = new HttpHandler.Builder()
                                .setUri(wmsUrl)
                                .setPath("/rpc/pakin/loc/v1")
                                .setJson(JSON.toJSONString(param))
                                .build()
                                .doPost();
                        JSONObject jsonObject = JSON.parseObject(response);
                        if (jsonObject.getInteger("code").equals(200)) {
                            StartupDto dto = jsonObject.getObject("data", StartupDto.class);
                            WrkMast currentWrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("wrk_no", dto.getWorkNo()));
                            if (currentWrkMast == null) {
                                throw new CoolException("WMS生成任务后,WCS查询为空");
                            }
                            Integer staNo = Utils.getStaNoByLocNo(dto.getLocNo());
                            LiftCommand command = new LiftCommand();
                            command.setWorkNo(dto.getWorkNo());
                            command.setSourceStaNo(inSta.getStaNo());
                            command.setTargetStaNo(staNo);
                            barcodeThread.setBarcode("");
                            boolean result = MessageQueue.offer(SlaveType.Devp, devp.getId(), new Task(2, command));
                            if (!result) {
                                throw new CoolException("更新plc站点信息失败");
                            }
                            currentWrkMast.setWrkSts(3L);// 3.设备执行中
                            currentWrkMast.setCrnStrTime(new Date());
                            wrkMastService.updateById(currentWrkMast);
                        } else {
                            News.error("" + mark + " - 5" + " - 请求接口失败!!!url:{};request:{};response:{}", wmsUrl + "/rpc/pakin/loc/v1", JSON.toJSONString(param), response);
                            // led 异常显示
                            if (ledThread != null) {
                                String errorMsg = jsonObject.getString("msg");
                                MessageQueue.offer(SlaveType.Led, inSta.getLed(), new Task(5, errorMsg));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                } else {
                    News.errorNoLog("" + mark + " - 6" + " - 站点信息不符合入库条件!!!" + " 自动信号:" + staProtocol.isAutoing() + "、可入信号:" + staProtocol.isInEnable()
                            + "、空板信号:" + staProtocol.isEmptyMk() + "、工作号:" + staProtocol.getWorkNo()
                            + "、锁定标记" + staProtocol.isPakMk());
                }
            }
        }
        News.infoNoLog("" + mark + " - 0" + " - 组托  ===》执行完成");
    }
    /**
     * 拣料、并板、盘点再入库
     */
    public synchronized void stnToCrnStnPick(Integer mark) {
        try {
            for (DevpSlave devp : slaveProperties.getDevp()) {
                // 遍历拣料入库口
                for (DevpSlave.Sta pickSta : devp.getPickSta()) {
                    // 获取拣料入库站信息
                    SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
                    StaProtocol staProtocol = devpThread.getStation().get(pickSta.getStaNo());
                    if (staProtocol == null) {
                        continue;
                    } else {
                        staProtocol = staProtocol.clone();
                    }
                    if (staProtocol.isAutoing()
                            && staProtocol.isLoading()
                            && staProtocol.isInEnable()
                            && staProtocol.getWorkNo() > 0
                            && staProtocol.isPakMk()) {
                        News.warnNoLog("" + mark + " - 0" + " - 开始执行");
                        // 获取条码扫描仪信息
                        BarcodeThread barcodeThread = (BarcodeThread) SlaveConnection.get(SlaveType.Barcode, pickSta.getBarcode());
                        if (barcodeThread == null) {
                            continue;
                        }
                        String barcode = barcodeThread.getBarcode();
                        if (!Cools.isEmpty(barcode)) {
                            News.info("" + mark + " - 1" + " - {}号条码扫描器检测条码信息:{}", pickSta.getBarcode(), barcode);
                            if ("NG".endsWith(barcode) || "NoRead".equals(barcode)) {
                                continue;
                            }
                        } else {
                            continue;
                        }
                    WrkMast wrkMast = wrkMastMapper.selectPickStep(barcode);
//                        WrkMast wrkMast = wrkMastMapper.selectPakInStep3(staProtocol.getWorkNo().intValue());
//                        if (wrkMast == null) {
//                            // 无拣料数据
//                            continue;
//                        }
                        if ((wrkMast.getIoType() != 103 && wrkMast.getIoType() != 104 && wrkMast.getIoType() != 107)
                                || Cools.isEmpty(wrkMast.getStaNo()) || Cools.isEmpty(wrkMast.getSourceStaNo())) {
                            continue;
                        }
                        // 获取目标站
                        Wrapper<StaDesc> wrapper = new EntityWrapper<StaDesc>()
                                .eq("type_no", wrkMast.getIoType() - 50)
                                .eq("stn_no", pickSta.getStaNo()) // 作业站点 = 拣料出库的目标站
                                .eq("crn_no", wrkMast.getCrnNo()); // 堆垛机号
                        StaDesc staDesc = staDescService.selectOne(wrapper);
                        if (Cools.isEmpty(staDesc)) {
                            //LED
                            LedThread ledThread = (LedThread) SlaveConnection.get(SlaveType.Led, pickSta.getLed());
                            // led 异常显示
                            if (ledThread != null) {
                                String errorMsg = "此为拣料、并板、盘点再入库.请放在" + pickSta.getBackSta().shortValue() + "站点";
                                MessageQueue.offer(SlaveType.Led, pickSta.getLed(), new Task(5, errorMsg));
                            }
                            continue;
                        }
                        LiftProtocol liftProtocol = devpThread.getLiftStatus();
                        if(liftProtocol == null) {
                            continue;
                        }
                        if (liftProtocol.getMode() != 1) {
                            continue;
                        }
                        if (liftProtocol.getDeviceStatus() != 0) {
                            continue;
                        }
                        if (liftProtocol.getWorkNo() > 0) {
                            continue;
                        }
                        try {
                            LocTypeDto locTypeDto = new LocTypeDto(staProtocol);
                            SearchLocParam param = new SearchLocParam();
                            param.setBarcode(wrkMast.getBarcode());
                            param.setSourceStaNo(pickSta.getStaNo());
                            param.setLocType1(locTypeDto.getLocType1());
                            String response = new HttpHandler.Builder()
                                    .setUri(wmsUrl)
                                    .setPath("/rpc/pakin/pick/loc/v1")
                                    .setJson(JSON.toJSONString(param))
                                    .build()
                                    .doPost();
                            JSONObject jsonObject = JSON.parseObject(response);
                            if (jsonObject.getInteger("code").equals(200)) {
                                WrkMast newWrkMast = wrkMastMapper.selectPakInStepBarcode(wrkMast.getBarcode());
                                if (newWrkMast == null) {
                                    // 无拣料数据
                                    News.error("" + mark + " - 3" + " - 拣选盘点回库获取工作档失败!!! [plc编号:{}]", devp.getId());
                                    continue;
                                }
                                if(newWrkMast.getWrkSts() != 53 && newWrkMast.getWrkSts() != 57) {
                                    News.error("" + mark + " - 3" + " - 拣选盘点回库工作档类型异常!!! [plc编号:{}]", devp.getId());
                                    continue;
                                }
                                if (wrkMast.getWrkSts() != 2) {
                                    News.error("" + mark + " - 3" + " - 拣选盘点回库工作档状态异常!!! [plc编号:{}]", devp.getId());
                                    continue;
                                }
                                Integer staNo = Utils.getStaNoByLocNo(newWrkMast.getLocNo());
                                LiftCommand command = new LiftCommand();
                                command.setWorkNo(newWrkMast.getWrkNo());
                                command.setSourceStaNo(pickSta.getStaNo());
                                command.setTargetStaNo(staNo);
                                boolean result = MessageQueue.offer(SlaveType.Devp, devp.getId(), new Task(2, command));
                                if (!result) {
                                    throw new CoolException("更新plc站点信息失败");
                                }
                                newWrkMast.setWrkSts(3L);// 3.设备执行中
                                newWrkMast.setCrnStrTime(new Date());
                                wrkMastService.updateById(newWrkMast);
                            } else {
                                News.error("" + mark + " - 5" + " - 请求接口失败!!!url:{};request:{};response:{}", wmsUrl + "/rpc/pakin/pick/loc/v1", JSON.toJSONString(param), response);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        News.errorNoLog("" + mark + " - 6" + " - 站点信息不符合入库条件!!!" + " 自动信号:" + staProtocol.isLoading() + "、可入信号:" + staProtocol.isInEnable()
                                + "、空板信号:" + staProtocol.isEmptyMk());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        News.infoNoLog("" + mark + " - 0" + " - 拣料、并板、盘点再入库  ===》执行完成");
    }
    /**
     * 执行出库任务
     */
    public synchronized void executeOutTask() {
        DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        if(devpThread == null) {
            return;
        }
        LiftProtocol liftProtocol = devpThread.getLiftStatus();
        if(liftProtocol == null) {
            return;
        }
        if (liftProtocol.getMode() != 1) {
            return;
        }
        if (liftProtocol.getDeviceStatus() != 0) {
            return;
        }
        if (liftProtocol.getWorkNo() > 0) {
            return;
        }
        //检测出库站是否可出
        StaProtocol staProtocol = devpThread.getStation().get(100);
        if (staProtocol == null) {
            return;
        }
        if (!staProtocol.isAutoing()) {
            return;
        }
        if (staProtocol.isLoading()) {
            return;
        }
        if (!staProtocol.isOutEnable()) {
            return;
        }
        //检查是否有正在执行的任务
        List<WrkMast> workingWrkMast = wrkMastService.selectList(new EntityWrapper<WrkMast>().in("wrk_sts", 3, 12));
        if (!workingWrkMast.isEmpty()) {
            return;
        }
        List<WrkMast> wrkMasts = wrkMastService.selectList(new EntityWrapper<WrkMast>().eq("wrk_sts", 11).orderBy("create_time"));
        if (wrkMasts.isEmpty()) {
            return;
        }
        WrkMast wrkMast = wrkMasts.get(0);
        Integer sourceStaNo = Utils.getStaNoByLocNo(wrkMast.getSourceLocNo());
        LiftCommand command = new LiftCommand();
        command.setWorkNo(wrkMast.getWrkNo());
        command.setSourceStaNo(sourceStaNo);
        command.setTargetStaNo(100);
        boolean result = MessageQueue.offer(SlaveType.Devp, 1, new Task(2, command));
        if (!result) {
            throw new CoolException("更新plc站点信息失败");
        }
        wrkMast.setWrkSts(12L);// 12.设备执行中
        wrkMast.setCrnStrTime(new Date());
        wrkMastService.updateById(wrkMast);
    }
    /**
     * 检测任务完成
     */
    public synchronized void deviceFinished() {
        // 根据plc遍历
        for (DevpSlave devp : slaveProperties.getDevp()) {
            DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
            if (devpThread == null) {
                continue;
            }
            LiftProtocol liftProtocol = devpThread.getLiftStatus();
            if (liftProtocol == null) {
                continue;
            }
            if (liftProtocol.getWorkNo() <= 0) {
                continue;
            }
            if (liftProtocol.getMode() != 1) {
                continue;
            }
            if (liftProtocol.getDeviceStatus() != 0) {
                continue;
            }
            WrkMast wrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("wrk_no", liftProtocol.getWorkNo()));
            if (wrkMast == null) {
                continue;
            }
            if (wrkMast.getWrkSts() == 3) {
                wrkMast.setWrkSts(4L);
                wrkMast.setCrnEndTime(new Date());
                wrkMast.setIoTime(new Date());
                wrkMastService.updateById(wrkMast);
            }else if (wrkMast.getWrkSts() == 12) {
                wrkMast.setWrkSts(14L);
                wrkMast.setCrnEndTime(new Date());
                wrkMast.setIoTime(new Date());
                wrkMastService.updateById(wrkMast);
            }else {
                News.error("未知的工作状态");
            }
        }
    }
    /**
     * 堆垛机异常信息记录
     */
    public synchronized void recCrnErr(Integer mark) {
        Date now = new Date();
        for (CrnSlave crn : slaveProperties.getCrn()) {
            // 获取堆垛机信息
            CrnThread crnThread = (CrnThread) SlaveConnection.get(SlaveType.Crn, crn.getId());
            CrnProtocol crnProtocol = crnThread.getCrnProtocol();
            if (crnProtocol == null) {
                continue;
            }
            if (true) {
//            if (crnProtocol.getModeType() != CrnModeType.STOP) {
                // 有任务
                if (crnProtocol.getTaskNo() != 0) {
                    BasErrLog latest = basErrLogService.findLatestByTaskNo(crn.getId(), crnProtocol.getTaskNo().intValue());
                    // 有异常
                    if (latest == null) {
                        News.warnNoLog("" + mark + " - 1" + " - 开始执行:堆垛机异常信息记录 : 有任务,有异常");
                        if (crnProtocol.getAlarm() != null && crnProtocol.getAlarm() > 0) {
                            WrkMast wrkMast = wrkMastMapper.selectById(crnProtocol.getTaskNo());
                            if (wrkMast == null) {
                                continue;
                            }
                            BasCrnError crnError = basCrnErrorMapper.selectById(crnProtocol.getAlarm());
                            String errName = crnError == null ? String.valueOf(crnProtocol.getAlarm()) : crnError.getErrName();
                            BasErrLog basErrLog = new BasErrLog(
                                    null,    // 编号
                                    wrkMast.getWrkNo(),    // 工作号
                                    now,    // 发生时间
                                    null,    // 结束时间
                                    wrkMast.getWrkSts(),    // 工作状态
                                    wrkMast.getIoType(),    // 入出库类型
                                    crn.getId(),    // 堆垛机
                                    null,    // plc
                                    wrkMast.getLocNo(),    // 目标库位
                                    wrkMast.getStaNo(),    // 目标站
                                    wrkMast.getSourceStaNo(),    // 源站
                                    wrkMast.getSourceLocNo(),    // 源库位
                                    wrkMast.getBarcode(),    // 条码
                                    (int) crnProtocol.getAlarm(),    // 异常码
                                    errName,    // 异常
                                    1,    // 异常情况
                                    now,    // 添加时间
                                    null,    // 添加人员
                                    now,    // 修改时间
                                    null,    // 修改人员
                                    "任务中异常"    // 备注
                            );
                            if (!basErrLogService.insert(basErrLog)) {
                                News.error("" + mark + " - 2" + " - 堆垛机plc异常记录失败 ===>> [id:{}] [error:{}]", crn.getId(), errName);
                            }
                        }
                    } else {
                        // 异常修复
                        if (crnProtocol.getAlarm() == null || crnProtocol.getAlarm() == 0) {
                            latest.setEndTime(now);
                            latest.setUpdateTime(now);
                            latest.setStatus(2);
                            if (!basErrLogService.updateById(latest)) {
                                News.error("" + mark + " - 3" + " - 堆垛机plc异常记录修复失败 ===>> [id:{}] [errLogId:{}]", crn.getId(), latest.getId());
                            }
                        }
                    }
                    // 无任务
                } else {
                    BasErrLog latest = basErrLogService.findLatest(crn.getId());
                    // 有异常
                    if (crnProtocol.getAlarm() != null && crnProtocol.getAlarm() > 0) {
                        News.warnNoLog("" + mark + " - 4" + " - 开始执行:堆垛机异常信息记录 : 无任务,有异常");
                        // 记录新异常
                        if (latest == null || (latest.getErrCode() != crnProtocol.getAlarm().intValue())) {
                            BasCrnError crnError = basCrnErrorMapper.selectById(crnProtocol.getAlarm());
                            String errName = crnError == null ? String.valueOf(crnProtocol.getAlarm()) : crnError.getErrName();
                            BasErrLog basErrLog = new BasErrLog(
                                    null,    // 编号
                                    null,    // 工作号
                                    now,    // 发生时间
                                    null,    // 结束时间
                                    null,    // 工作状态
                                    null,    // 入出库类型
                                    crn.getId(),    // 堆垛机
                                    null,    // plc
                                    null,    // 目标库位
                                    null,    // 目标站
                                    null,    // 源站
                                    null,    // 源库位
                                    null,    // 条码
                                    (int) crnProtocol.getAlarm(),    // 异常码
                                    errName,    // 异常
                                    1,    // 异常情况
                                    now,    // 添加时间
                                    null,    // 添加人员
                                    now,    // 修改时间
                                    null,    // 修改人员
                                    "无任务异常"    // 备注
                            );
                            if (!basErrLogService.insert(basErrLog)) {
                                News.error("" + mark + " - 5" + " - 堆垛机plc异常记录失败 ===>> [id:{}] [error:{}]", crn.getId(), errName);
                            }
                        }
                        // 无异常
                    } else {
                        // 异常修复
                        if (latest != null && latest.getStatus() == 1) {
                            latest.setEndTime(now);
                            latest.setUpdateTime(now);
                            latest.setStatus(2);
                            if (!basErrLogService.updateById(latest)) {
                                News.error("" + mark + " - 6" + " - 堆垛机plc异常记录修复失败 ===>> [id:{}] [errLogId:{}]", crn.getId(), latest.getId());
                            }
                        }
                    }
                }
            }
        }
        News.infoNoLog("" + mark + " - 0" + " - 堆垛机异常信息记录执行完成");
    }
    /**
     * 出库  ===>> 工作档信息写入led显示器
     */
    public synchronized void ledExecute(Integer mark) {
        for (LedSlave led : slaveProperties.getLed()) {
            // 获取输送线plc线程
            DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, led.getDevpPlcId());
            // 命令集合
            List<LedCommand> commands = new ArrayList<>();
//            // 工作档集合
//            List<WrkMast> wrkMasts = new ArrayList<>();
            List<Integer> workNoList = new ArrayList<>();
            for (Integer staNo : led.getStaArr()) {
                // 获取叉车站点
                StaProtocol staProtocol = devpThread.getStation().get(staNo);
                if (null == staProtocol || null == staProtocol.getWorkNo() || 0 == staProtocol.getWorkNo() || !staProtocol.isLoading()) {
                    continue;
                } else {
                    staProtocol = staProtocol.clone();
                }
                Integer wrkNo = null;
                Integer ioType = null;
                Integer targetStaNo = null;
                String sourceLocNo = null;
                String locNo = null;
                String barcode = null;
                // 获取工作档数据
                WrkMast wrkMast = wrkMastMapper.selectById(staProtocol.getWorkNo());
//                if (null == wrkMast || wrkMast.getWrkSts() < 14 || wrkMast.getIoType() < 100) { continue; }
                if (null == wrkMast) {
                    List<WrkMastLog> wrkMastLogs = wrkMastLogService.selectList(new EntityWrapper<WrkMastLog>()
                            .eq("wrk_no", staProtocol.getWorkNo())
                            .orderBy("modi_time", false)
                    );
                    if (wrkMastLogs.isEmpty()) {
                        continue;
                    }
                    WrkMastLog wrkMastLog = wrkMastLogs.get(0);
                    wrkNo = wrkMastLog.getWrkNo();
                    ioType = wrkMastLog.getIoType();
                    sourceLocNo = wrkMastLog.getSourceLocNo();
                    locNo = wrkMastLog.getLocNo();
                    targetStaNo = wrkMastLog.getStaNo();
                    barcode = wrkMastLog.getBarcode();
                }else {
                    wrkNo = wrkMast.getWrkNo();
                    ioType = wrkMast.getIoType();
                    sourceLocNo = wrkMast.getSourceLocNo();
                    locNo = wrkMast.getLocNo();
                    targetStaNo = wrkMast.getStaNo();
                    barcode = wrkMast.getBarcode();
                }
                News.warnNoLog("" + mark + " - 0" + " - 开始执行:出库  ===>> 工作档信息写入led显示器");
                workNoList.add(wrkNo);
                // 组装命令
                LedCommand ledCommand = new LedCommand();
                ledCommand.setWorkNo(wrkNo);
                ledCommand.setIoType(ioType);
                // 出库模式
                switch (ioType) {
                    case 1:
                        ledCommand.setTitle("全板入库");
                        break;
                    case 10:
                        ledCommand.setTitle("空板入库");
                        break;
                    case 101:
                        ledCommand.setTitle("全板出库");
                        break;
                    case 103:
                        ledCommand.setTitle("拣料出库");
                        break;
                    case 104:
                        ledCommand.setTitle("并板出库");
                        break;
                    case 107:
                        ledCommand.setTitle("盘点出库");
                        break;
                    case 110:
                        ledCommand.setTitle("空板出库");
                        ledCommand.setEmptyMk(true);
                        break;
                    case 53:
                        ledCommand.setTitle("拣料入库");
                        break;
                    case 57:
                        ledCommand.setTitle("盘点入库");
                        break;
                    case 54:
                        ledCommand.setTitle("并板入库");
                        break;
                    default:
                        News.error("" + mark + " - 1" + " - 任务入出库类型错误!!![工作号:{}] [入出库类型:{}]", wrkNo, ioType);
                        break;
                }
                ledCommand.setSourceLocNo(sourceLocNo);
                ledCommand.setLocNo(locNo);
                ledCommand.setStaNo(targetStaNo);
                ledCommand.setBarcode(barcode);
//                ledCommand.setSourceStaNo(wrkMast.getSourceStaNo());
                if (ioType != 110 && ioType != 10) {
                    List<WrkDetl> wrkDetls = wrkDetlService.findByWorkNo(wrkNo);
                    if (!wrkDetls.isEmpty()) {
                        WrkDetl wrkDetl = wrkDetls.get(0);
                        double anfme = 0D;
                        double weight = 0D;
                        for (WrkDetl detl : wrkDetls) {
                            anfme += detl.getAnfme();
                            weight += detl.getWeight();
                            wrkDetl.setAnfme(anfme);
                            wrkDetl.setWeight(weight);
                        }
                        List<LocDetl> locDetls = locDetlService.selectList(new EntityWrapper<LocDetl>()
                                .eq("loc_no", wrkMast.getSourceLocNo()));
                        double totalAnfme = 0D;
                        double totalWeight = 0D;
                        for (LocDetl locDetl : locDetls) {
                            totalAnfme += locDetl.getAnfme();
                            totalWeight += locDetl.getWeight();
                        }
                        wrkDetl.setStockNum(totalAnfme);
                        wrkDetl.setStockNum2(totalWeight);
                        ledCommand.getMatDtos().add(new MatDto(
                                wrkDetl.getMatnr()
                                , wrkDetl.getMaktx()
                                , wrkDetl.getAnfme()
                                , wrkDetl.getWeight()
                                , wrkDetl.getStockNum()
                                , wrkDetl.getStockNum2()
                                , wrkDetl.getSpecs()
                                , wrkDetl.getSku()
                                , wrkDetl.getZpallet()
                                , wrkDetl.getModel()
                                , wrkDetl.getSupp()
                                , wrkDetl.getKpCstmrName()
                                , wrkDetl.getOrderNo()
                                , wrkDetl.getCstateid$()
                        ));
                    }else {
                        List<WrkDetlLog> wrkDetlLogs = wrkDetlLogService.selectTodayByWrkNo(wrkNo);
                        if(!wrkDetlLogs.isEmpty()) {
                            WrkDetlLog wrkDetlLog = wrkDetlLogs.get(0);
                            double anfme = 0D;
                            double weight = 0D;
                            for (WrkDetlLog detl : wrkDetlLogs) {
                                anfme += detl.getAnfme();
                                weight += detl.getWeight();
                                wrkDetlLog.setAnfme(anfme);
                                wrkDetlLog.setWeight(weight);
                            }
                            List<LocDetl> locDetls = locDetlService.selectList(new EntityWrapper<LocDetl>()
                                    .eq("loc_no", sourceLocNo));
                            double totalAnfme = 0D;
                            double totalWeight = 0D;
                            for (LocDetl locDetl : locDetls) {
                                totalAnfme += locDetl.getAnfme();
                                totalWeight += locDetl.getWeight();
                            }
                            wrkDetlLog.setStockNum(totalAnfme);
                            wrkDetlLog.setStockNum2(totalWeight);
                            ledCommand.getMatDtos().add(new MatDto(
                                    wrkDetlLog.getMatnr()
                                    , wrkDetlLog.getMaktx()
                                    , wrkDetlLog.getAnfme()
                                    , wrkDetlLog.getWeight()
                                    , wrkDetlLog.getStockNum()
                                    , wrkDetlLog.getStockNum2()
                                    , wrkDetlLog.getSpecs()
                                    , wrkDetlLog.getSku()
                                    , wrkDetlLog.getZpallet()
                                    , wrkDetlLog.getModel()
                                    , wrkDetlLog.getSupp()
                                    , wrkDetlLog.getKpCstmrName()
                                    , wrkDetlLog.getOrderNo()
                                    , wrkDetlLog.getCstateid$()
                            ));
                        }
                    }
                }
                commands.add(ledCommand);
            }
            Set<Integer> workNos = new HashSet<>(workNoList);
            // 获取LED线程
            LedThread ledThread = (LedThread) SlaveConnection.get(SlaveType.Led, led.getId());
            // 相同工作号集合则过滤
            if (CollectionUtils.equals(ledThread.getWorkNos(), workNos)) {
                continue;
            }
//             命令下发 -------------------------------------------------------------------------------
//            if (!commands.isEmpty()) {
//                if (led.getId() < 7) {
//                    if (!MessageQueue.offer(SlaveType.Led, led.getId(), new Task(3, commands))) {
//                        News.error(""+mark+" - 2"+" - {}号LED命令下发失败!!![ip:{}] [port:{}]", led.getId(), led.getIp(), led.getPort());
//                        continue;
//                    } else {
//                        ledThread.setLedMk(false);
//                    }
//                } else {
//                    if (!MessageQueue.offer(SlaveType.Led, led.getId(), new Task(1, commands))) {
//                        News.error(""+mark+" - 3"+" - {}号LED命令下发失败!!![ip:{}] [port:{}]", led.getId(), led.getIp(), led.getPort());
//                        continue;
//                    } else {
//                        ledThread.setLedMk(false);
//                    }
//                }
//
//            }
            // 命令下发 -------------------------------------------------------------------------------
            if (!commands.isEmpty()) {
                if (!MessageQueue.offer(SlaveType.Led, led.getId(), new Task(3, commands))) {
                    News.error("{}号LED命令下发失败!!![ip:{}] [port:{}]", led.getId(), led.getIp(), led.getPort());
                    continue;
                } else {
                    ledThread.setLedMk(false);
                }
            }
            try {
                // 修改主档led标记
                for (Integer wrkNo : workNoList) {
                    WrkMast wrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("wrk_no", wrkNo));
                    if (wrkMast != null) {
                        wrkMast.setOveMk("Y");
                        wrkMast.setModiTime(new Date());
                        if (wrkMastMapper.updateById(wrkMast) == 0) {
                            News.errorNoLog("" + mark + " - 4" + " - 更新工作档失败");
                            throw new CoolException("更新工作档失败");
                        }
                    }
                }
                // 更新线程当前工作号集合
                ledThread.setWorkNos(workNos);
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        News.infoNoLog("" + mark + " - 0" + " - 出库  ===>> 工作档信息写入led显示器执行完成");
    }
    /**
     * 其他  ===>> LED显示器复位,显示默认信息
     */
    public synchronized void ledReset(Integer mark) {
        News.warnNoLog("" + mark + " - 0" + " - 开始执行:其他  ===>> LED显示器复位,显示默认信息");
        for (LedSlave led : slaveProperties.getLed()) {
            // 获取输送线plc线程
            DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, led.getDevpPlcId());
            // 命令集合
            boolean reset = true;
            for (Integer staNo : led.getStaArr()) {
                // 获取叉车站点
                StaProtocol staProtocol = devpThread.getStation().get(staNo);
                if (staProtocol == null) {
                    continue;
                }
                if (staProtocol.getWorkNo() != 0 && staProtocol.isLoading()) {
                    reset = false;
                    break;
                }
            }
            // 获取led线程
            LedThread ledThread = (LedThread) SlaveConnection.get(SlaveType.Led, led.getId());
            // led显示默认内容
            if (reset && !ledThread.isLedMk()) {
                ledThread.setLedMk(true);
                if (!MessageQueue.offer(SlaveType.Led, led.getId(), new Task(4, new ArrayList<>()))) {
                    News.error("" + mark + " - 1" + " - {}号LED命令下发失败!!![ip:{}] [port:{}]", led.getId(), led.getIp(), led.getPort());
                } else {
                }
            }
        }
        News.infoNoLog("" + mark + " - 0" + " - 执行完成:其他  ===>> LED显示器复位,显示默认信息");
    }
}