package com.foreverwin.mesnac.common.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.constant.CustomFieldConstant;
import com.foreverwin.mesnac.common.dto.LabelPrintDto;
import com.foreverwin.mesnac.common.dto.SfcDispatchDto;
import com.foreverwin.mesnac.common.enums.DispatchStatusEnum;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.mapper.ProdReadyTaskMapper;
import com.foreverwin.mesnac.common.model.Message;
import com.foreverwin.mesnac.common.model.PrintLog;
import com.foreverwin.mesnac.common.model.ProdReadyTask;
import com.foreverwin.mesnac.common.model.ProdReadyTaskDetail;
import com.foreverwin.mesnac.common.service.*;
import com.foreverwin.mesnac.common.util.ActiveMQUtil;
import com.foreverwin.mesnac.common.util.DateUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.dto.BomComponentDto;
import com.foreverwin.mesnac.meapi.dto.RouterStepDto;
import com.foreverwin.mesnac.meapi.mapper.CustomFieldsMapper;
import com.foreverwin.mesnac.meapi.mapper.UserGroupMapper;
import com.foreverwin.mesnac.meapi.mapper.WorkCenterMapper;
import com.foreverwin.mesnac.meapi.model.*;
import com.foreverwin.mesnac.meapi.service.*;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import com.sap.me.messaging.MessageTypeBOHandle;
import com.sap.me.user.UserGroupBOHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 生产准备任务主表 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-06-23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProdReadyTaskServiceImpl extends ServiceImpl<ProdReadyTaskMapper, ProdReadyTask> implements ProdReadyTaskService {

    public static final String P01 = "P01";
    public static final String P02 = "P02";
    public static final String P03 = "P03";
    public static final String STATUS_NEW = "NEW";
    public static final String STATUS_DOING = "DOING";
    public static final String STATUS_FINISH = "FINISH";
    public static final String STATUS_CANCEL = "CANCEL";
    public static final String MESSAGE_TYPE_WLZB = "WLZB";

    @Autowired(required = false)
    @Qualifier("defaultJmsTemplate")
    private JmsMessagingTemplate jmsTemplate;
    @Value("${print.server}")
    private String printServer;
    @Autowired
    private MessageTypeUserGroupService messageTypeUserGroupService;
    @Autowired
    private ProdReadyTaskMapper prodReadyTaskMapper;
    @Autowired
    private ResrceService resrceService;
    @Autowired
    private RouterService routerService;
    @Autowired
    private RouterStepService routerStepService;
    @Autowired
    private ProdReadyTaskDetailService prodReadyTaskDetailService;
    @Autowired
    private SfcDispatchCommonService sfcDispatchCommonService;
    @Autowired
    private BomComponentService bomComponentService;
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private WorkCenterMapper workCenterMapper;
    @Autowired
    private CustomFieldsService customFieldsService;
    @Autowired
    private MessageTypeService messageTypeService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private WorkCenterService workCenterService;
    @Autowired
    private PrintLogService printLogService;
    @Autowired
    private ActiveMQUtil activeMQUtil;
    @Autowired
    private MessageService messageService;

    @Autowired
    private NwaUserService nwaUserService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private SfcService sfcService;
    @Autowired
    private CustomFieldsMapper customFieldsMapper;


    @Override
    public IPage<ProdReadyTask> selectPage(FrontPage<ProdReadyTask> frontPage, ProdReadyTask prodReadyTask) {
        QueryWrapper<ProdReadyTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(prodReadyTask);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<ProdReadyTask> selectList(ProdReadyTask prodReadyTask) {
        QueryWrapper<ProdReadyTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(prodReadyTask);
        return super.list(queryWrapper);
    }

    @Override
    public void createTask(List<SfcDispatchDto> sfcDispatchDtoList) {
        //根据站点及派工BO查询数据
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        for (SfcDispatchDto sfcDispatchDto : sfcDispatchDtoList) {
            String sfcDispatchBO = sfcDispatchDto.getHandle();
            String dispatchStatus = sfcDispatchDto.getDispatchStatus();
            String shopOrder = sfcDispatchDto.getShopOrder();
            String sfc = sfcDispatchDto.getSfc();
            String operation = sfcDispatchDto.getOperation();
            String resrce = sfcDispatchDto.getResrce();
            String stepId = sfcDispatchDto.getStepId();
            String workCenter = sfcDispatchDto.getWorkCenter();

            ShopOrder byId = shopOrderService.getById(HandleEnum.SHOP_ORDER.getHandle(site, shopOrder));
            if (DispatchStatusEnum.RELEASE.getCode().equals(dispatchStatus)) {
                ProdReadyTask prodReadyTask = new ProdReadyTask();
                prodReadyTask.setSite(site);
                prodReadyTask.setTaskNo(StringUtil.createQUID());
                prodReadyTask.setHandle(HandleEnum.PROD_READY_TASK.getHandle(site, prodReadyTask.getTaskNo()));
                prodReadyTask.setSfcDispatchBo(sfcDispatchBO);
                prodReadyTask.setShopOrder(shopOrder);
                prodReadyTask.setWorkCenter(workCenter);
                prodReadyTask.setSfc(sfc);
                prodReadyTask.setOperation(operation);
                prodReadyTask.setStepId(stepId);
                prodReadyTask.setItem(StringUtil.trimHandle(byId.getItemBo()));
                prodReadyTask.setResrce(resrce);
                prodReadyTask.setCreateUser(user);
                prodReadyTask.setCreatedDateTime(LocalDateTime.now());
                prodReadyTask.setModifyUser(user);
                prodReadyTask.setModifiedDateTime(LocalDateTime.now());
                List<ProdReadyTaskDetail> prodReadyTaskDetailList = new ArrayList<>();

                String sfcBo = HandleEnum.SFC.getHandle(site, sfc);
                List<BomComponentDto> bomComponentList = bomComponentService.getSfcBomComponent(sfcBo);
                if (!bomComponentList.isEmpty()) {
                    for (BomComponentDto bomComponentDto : bomComponentList) {
                        if (bomComponentDto.getOperation().equals(operation) && bomComponentDto.getStepId().equals(stepId)) {
                            String accessoryType = bomComponentDto.getAccessoryType();
                            //物料P001，校验当前派工单（SFC+工序/步骤）加工是否需要准备物料
                            if (accessoryType == null || accessoryType.equals("0")) {
                                if (prodReadyTaskDetailList.size() > 0) {
                                    long count = prodReadyTaskDetailList.stream().filter(prodReadyTaskDetail -> prodReadyTaskDetail.getInspectionItem().equals(P01)).count();
                                    if (count > 0) {
                                        continue;
                                    }
                                }
                                ProdReadyTaskDetail prodReadyTaskDetail = new ProdReadyTaskDetail();
                                prodReadyTaskDetail.setHandle(HandleEnum.PROD_READY_TASK_DETAIL.getHandle(prodReadyTask.getHandle(), P01));
                                prodReadyTaskDetail.setProdReadyTaskBo(prodReadyTask.getHandle());
                                prodReadyTaskDetail.setInspectionItem(P01);
                                prodReadyTaskDetail.setResult("");
                                prodReadyTaskDetail.setRemarks("");
                                prodReadyTaskDetail.setCreateUser(user);
                                prodReadyTaskDetail.setCreatedDateTime(LocalDateTime.now());
                                prodReadyTaskDetail.setModifyUser(user);
                                prodReadyTaskDetail.setModifiedDateTime(LocalDateTime.now());
                                prodReadyTaskDetailList.add(prodReadyTaskDetail);
                            } else if (accessoryType.equals("1")) {
                                if (prodReadyTaskDetailList.size() > 0) {
                                    long count = prodReadyTaskDetailList.stream().filter(prodReadyTaskDetail -> prodReadyTaskDetail.getInspectionItem().equals(P02)).count();
                                    if (count > 0) {
                                        continue;
                                    }
                                }
                                //刀具P002，校验当前派工单（SFC+工序/步骤）加工是否需要准备物料
                                ProdReadyTaskDetail prodReadyTaskDetail = new ProdReadyTaskDetail();
                                prodReadyTaskDetail.setHandle(HandleEnum.PROD_READY_TASK_DETAIL.getHandle(prodReadyTask.getHandle(), P02));
                                prodReadyTaskDetail.setProdReadyTaskBo(prodReadyTask.getHandle());
                                prodReadyTaskDetail.setInspectionItem(P02);
                                prodReadyTaskDetail.setResult("");
                                prodReadyTaskDetail.setRemarks("");
                                prodReadyTaskDetail.setCreateUser(user);
                                prodReadyTaskDetail.setCreatedDateTime(LocalDateTime.now());
                                prodReadyTaskDetail.setModifyUser(user);
                                prodReadyTaskDetail.setModifiedDateTime(LocalDateTime.now());
                                prodReadyTaskDetailList.add(prodReadyTaskDetail);
                            }
                        }
                    }
                }
                //工控程序P003，工控程序，校验是否需要准备工控程序
                String customFieldsValue = customFieldsService.getCustomFieldsValue(HandleEnum.WORK_CENTER.getHandle(site, workCenter), CustomFieldConstant.WORK_CENTER_CUSTOM_FIELD_PROCESS_CONTROL);
                if (StringUtil.notBlank(customFieldsValue) && customFieldsValue.equals(Constants.STATUS_Y)) {
                    customFieldsValue = customFieldsService.getCustomFieldsValue(HandleEnum.RESOURCE.getHandle(site, resrce), CustomFieldConstant.RESRCE_CUSTOM_FIELD_PROCESS_CONTROL);
                    if (StringUtil.notBlank(customFieldsValue) && customFieldsValue.equals(Constants.STATUS_Y)) {
                        ProdReadyTaskDetail prodReadyTaskDetail = new ProdReadyTaskDetail();
                        prodReadyTaskDetail.setHandle(HandleEnum.PROD_READY_TASK_DETAIL.getHandle(prodReadyTask.getHandle(), P03));
                        prodReadyTaskDetail.setProdReadyTaskBo(prodReadyTask.getHandle());
                        prodReadyTaskDetail.setInspectionItem(P03);
                        prodReadyTaskDetail.setResult("");
                        prodReadyTaskDetail.setRemarks("");
                        prodReadyTaskDetail.setCreateUser(user);
                        prodReadyTaskDetail.setCreatedDateTime(LocalDateTime.now());
                        prodReadyTaskDetail.setModifyUser(user);
                        prodReadyTaskDetail.setModifiedDateTime(LocalDateTime.now());
                        prodReadyTaskDetailList.add(prodReadyTaskDetail);
                    }
                }
                if (prodReadyTaskDetailList.size() > 0) {
                    prodReadyTask.setStatus(STATUS_NEW);
                    prodReadyTaskDetailService.saveBatch(prodReadyTaskDetailList);
                } else {
                    prodReadyTask.setStatus(STATUS_FINISH);
                    prodReadyTask.setResult(Constants.RSESULT_OK);
                    prodReadyTask.setCompleteUser(user);
                    prodReadyTask.setCompleteDateTime(LocalDateTime.now());
                }
                save(prodReadyTask);
            } else if (DispatchStatusEnum.CANCEL.getCode().equals(dispatchStatus)) {
                LambdaQueryWrapper<ProdReadyTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(ProdReadyTask::getSfcDispatchBo, sfcDispatchBO);
                lambdaQueryWrapper.orderByDesc(ProdReadyTask::getCreatedDateTime);
                List<ProdReadyTask> list = list(lambdaQueryWrapper);
                if (list.size() > 0) {
                    ProdReadyTask prodReadyTask = list.get(0);
                    if (prodReadyTask.getStatus().equals(STATUS_CANCEL)) {
                       continue;
                    }
                    prodReadyTask.setStatus(STATUS_CANCEL);
                    LocalDateTime now = LocalDateTime.now();
                    prodReadyTask.setCancelDateTime(now);
                    prodReadyTask.setModifiedDateTime(now);
                    prodReadyTask.setCancelUser(user);
                    prodReadyTask.setModifyUser(user);
                    updateById(prodReadyTask);
                }
            }
        }
    }

    @Override
    public List<ProdReadyTask> getTaskList(ProdReadyTask prodReadyTask) {
        String user = CommonMethods.getUser();
        String site = CommonMethods.getSite();
        Integer admin = userGroupMapper.getUserGroupByUser(HandleEnum.USER.getHandle(site, user), new UserGroupBOHandle(site, "ADMINISTRATORS").getValue());
        return prodReadyTaskMapper.getTaskList(prodReadyTask, LocaleContextHolder.getLocale().getLanguage(), admin, user);
    }

    @Override
    public ProdReadyTask loadProExecute(String taskBo) {
        ProdReadyTask prodReadyTask = prodReadyTaskMapper.selectById(taskBo);
        if (prodReadyTask.getStatus().equals(STATUS_NEW)) {
            prodReadyTask.setReadyUser(CommonMethods.getUser());
            prodReadyTask.setReadyDateTime(LocalDateTime.now());
            prodReadyTask.setModifyUser(CommonMethods.getUser());
            prodReadyTask.setModifiedDateTime(LocalDateTime.now());
            prodReadyTask.setStatus(STATUS_DOING);
            updateById(prodReadyTask);
        }
        WorkCenter workCenter = new WorkCenter();
        workCenter.setWorkCenter(prodReadyTask.getWorkCenter());
        workCenter.setSite(CommonMethods.getSite());
        List<WorkCenter> workCenters = workCenterService.selectList(workCenter);
        prodReadyTask.setWorkCenterDesc(workCenters.get(0).getDescription());
        prodReadyTask.setDispatchNo(StringUtil.trimHandle(prodReadyTask.getSfcDispatchBo()));
        LambdaQueryWrapper<ProdReadyTaskDetail> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(ProdReadyTaskDetail::getProdReadyTaskBo, taskBo);
        List<ProdReadyTaskDetail> list = prodReadyTaskDetailService.list(lambdaQuery);
        prodReadyTask.setProdReadyTaskDetailList(list);
        return prodReadyTask;
    }

    @Override
    public Map<String, Object> loadTaskExecute(String taskBo) {
        Map<String, Object> returnMap=new HashMap<>();
        ProdReadyTask prodReadyTask = prodReadyTaskMapper.selectById(taskBo);
        String dispatchNo = StringUtil.trimHandle(prodReadyTask.getSfcDispatchBo());
        String site = CommonMethods.getSite();
        if (prodReadyTask.getStatus().equals(STATUS_NEW)) {
            prodReadyTask.setReadyUser(CommonMethods.getUser());
            prodReadyTask.setReadyDateTime(LocalDateTime.now());
            prodReadyTask.setModifyUser(CommonMethods.getUser());
            prodReadyTask.setModifiedDateTime(LocalDateTime.now());
            prodReadyTask.setStatus(STATUS_DOING);
            updateById(prodReadyTask);
        }
        LambdaQueryWrapper<ProdReadyTaskDetail> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(ProdReadyTaskDetail::getProdReadyTaskBo, taskBo);
        List<ProdReadyTaskDetail> list = prodReadyTaskDetailService.list(lambdaQuery);
        List<Map<String, Object>> itemList = null;
        List<Map<String, Object>> toolList = null;
        List<Map<String, Object>> processControolList = null;
        //物料接收数据
        if (list.stream().filter(prodReadyTaskDetail -> prodReadyTaskDetail.getInspectionItem().equals(P01)).count()>0){
            itemList = prodReadyTaskMapper.getItemDetail(site, LocaleContextHolder.getLocale().getLanguage(), dispatchNo);
        }
        //刀具
        if (list.stream().filter(prodReadyTaskDetail -> prodReadyTaskDetail.getInspectionItem().equals(P02)).count()>0){
            toolList  = prodReadyTaskMapper.getToolDetail(site, LocaleContextHolder.getLocale().getLanguage(), dispatchNo);
        }
        //通过加工的零件号、设备类型、设备获取发布状态的工控程序
        if (list.stream().filter(prodReadyTaskDetail -> prodReadyTaskDetail.getInspectionItem().equals(P03)).count()>0){
            processControolList= new ArrayList<>();
            SfcDispatchDto sfcdispatch = new SfcDispatchDto();
            sfcdispatch.setHandle(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
            sfcdispatch = sfcDispatchCommonService.findSfcDispatchBySfc(sfcdispatch);
            Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfcdispatch.getSfc()));
            String itemBo = sfcServiceById.getItemBo();
            JSONObject jsonObject = sendToDnc(StringUtil.trimHandle(itemBo), sfcdispatch.getResrce(), sfcdispatch.getResourceType());
            Map<String, Object> map = new HashMap<>();
            map.put("RESOURCE", sfcdispatch.getResrce());
            map.put("RESOURCE_TYPE", sfcdispatch.getResourceType());
            map.put("RESULT", jsonObject.get("RESULT"));
            map.put("MESSAGE", jsonObject.get("MESSAGE"));
            processControolList.add(map);
        }
        returnMap.put("itemList",itemList);
        returnMap.put("cutterList",toolList);
        returnMap.put("processControlList",processControolList);
        return returnMap;
    }

    @Override
    public void savePdaResult(ProdReadyTask prodReadyTask) {
        String user = CommonMethods.getUser();
        ProdReadyTask byId = getById(prodReadyTask.getHandle());
        if (byId.getStatus().equals(STATUS_CANCEL)) {
            throw new BaseException("产前准备任务已取消");
        }
        if (byId.getStatus().equals(STATUS_FINISH) && byId.getResult().equals(Constants.RSESULT_OK)) {
            throw new BaseException("产前准备任务已完成");
        }
        List<ProdReadyTaskDetail> prodReadyTaskDetailList = prodReadyTask.getProdReadyTaskDetailList();
        prodReadyTask.setStatus(STATUS_FINISH);
        prodReadyTask.setCompleteUser(user);
        prodReadyTask.setCompleteDateTime(LocalDateTime.now());
        prodReadyTask.setModifyUser(user);
        prodReadyTask.setModifiedDateTime(LocalDateTime.now());
        updateById(prodReadyTask);
        if (prodReadyTaskDetailList != null && prodReadyTaskDetailList.size() > 0) {
            for (ProdReadyTaskDetail prodReadyTaskDetail : prodReadyTaskDetailList) {
                String detailHandle = HandleEnum.PROD_READY_TASK_DETAIL.getHandle(prodReadyTask.getHandle(), prodReadyTaskDetail.getInspectionItem());
                prodReadyTaskDetail.setHandle(detailHandle);
                prodReadyTaskDetail.setModifyUser(user);
                prodReadyTaskDetail.setModifiedDateTime(LocalDateTime.now());
                prodReadyTaskDetailService.updateById(prodReadyTaskDetail);
            }
        }
    }

    @Override
    public List<Map<String, Object>> getInspectionDetailList(Map<String, String> param) {
        String type = param.get("type");
        String dispatchNo = param.get("dispatchNo");
        List<Map<String, Object>> returnMap = new ArrayList<>();
        String site = CommonMethods.getSite();
        if (type.equals(P01)) {
            //物料接收数据
            returnMap = prodReadyTaskMapper.getItemDetail(site, LocaleContextHolder.getLocale().getLanguage(), dispatchNo);
        } else if (type.equals(P02)) {
            //刀具
            returnMap = prodReadyTaskMapper.getToolDetail(site, LocaleContextHolder.getLocale().getLanguage(), dispatchNo);
        } else {
            //通过加工的零件号、设备类型、设备获取发布状态的工控程序
            SfcDispatchDto sfcdispatch = new SfcDispatchDto();
            sfcdispatch.setHandle(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
            sfcdispatch = sfcDispatchCommonService.findSfcDispatchBySfc(sfcdispatch);
            Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfcdispatch.getSfc()));
            String itemBo = sfcServiceById.getItemBo();
            JSONObject jsonObject = sendToDnc(StringUtil.trimHandle(itemBo), sfcdispatch.getResrce(), sfcdispatch.getResourceType());
            Map<String, Object> map = new HashMap<>();
            map.put("RESOURCE", sfcdispatch.getResrce());
            map.put("RESOURCE_TYPE", sfcdispatch.getResourceType());
            map.put("RESULT", jsonObject.get("RESULT"));
            map.put("MESSAGE", jsonObject.get("MESSAGE"));
            returnMap.add(map);
        }
        return returnMap;
    }

    @Override
    public boolean saveResult(ProdReadyTask prodReadyTask) {
        String user = CommonMethods.getUser();
        ProdReadyTask byId = getById(prodReadyTask.getHandle());
        if (byId.getStatus().equals(STATUS_CANCEL)) {
            throw new BaseException("产前准备任务已取消");
        }
        if (byId.getStatus().equals(STATUS_FINISH) && byId.getResult().equals(Constants.RSESULT_OK)) {
            throw new BaseException("产前准备任务已完成");
        }
        List<ProdReadyTaskDetail> prodReadyTaskDetailList = prodReadyTask.getProdReadyTaskDetailList();
        prodReadyTask.setStatus(STATUS_FINISH);
        prodReadyTask.setCompleteUser(user);
        prodReadyTask.setCompleteDateTime(LocalDateTime.now());
        prodReadyTask.setModifyUser(user);
        prodReadyTask.setModifiedDateTime(LocalDateTime.now());
        boolean update = updateById(prodReadyTask);
        if (prodReadyTaskDetailList != null && prodReadyTaskDetailList.size() > 0) {
            for (ProdReadyTaskDetail prodReadyTaskDetail : prodReadyTaskDetailList) {
                prodReadyTaskDetail.setModifyUser(user);
                prodReadyTaskDetail.setModifiedDateTime(LocalDateTime.now());
                prodReadyTaskDetailService.updateById(prodReadyTaskDetail);
            }
        }
        return update;
    }

    @Override
    public void doPrint(ProdReadyTask prodReadyTask ,String printerName) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String sfcDispatchBo = prodReadyTask.getSfcDispatchBo();
        SfcDispatchDto sfcDispatchDto = new SfcDispatchDto();
        sfcDispatchDto.setHandle(sfcDispatchBo);
        sfcDispatchDto = sfcDispatchCommonService.findSfcDispatchBySfc(sfcDispatchDto);
        List<PrintLog> printList = new ArrayList<>();
        List<LabelPrintDto> labelPrintDtoList = new ArrayList<>();
        String printData = null;
        PrintLog printTag = new PrintLog();

        String resrce = sfcDispatchDto.getResrce();
        String shopOrder = sfcDispatchDto.getShopOrder();
        String factory = customFieldsService.getCustomFieldsValue(HandleEnum.SHOP_ORDER.getHandle(site, shopOrder), CustomFieldConstant.SO_FACTORY);
        String printName = customFieldsService.getCustomFieldsValue(HandleEnum.RESOURCE.getHandle(site, resrce), CustomFieldConstant.RESRCE_CUSTOM_FIELD_PRINT_NAME);
        String type=Constants.PRINT_TYPE_SFC;
        if (StringUtil.notBlank(factory)&&factory.equals("6100")){
            type=Constants.PRINT_TYPE_PRODUCT;
        }
        if (printerName == null && StringUtil.isBlank(printName)) {
            throw new BaseException("资源" + resrce + "维护的打印机不能为空");
        }
        String item = prodReadyTask.getItem();
        Item selectCurrent = itemService.selectCurrent(site, item);
        QueryWrapper<PrintLog> queryWrapper = new QueryWrapper();
        queryWrapper.eq(PrintLog.SFC, prodReadyTask.getSfc());
        queryWrapper.eq(PrintLog.STEP_ID, prodReadyTask.getStepId());
        queryWrapper.eq(PrintLog.RESRCE, prodReadyTask.getResrce());
        queryWrapper.eq(PrintLog.CATEGORY, type);
        queryWrapper.eq(PrintLog.PRINT_TEMPLATE, type);
        List<PrintLog> printLogList = printLogService.list(queryWrapper);
        if (printLogList.isEmpty() || !printLogList.isEmpty()) {
            //打印参数
            LabelPrintDto labelPrintDto = new LabelPrintDto();
            labelPrintDto.setPrinter(printerName == null ? printName : printerName);
            labelPrintDto.setPrintTemplate(type);
            labelPrintDto.setShopOrder(shopOrder);
            labelPrintDto.setItem(selectCurrent.getItem());
            labelPrintDto.setPrintNum(1);
            labelPrintDto.setItemDescription(selectCurrent.getDescription());
            labelPrintDto.setSfc(prodReadyTask.getSfc());
            Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, prodReadyTask.getSfc()));
            String drawingRevision = customFieldsService.getCustomFieldsValue(sfcServiceById.getItemBo(), CustomFieldConstant.ITEM_DWG_NO);
            labelPrintDto.setDrawingVersion(drawingRevision);
            labelPrintDto.setQty(new BigDecimal(sfcServiceById.getQty()));
            String workOrder = customFieldsService.getCustomFieldsValue(sfcServiceById.getShopOrderBo(), CustomFieldConstant.SO_WORK_ORDER);
            String itemNumber = customFieldsService.getCustomFieldsValue(sfcServiceById.getShopOrderBo(), CustomFieldConstant.SO_ITEM_NUMBER);
            labelPrintDto.setItemNumber(itemNumber);
            labelPrintDto.setWorkOrder(workOrder);
            labelPrintDto.setBlankingSize(sfcDispatchDto.getBlankingSize());
            // 是否主观件 :辅料类型是9，则为主观件
            String accessory_type = customFieldsMapper.selectCustomFieldsValue(selectCurrent.getHandle(), "ACCESSORY_TYPE");
            if (StringUtil.notBlank(accessory_type)&&"9".equals(accessory_type)){
                labelPrintDto.setMainPart(true);
            }else{
                labelPrintDto.setMainPart(false);
            }
            //下道工序
            Router router = routerService.getRouterBySfcBo(HandleEnum.SFC.getHandle(site, sfcServiceById.getSfc()));
            if (router==null){
                throw new BaseException("未找到当前工序");
            }
            List<RouterStepDto> stepOperationList = routerStepService.findRouterOperationByRouterBo(site, router.getHandle());
            StringBuilder operationDesc = new StringBuilder();
            for (int i = 0; i < stepOperationList.size(); i++) {
                RouterStepDto stepOperation = stepOperationList.get(i);
                operationDesc.append(stepOperation.getOperationDesc()) ;
                if (i!=stepOperationList.size()-1){
                    operationDesc.append(",");
                }
            }
            labelPrintDto.setOperation(operationDesc.toString());

            //打印物料去向
            labelPrintDto.setItemTypeOrder(sfcDispatchDto.getOther2());
            labelPrintDtoList.add(labelPrintDto);
            printData = JSON.toJSONString(labelPrintDtoList);
            //打印记录
            printTag.setHandle(UUID.randomUUID().toString());
            printTag.setPrintName(printName);
            printTag.setPrintTemplate(type);
            printTag.setSite(site);
            printTag.setCategory(type);
            printTag.setPrintParam(JSON.toJSONString(labelPrintDtoList));
            printTag.setSfc(prodReadyTask.getSfc());
            printTag.setResrce(prodReadyTask.getResrce());
            printTag.setStepId(prodReadyTask.getStepId());
            printTag.setOperation(prodReadyTask.getOperation());
            printTag.setItemBo(selectCurrent.getHandle());
            printTag.setIsPrint("false");
            printTag.setPrintNum(1);
            printTag.setItem(item);
            printTag.setItemDescription(selectCurrent.getDescription());

            printList.add(printTag);
            printLogService.savePrintLog(site, user, printTag);

        } else {
            printData = printLogList.get(0).getPrintParam();
        }
        String post = HttpUtil.post(printServer, printData, 30000);
        /**
         * {"msg":"打印成功","code":0}
         * {"msg":"打印失败","code":500}
         * 根据返回值，更新打印机信息-printName及打印是否成功信息isPrint
         */
        JSONObject jsonObject = JSONObject.parseObject(post);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        if (code != 0){
            throw BusinessException.build(msg);
        }
        if (printLogList.isEmpty()) {
            printTag.setIsPrint("true");
            printTag.setPrintNum(1);
            printLogService.updateById(printTag);
        } else {
            PrintLog printLog = printLogList.get(0);
            printTag.setIsPrint("true");
            printTag.setPrintNum(printLog.getPrintNum() + 1);
            printTag.setModifiedDateTime(LocalDateTime.now());
            printTag.setModifyUser(user);
            printLogService.updateById(printLog);
        }

    }

    @Override
    public void sendMsgJob(String site) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endTime = now.plusMinutes(30);
        //查找当前派工单的计划开始时间30分钟内的未准备完成的任务
        List<ProdReadyTask> prodReadyTasks = prodReadyTaskMapper.getUnreadyTasks(site, now, endTime);
        for (ProdReadyTask prodReadyTask : prodReadyTasks) {
            QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
            messageQueryWrapper.eq(Message.OBJECT_BO, prodReadyTask.getHandle());
            List<Message> list = messageService.list(messageQueryWrapper);
            if (!list.isEmpty()) {
                continue;
            }
            LambdaQueryWrapper<ProdReadyTaskDetail> lambdaQuery = new LambdaQueryWrapper<>();
            lambdaQuery.eq(ProdReadyTaskDetail::getProdReadyTaskBo, prodReadyTask.getHandle());
            List<ProdReadyTaskDetail> readyTaskDetails = prodReadyTaskDetailService.list(lambdaQuery);
            for (ProdReadyTaskDetail prodReadyTaskDetail : readyTaskDetails) {
                if (prodReadyTaskDetail.getInspectionItem().equals(P01)) {
                    Message message = new Message();
                    String uuid = UUID.randomUUID().toString();
                    message.setHandle(uuid);
                    message.setSite(site);
                    message.setObjectBo(prodReadyTask.getHandle());
                    message.setType("C");
                    message.setMessageType(MESSAGE_TYPE_WLZB);
                    //查询消息类型关联的用户组
                    String workCenter = prodReadyTask.getWorkCenter();
                    String userGroup = workCenter + "-" + MESSAGE_TYPE_WLZB;

                    QueryWrapper<MessageTypeUserGroup> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(MessageTypeUserGroup.MESSAGE_TYPE_BO, new MessageTypeBOHandle(site, MESSAGE_TYPE_WLZB).getValue());
                    queryWrapper.eq(MessageTypeUserGroup.USER_GROUP_BO, new UserGroupBOHandle(site, userGroup).getValue());
                    List<MessageTypeUserGroup> messageTypeUserGroupList = messageTypeUserGroupService.list(queryWrapper);
                    if (messageTypeUserGroupList.isEmpty()) {
                        continue;
                    }
                    message.setSendUserGroup(userGroup);
                    message.setSendUser("JOB");
                    String sendMessage = this.formatMessage(prodReadyTask, MESSAGE_TYPE_WLZB, site);
                    message.setContent(sendMessage);
                    message.setUpUserGroup(null);
                    message.setUpUser(null);
                    message.setUpMessageType(null);
                    message.setUpDateTime(null);
                    message.setGrade(null);
                    message.setResponseDateTime(null);
                    message.setNode(null);
                    message.setStatus(Constants.STATUS_Y);
                    message.setCreatedUser("JOB");
                    message.setCreatedDateTime(LocalDateTime.now());
                    message.setModifiedUser("JOB");
                    message.setModifiedDateTime(LocalDateTime.now());
                    List<NwaUser> nwaUsers = nwaUserService.checkUserGroup(site, userGroup);
                    StringBuilder sendUsers = new StringBuilder();
                    for (int i = 0; i < nwaUsers.size(); i++) {
                        if (i == (nwaUsers.size() - 1)) {
                            sendUsers.append(nwaUsers.get(i));
                        } else {
                            sendUsers.append(nwaUsers.get(i)).append("|");
                        }
                    }
                    messageService.save(message);
                    activeMQUtil.wechatSendMessage(sendUsers.toString(), sendMessage);
                }
            }
        }

    }

    @Override
    public void doReadyList(List<ProdReadyTask> list) {
        String user = CommonMethods.getUser();
        for (ProdReadyTask prodReadyTask : list) {
            prodReadyTask = getById(prodReadyTask.getHandle());
            String result = prodReadyTask.getResult();
            if (prodReadyTask.getStatus().equals(STATUS_CANCEL)) {
                throw new BaseException("产品条码" + prodReadyTask.getSfc() + "产前准备任务已取消");
            }
            if (StringUtil.notBlank(result) && prodReadyTask.getResult().equals(Constants.RSESULT_OK)) {
                throw new BaseException("产品条码" + prodReadyTask.getSfc() + "产前准备任务已完成");
            }
            prodReadyTask.setStatus(STATUS_FINISH);
            prodReadyTask.setResult(Constants.RSESULT_OK);
            prodReadyTask.setCompleteUser(user);
            prodReadyTask.setCompleteDateTime(LocalDateTime.now());
            prodReadyTask.setModifyUser(user);
            prodReadyTask.setModifiedDateTime(LocalDateTime.now());
            updateById(prodReadyTask);
        }
    }


    public String formatMessage(ProdReadyTask prodReadyTask, String messageType, String site) {
        //找到消息内容
        String locale = LocaleContextHolder.getLocale().getLanguage();
        MessageType messageTypeEntity = new MessageType();
        messageTypeEntity.setSite(site);
        messageTypeEntity.setMessageType(messageType);
        QueryWrapper<MessageType> messageTypeQueryWrapper = new QueryWrapper<MessageType>();
        messageTypeQueryWrapper.setEntity(messageTypeEntity);
        MessageType sendMessageType = messageTypeService.getOne(messageTypeQueryWrapper);
        if (sendMessageType == null) {
            throw new BaseException("异常提报时找不到要发送的消息类型");
        }
        //格式化消息
        String body = sendMessageType.getBody();
        //替换消息类型中的参数
        Map<String, String> messageMap = new HashMap<>();
        //根据车间找到对应车间的描述
        WorkCenter workCenter = workCenterMapper.findWorkCenterDescriptionByWorkCenter(site, prodReadyTask.getWorkCenter(), locale);
        //根据资源找到对应的产线的描述
        Resrce byResrce = resrceService.getById(HandleEnum.RESOURCE.getHandle(site, prodReadyTask.getResrce()));
        Item selectCurrent = itemService.selectCurrent(site, prodReadyTask.getItem());
        //项目号
        String item = selectCurrent.getItem() + "/" + selectCurrent.getDescription();
        messageMap.put("WORKCENTER", workCenter.getDescription());
        messageMap.put("RESOURCE", byResrce.getResrce() + "/" + byResrce.getDescription());
        messageMap.put("ITEM", item);
        messageMap.put("SHOPORDER", prodReadyTask.getShopOrder());
        messageMap.put("SFC", prodReadyTask.getSfc());

        //格式化之后的消息
        return StringUtils.format(body, messageMap);
    }

    public JSONObject sendToDnc(String item, String resource, String resourceType) {
        String site = CommonMethods.getSite();
        String queue = "resource.check.process";
        JSONObject messageObject = new JSONObject();
        String tranid = UUID.randomUUID().toString();
        messageObject.put("TRANID", tranid);
        String dateTime = DateUtil.formatDate(new Date());
        messageObject.put("DATE_TIME", dateTime);
        messageObject.put("SITE", site);
        messageObject.put("MESSAGE_ID", queue);
        messageObject.put("ITEM", item);
        messageObject.put("RESOURCE", resource);
        messageObject.put("RESOURCE_TYPE", resourceType);
        String causeMessage = null;
        String message = jmsTemplate.convertSendAndReceive(queue, messageObject.toString(), String.class);

        if (StringUtil.isBlank(message)) {
            causeMessage = "队列消息消费超时或者未返回消费数据";
        } else {

            JSONObject jsonNode = JSONObject.parseObject(message);
            String result = jsonNode.getString("STATUS");
            if ("S".equalsIgnoreCase(result)) {
                return jsonNode;
            } else {
                causeMessage = jsonNode.getString("MESSAGE");
            }

        }
        JSONObject messageFailObject = new JSONObject();
        messageFailObject.put("TRANID", tranid);
        messageFailObject.put("RESULT", "E");
        messageFailObject.put("MESSAGE", causeMessage);
        return messageFailObject;
    }


}