package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesEarlyWarningService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.bean.edi.wh.order.MesCimGmGepics;
import cn.estsh.i3plus.pojo.mes.model.KanBanPictureModel;
import cn.estsh.i3plus.pojo.mes.model.MesEarlyWarningKanBanModel;
import cn.estsh.i3plus.pojo.mes.model.MesKanBanShowModel;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.estsh.i3plus.pojo.mes.repository.wh.MesCimGmGepicsRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MesEarlyWarningServiceImpl implements IMesEarlyWarningService {

    @Autowired
    private MesEarlyWarningKanBanRepository earlyWarningKanBanRao;

    @Autowired
    private MesCimGmGepicsRepository cimGmGepicsRao;

    @Autowired
    private MesWorkOrderAssemblyRepository workOrderAssemblyRao;

    @Autowired
    private MesWorkOrderRepository workOrderRao;

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private MesEarlyWarningRecordRepository earlyWarningRecordRao;

    @Autowired
    private MesQueueOrderRepository queueOrderRao;

    @Autowired
    private MesEarlyWarningScreenRepository screenRao;
    @Override
    public  List<MesEarlyWarningKanBan> getEarlyWarningList(String organizeCode) {

        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        return earlyWarningKanBanRao.findByHqlWhere(ddlPackBean);
    }

    @Override
    public void saveEarlyWarning(MesEarlyWarningKanBanModel model) {
        MesEarlyWarningKanBan kanBan = new MesEarlyWarningKanBan();
        try {
            BeanUtils.copyProperties(kanBan,model);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error(e.getMessage());
            MesPcnException.throwMesBusiException("类型转换出错!"+e.getMessage());
        }
        ConvertBean.saveOrUpdate(kanBan,model.getCreateUser());
        earlyWarningKanBanRao.insert(kanBan);

    }

    @Override
    public void updateEarlyWarning(MesEarlyWarningKanBan earlyWarning) {
        ConvertBean.saveOrUpdate(earlyWarning,earlyWarning.getCreateUser());
        earlyWarningKanBanRao.insert(earlyWarning);

    }

    @Override
    public void deleteEarlyWarning(Long id, String organizeCode,String userName) {
        earlyWarningKanBanRao.deleteWeaklyByProperties(new String[]{"id","organizeCode"},new Object[]{id,organizeCode},userName);
    }

    @Override
    public MesEarlyWarningKanBan getKanbanData(Long id,String organizeCode) {
        List<MesEarlyWarningKanBan> list = earlyWarningKanBanRao.findByProperty(new String[]{"id", "organizeCode"}, new Object[]{id, organizeCode});
        if (!list.isEmpty()){
            return list.get(0);
        }
        return new MesEarlyWarningKanBan();
    }

    @Override
    public MesKanBanShowModel doGetData(Long id, String organizeCode) throws ParseException {
        DdlPackBean earlyWarningKanBanPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(id, "id", earlyWarningKanBanPackBean);
        List<MesEarlyWarningKanBan> list = earlyWarningKanBanRao.findByHqlTopWhere(earlyWarningKanBanPackBean, 1);
        if (list.isEmpty()) {
            return new MesKanBanShowModel();
        }

        MesEarlyWarningKanBan kanBan = list.get(0);
        String jacInfoPoint = kanBan.getJacInfoPoint();
        int custOnlineInfo = kanBan.getCustOnlineInfo();
        String workCenterCode = kanBan.getWorkCenterCode();
        String workCellCode = kanBan.getWorkCellCode();
        //1.获取最近的20条v107信息
        List<MesCimGmGepics> gmGepicsList = getlastDataList(1, jacInfoPoint, organizeCode, 20);
        //2.获取最新的一条报文信息,取gmGepicsList的第一条
        MesCimGmGepics lastCimGmGepics = gmGepicsList.get(0);
        //3.获取最新客户上线的报文
        List<MesCimGmGepics> gmGepicsListOne = getlastDataList(custOnlineInfo, jacInfoPoint, organizeCode, 1);
        MesCimGmGepics lastOne = !gmGepicsListOne.isEmpty() ?gmGepicsListOne.get(0) : null;
        if (lastOne==null){
            MesKanBanShowModel mesKanBanShowModel = new MesKanBanShowModel();
            mesKanBanShowModel.setWorkOrderCenter(kanBan.getWorkCenterCode());
            return mesKanBanShowModel;
        }
        //4.获取最新工位单号 获取工单的产线和工位的最新的工单
        MesWorkOrder lastWorkOrder = getLastWorkOrder(workCenterCode, workCellCode, organizeCode);
        //5.获取最新下线工单
        MesWorkOrder lastOfflineOrder = getLastOfflineOrder(workCenterCode, organizeCode);
        if (lastWorkOrder == null && lastOfflineOrder != null){
            lastWorkOrder = lastOfflineOrder;
        }
        //6.查询报警产量 & 获取开班起始时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(now);
        String tempStartDatetime = date + " " + kanBan.getShiftStartTime() + ":00";
        Date shiftStartTime = sdf1.parse(tempStartDatetime);
        //如果小于当前时间，显示前一天的统计
        Calendar calendar = Calendar.getInstance();
        if (now.before(shiftStartTime)) {
            calendar.setTime(now);
            calendar.add(Calendar.DATE, -1);
        } else {
            calendar.setTime(shiftStartTime);
        }
        String realEndTime = sdf1.format(calendar.getTime());
        //7.根据条件获取工单的数量
        Integer workCounts = getWorkCounts(realEndTime, organizeCode, workCenterCode);

        //8.查询报警产量
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(now);

        int productCount = kanBan.getProductCount();
        int productDay = kanBan.getProductDay();
        calendar1.add(Calendar.DATE,-productDay);
//        List<String> vehicleNoList = getCLWarning(sdf1.format(calendar1.getTime()), productCount,organizeCode);
        List<String> vehicleNoList = new ArrayList<>();
        //9.汇总数据
        return doGetSGMData(kanBan, gmGepicsList, lastCimGmGepics, lastOne, lastWorkOrder, lastOfflineOrder, workCounts, vehicleNoList);
    }

    @Override
    public void savePicture(KanBanPictureModel model) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(model.getOrganizeCode());
        DdlPreparedPack.getOrderBy("createDatetime", CommonEnumUtil.ASC_OR_DESC.DESC.getValue(), ddlPackBean);
        List<MesEarlyWarningScreen> screenList = screenRao.findByHqlWhere(ddlPackBean);
        if (!screenList.isEmpty()) {
            //5分钟内只记录一次,防止前端不断刷数据
            MesEarlyWarningScreen mesEarlyWarningScreen = screenList.get(0);
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(mesEarlyWarningScreen.getCreateDatetime());
                Calendar dateC = Calendar.getInstance();
                dateC.setTime(date);
                dateC.add(Calendar.MINUTE,5);
                Calendar now = Calendar.getInstance();
                now.setTime(new Date());
                if (dateC.before(now)){
                    return;
                }
            } catch (ParseException e) {
            }

        }
        MesEarlyWarningScreen mesEarlyWarningScreen = new MesEarlyWarningScreen();
        mesEarlyWarningScreen.setPicture(model.getPicture());
        if (model.getId() != null){
            mesEarlyWarningScreen.setRecordId(model.getId().toString());
        }
        mesEarlyWarningScreen.setOrganizeCode(model.getOrganizeCode());
        ConvertBean.saveOrUpdate(mesEarlyWarningScreen, AuthUtil.getSessionUser().getUserName());
        screenRao.insert(mesEarlyWarningScreen);
    }

    /**
     * 获取最新20条数据
     * @param type
     * @param gaRule 信息点
     * @return
     */
    private List<MesCimGmGepics> getlastDataList(int type, String gaRule,String organizeCode,Integer count){
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(type,"type",ddlPackBean);
        if (!StringUtils.isEmpty(gaRule)){
            DdlPreparedPack.getStringEqualPack(gaRule,"gaRule",ddlPackBean);
        }
        DdlPreparedPack.getStringEqualPack(organizeCode,"organizeCode",ddlPackBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue(),CommonEnumUtil.ASC_OR_DESC.DESC.getValue()},new String[]{"createDatetime","rowNo"},ddlPackBean);
        return cimGmGepicsRao.findByHqlTopWhere(ddlPackBean,count);
    }

    /**
     * 根据产线工位 查询最新的工单
     * 工单status 不是  40已关闭，90已拆解 状态
     * sort_flag 不是 E X 单
     * @param workCenterCode
     * @param workCellCode
     * @param organizeCode
     * @return
     */
    private MesWorkOrder getLastWorkOrder(String workCenterCode,String workCellCode,String organizeCode){
        //工单status 不是  40已关闭，90已拆解 状态
        //工单sort_flag 不是 E X单
        //工单order_type 类型为 排序单类型
        //工单 cust_order_code 不为空
        //工单 的id in装配件清单表中 工位等于@workCellCode 且 status = 1
        //工单 productSeq =  work_order表中最大的排序信息 【work_order 的id in (装配件清单表中 工位等于@workCellCode 且 status = 1 已经装配) 产线=，order_type = 排序单，sort_flag 不为 x ,E;status not in 入参1，入参2，cust_order_code不为空】

        // workOrderAssembly
//        DdlPackBean assemblyPackBean = DdlPackBean.getDdlPackBean(organizeCode);
//        DdlPreparedPack.getStringEqualPack(workCenterCode,"workCenterCode",assemblyPackBean);
//        DdlPreparedPack.getStringEqualPack(workCellCode,"workCellCode",assemblyPackBean);
//        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue(),"assemblyStatus",assemblyPackBean);
//        List<MesWorkOrderAssembly> mesWorkOrderAssemblyList = workOrderAssemblyRao.findByHqlWhere(assemblyPackBean);
//        //todo 有内存溢出风险 调试一下,写hql按照分组查询出workOrderNoList
//        List<String> workOrderNoList = mesWorkOrderAssemblyList.stream().map(MesWorkOrderAssembly::getWorkOrderNo).distinct().collect(Collectors.toList());
        List<Integer> orderStatusList = new ArrayList<>();
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.CLOSE.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.DISMANTLE.getValue());

        List<String> orderFlagList = new ArrayList<>();
        orderFlagList.add(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.E.getValue());
        orderFlagList.add(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.X.getValue());
        DdlPackBean queueOrderPackBean = DdlPackBean.getDdlPackBean(organizeCode);
//        DdlPreparedPack.getInPackList(workOrderNoList,"workOrderNo",queueOrderPackBean);
        DdlPreparedPack.getStringEqualPack(workCenterCode,"workCenterCode",queueOrderPackBean);
        DdlPreparedPack.getStringEqualPack(workCellCode,"workCellCode",queueOrderPackBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.QUEUE_ORDER_STATUS.CREATE.getValue(),"status",queueOrderPackBean);
        DdlPreparedPack.getNotInPack(orderFlagList,"orderFlag",queueOrderPackBean);
        DdlPreparedPack.getStringNotBlanklPack("custOrderNo",queueOrderPackBean);
        DdlPreparedPack.getOrderBy("productSeq",CommonEnumUtil.ASC_OR_DESC.ASC.getValue(), queueOrderPackBean);
        //先查对列表,找到对应产线工位的工单
        List<MesQueueOrder> queueOrderList = queueOrderRao.findByHqlTopWhere(queueOrderPackBean,1);
        //过滤掉关闭和拆解的工单
        List<MesWorkOrder> workOrderList = new ArrayList<>();
        if (!queueOrderList.isEmpty()){
            List<Integer> orderStatusList1 = new ArrayList<>();
            orderStatusList1.add(MesExtEnumUtil.ORDER_STATUS.RELEASE.getValue());
            orderStatusList1.add(MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue());
            List<String> workOrderNoQueueList = queueOrderList.stream().map(MesQueueOrder::getWorkOrderNo).distinct().collect(Collectors.toList());
            DdlPackBean orderPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getInPackList(workOrderNoQueueList,"workOrderNo",orderPackBean);
            DdlPreparedPack.getInPackList(orderStatusList1,"workOrderStatus",orderPackBean);
            DdlPreparedPack.getOrderBy("productSeq",CommonEnumUtil.ASC_OR_DESC.ASC.getValue(), orderPackBean);
            workOrderList = workOrderRao.findByHqlTopWhere(orderPackBean, 1);
        }
        return !workOrderList.isEmpty() ? workOrderList.get(0) : null;
    }

    private MesWorkOrder getLastOfflineOrder(String workCenterCode,String organizeCode){

        List<String> sortFlagList = new ArrayList<>();
        sortFlagList.add(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.E.getValue());
        sortFlagList.add(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.X.getValue());

        List<Integer> orderStatusList = new ArrayList<>();
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.SHIPPING.getValue());
        DdlPackBean workOrderPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode,"workCenterCode",workOrderPackBean);
        DdlPreparedPack.getInPackList(orderStatusList,"workOrderStatus",workOrderPackBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.ORDER_TYPE.SORT.getValue(),"workOrderType",workOrderPackBean);
        DdlPreparedPack.getNotInPack(sortFlagList,"orderFlag",workOrderPackBean);
        DdlPreparedPack.getStringNotBlanklPack("custOrderNo",workOrderPackBean);
        DdlPreparedPack.getOrderBy("productSeq",CommonEnumUtil.ASC_OR_DESC.DESC.getValue(), workOrderPackBean);
        List<MesWorkOrder> mesWorkOrders = workOrderRao.findByHqlTopWhere(workOrderPackBean, 1);
        return !mesWorkOrders.isEmpty() ? mesWorkOrders.get(0): null;
    }

    private Integer getWorkCounts(String realEndTime,String organizeCode,String workCenterCode){
        DdlPackBean workOrderPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        List<Integer> orderStatusList = new ArrayList<>();
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.SHIPPING.getValue());
        DdlPreparedPack.getStringEqualPack(workCenterCode,"workCenterCode",workOrderPackBean);
        DdlPreparedPack.getInPackList(orderStatusList,"workOrderStatus",workOrderPackBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.ORDER_TYPE.SORT.getValue(),"workOrderType",workOrderPackBean);
        DdlPreparedPack.getStringBiggerPack(realEndTime,"offlineTime",workOrderPackBean);
        DdlPreparedPack.getStringNoEqualPack(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.X.getValue(),"orderFlag",workOrderPackBean);

        return workOrderRao.findByHqlWhereCount(workOrderPackBean);
    }

    //报警产量
    private List<String> getCLWarning(String date, int qty,String organizeCode) {
        List<Integer> orderStatusList = new ArrayList<>();
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.CREATE.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.RELEASE.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue());
        orderStatusList.add(MesExtEnumUtil.ORDER_STATUS.DISMANTLE.getValue());

        StringBuilder hql = new StringBuilder();
        hql.append("   select carModelCode from  MesWorkOrder");
        hql.append("   where organizeCode = :organizeCode");
        hql.append("   and createDatetime <= :createDatetime");
        hql.append("   and workOrderStatus in (:workOrderStatus)");
        hql.append("   and orderFlag != :sortFlag");
        hql.append("   group by carModelCode ");
        hql.append("   having count(carModelCode) <= :qty");
        Query query = entityManager.createQuery(hql.toString());
        query.setParameter("workOrderStatus",orderStatusList);
        query.setParameter("organizeCode",organizeCode);
        query.setParameter("createDatetime", date);
        query.setParameter("qty", (long)qty);
        query.setParameter("sortFlag", MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.X.getValue());
        return (List<String>)query.getResultList();
    }

    //汇总数据

    /**
     *
     * @param infoV107List 报文信息
     * @param infoDD 最新报文信息
     * @param infoKH 最新客户上线信息
     * @param workOrder 最新工单
     * @param workOrderLast 最新下线工单
     * @param workCount 工单数量
     * @param vehicleNoList 报警
     */
    private MesKanBanShowModel doGetSGMData(MesEarlyWarningKanBan kanBan,List<MesCimGmGepics> infoV107List,MesCimGmGepics infoDD, MesCimGmGepics infoKH, MesWorkOrder workOrder,MesWorkOrder workOrderLast,int workCount,List<String> vehicleNoList) throws ParseException {
        MesKanBanShowModel mesKanBanShowModel = new MesKanBanShowModel();
        //是否截图
        boolean shortCut = false;
        if (infoV107List.isEmpty()){
            return mesKanBanShowModel;
        }
        StringBuilder errorMsg = new StringBuilder();
        for (int i = 0; i < infoV107List.size()-1; i++) {
            int preCsnNo = Integer.parseInt(infoV107List.get(i+1).getCsnNo().substring(3,10));
            int curCsnNo = Integer.parseInt(infoV107List.get(i).getCsnNo().substring(3,10));
            if (curCsnNo != preCsnNo+1){
                //需要保留截图
                //需要发声音
                //需要发送记录信息 当前csnNo进行了跳号
                errorMsg.append(String.format("当前CsnNo:%d进行了跳号;\n",curCsnNo));
            }
        }
        if (errorMsg.length()>0){
            shortCut = true;
            mesKanBanShowModel.setVoice("跳号的声音");
        }
        mesKanBanShowModel.setErrorMsg(errorMsg.toString());

        if (infoDD == null){
            return mesKanBanShowModel;
        }
        if (infoKH == null){
            return mesKanBanShowModel;
        }
        if (workOrder == null){
            return mesKanBanShowModel;
        }
        if (workOrderLast == null){
            return mesKanBanShowModel;
        }
        //据上次获取v107信息的时间
        String matchTime = infoDD.getCreateDatetime();

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime match = LocalDateTime.parse(matchTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        long minutes = Duration.between(match,now).toMinutes();
        mesKanBanShowModel.setMinutes(minutes);

        //最新v107信息
        String v107Msg = infoDD.getCsnNo() + "@" + infoDD.getDate() + " " + infoDD.getTime();
        mesKanBanShowModel.setV107Msg(v107Msg);
        //最新客户上线信息
        String infoKHCsnNo = infoKH.getCsnNo() + "@" + infoKH.getDate() + " " + infoKH.getTime();
        mesKanBanShowModel.setInfoKHCsnNo(infoKHCsnNo);
        //生产线
        String workOrderCenter = kanBan.getWorkCenterName() +" " + kanBan.getWorkCenterDescription();
        mesKanBanShowModel.setWorkOrderCenter(workOrderCenter);
        //供货缓冲 >=
        Long supplyRedBuffer = kanBan.getSupplyRedBuffer();
        Long supplyYellowBuffer = kanBan.getSupplyYellowBuffer();
        mesKanBanShowModel.setSupplyRedBuffer(supplyRedBuffer);
        //供货缓冲实际
        Long realSupplyBuffer = Long.parseLong(infoDD.getCsnNo().substring(3,10)) - Long.parseLong(infoKH.getCsnNo().substring(3,10)) - kanBan.getOnlineAdjustNum();
        if (realSupplyBuffer < 0){
            realSupplyBuffer = 0L;
        }
        mesKanBanShowModel.setRealSupplyBuffer(realSupplyBuffer);
        if (realSupplyBuffer < supplyRedBuffer){
            mesKanBanShowModel.setRealSupplyBufferColor("red");
            mesKanBanShowModel.setSupplyRedBuffer(supplyRedBuffer);
        }else if (realSupplyBuffer < supplyYellowBuffer){
            mesKanBanShowModel.setRealSupplyBufferColor("orange");
            mesKanBanShowModel.setSupplyRedBuffer(supplyYellowBuffer);
        }

        //线头积单
        Long summaryWorkOrderRedCount = kanBan.getSummaryWorkOrderRedCount();
        mesKanBanShowModel.setSummaryWorkOrderRedCount(summaryWorkOrderRedCount);
        //线头实际积单
        long summaryRealSupplyRealCount;
        String custOrderNo = workOrder.getCustOrderNo();
        if(custOrderNo.length() >= 10){
            summaryRealSupplyRealCount = Long.parseLong(infoDD.getCsnNo().substring(3, 10)) - Long.parseLong(workOrder.getCustOrderNo().substring(workOrder.getCustOrderNo().length() - 7));
        }else {
            summaryRealSupplyRealCount = Long.parseLong(infoDD.getCsnNo().substring(infoDD.getCsnNo().length() - 5))- Long.parseLong(workOrder.getCustOrderNo().substring(workOrderLast.getCustOrderNo().length() - 7));
        }
        if(summaryRealSupplyRealCount < 0){
            summaryRealSupplyRealCount = 0;
        }
        mesKanBanShowModel.setSummaryRealSupplyRealCount(summaryRealSupplyRealCount);
        Long summaryWorkOrderYellowCount = kanBan.getSummaryWorkOrderYellowCount();
        if (summaryRealSupplyRealCount > summaryWorkOrderYellowCount && summaryRealSupplyRealCount < summaryWorkOrderRedCount){
            mesKanBanShowModel.setSummaryWorkOrderColor("orange");
        }else if (summaryRealSupplyRealCount >= summaryWorkOrderRedCount){
            mesKanBanShowModel.setSummaryWorkOrderColor("red");
        }
        //成品缓冲
        Long productionRedBuffer =kanBan.getProductionRedBuffer();
        mesKanBanShowModel.setProductionRedBuffer(productionRedBuffer);
        //成品实际缓冲
        Long realProductionBuffer;
        if (workOrderLast.getCustOrderNo().length() >= 10){
            realProductionBuffer = Long.parseLong(workOrderLast.getCustOrderNo().substring(workOrderLast.getCustOrderNo().length() - 7)) - Long.parseLong(infoKH.getCsnNo().substring(3, 10))  - kanBan.getOnlineToShippingAdjustNum() ;
        }else {
            realProductionBuffer = Long.parseLong(workOrderLast.getCustOrderNo().substring(workOrderLast.getCustOrderNo().length() - 5)) - Long.parseLong(infoKH.getCsnNo().substring(infoKH.getCsnNo().length()-5)) - kanBan.getOnlineToShippingAdjustNum() ;

        }
        if(realProductionBuffer <0){
            realProductionBuffer = 0L;
        }
        mesKanBanShowModel.setRealProductionBuffer(realProductionBuffer);
        Long productionYellowBuffer = kanBan.getProductionYellowBuffer();
        if (realProductionBuffer < productionRedBuffer){
            mesKanBanShowModel.setRealProductionBufferColor("red");
        }else if (realProductionBuffer < productionYellowBuffer){
            mesKanBanShowModel.setRealProductionBufferColor("orange");
        }
        //声音信息
        //private String voice;
        //错误信息
        //private String errorMsg;
        //截图地址
        String saveUrl = kanBan.getPictureUrl();
        mesKanBanShowModel.setShortCut(shortCut);
        mesKanBanShowModel.setSaveUrl(saveUrl);

        if (kanBan.getRecord().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue())){
            MesEarlyWarningRecord record = new MesEarlyWarningRecord();
            //供货缓冲实际值
            record.setRealSupplyBuffer(realSupplyBuffer);
            //实际积累
            record.setSummaryRealSupplyRealCount(summaryRealSupplyRealCount);
            //成品缓冲
            record.setRealProductionBuffer(realProductionBuffer);
            // 告警数量
            record.setWorkOrderCount((long)workCount);
            record.setWorkCenterCode(workOrderCenter);
            record.setGaNo(infoDD.getCsnNo());
            record.setLastGaNo(infoKH.getCsnNo());
            record.setRemark(kanBan.getId().toString());
            ConvertBean.saveOrUpdate(record,"kanban");
            earlyWarningRecordRao.insert(record);
            mesKanBanShowModel.setRecordId(record.getId());
        }
        mesKanBanShowModel.setTotalCount((long)workCount);
        return mesKanBanShowModel;
    }
}
