admin
2024-08-28 c2e92c3bd4fc134b27ba6a6271f63b032b2b9d99
jcdm-main/src/main/java/com/jcdm/main/restful/qingYan/service/ExternalInterface.java
@@ -1,41 +1,61 @@
package com.jcdm.main.restful.qingYan.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.jcdm.common.core.domain.AjaxResult;
import com.jcdm.common.utils.StringUtils;
import com.jcdm.framework.websocket.WebSocketUsers;
import com.jcdm.main.bs.beatSetting.domain.BsBeatSetting;
import com.jcdm.main.bs.beatSetting.service.IBsBeatSettingService;
import com.jcdm.main.bs.formulaChild.domain.BsFormulaChildInfo;
import com.jcdm.main.bs.formulaChild.service.IBsFormulaChildInfoService;
import com.jcdm.main.constant.Constants;
import com.jcdm.main.da.paramCollection.domain.DaParamCollection;
import com.jcdm.main.da.paramCollection.service.IDaParamCollectionService;
import com.jcdm.main.da.passingStationCollection.domain.DaPassingStationCollection;
import com.jcdm.main.da.passingStationCollection.service.IDaPassingStationCollectionService;
import com.jcdm.main.da.testDeviceInterface.domain.DaTestDeviceInterface;
import com.jcdm.main.da.testDeviceInterface.service.IDaTestDeviceInterfaceService;
import com.jcdm.main.om.productionOrde.domain.OmProductionOrdeInfo;
import com.jcdm.main.om.productionOrde.service.IOmProductionOrdeInfoService;
import com.jcdm.main.restful.qingYan.doman.ChildVO;
import com.jcdm.main.restful.qingYan.doman.ParentVO;
import com.jcdm.main.restful.qingYan.doman.PostEntity;
import com.jcdm.main.restful.factoryMes.service.RestfulService;
import com.jcdm.main.restful.qingYan.doman.*;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.websocket.Session;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/jcdmMes")
public class ExternalInterface {
    Map<String, Session> map = WebSocketUsers.getUsers();
    private static final Logger logger = LoggerFactory.getLogger("sys-user");
    public SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private IDaTestDeviceInterfaceService daTestDeviceInterfaceService;
    @Autowired
    private IDaParamCollectionService daParamCollectionService;
@@ -45,164 +65,148 @@
    @Autowired
    private IOmProductionOrdeInfoService productionOrdeInfoService;
    String url = "https://imes-uat-group.geelycv-test.com/api/mom-open/restful/aMesSysIntegration/deviceResultFeedback";
    @Autowired
    private IOmProductionOrdeInfoService omProductionOrdeInfoService;
    @Autowired
    private IBsFormulaChildInfoService bsFormulaChildInfoService;
    @Autowired
    private IBsBeatSettingService bsBeatSettingService;
    private IDaPassingStationCollectionService passingStationCollectionService;
//    String url = "https://imes-uat-group.geelycv-test.com/api/mom-open/restful/aMesSysIntegration/deviceResultFeedback";
    String url = "https://imes-group.geelycv.com/api/mom-open/restful/aMesSysIntegration/deviceResultFeedback";
    /**
     * 导出点检任务列表
     */
    @PostMapping("/deviceResultFeedback")
    public AjaxResult hdy(@RequestBody ParentVO parentVO)
    public AjaxResult deviceResultFeedback(@RequestBody ParentVO parentVO)
    {
        //保存
        //过站记录
        String productNum = parentVO.getProductNum();
        if (StrUtil.isNotBlank(productNum)){
            List<OmProductionOrdeInfo> list = productionOrdeInfoService.list(new LambdaQueryWrapper<OmProductionOrdeInfo>().eq(OmProductionOrdeInfo::getProductNum, productNum));
            if (CollUtil.isNotEmpty(list)){
                OmProductionOrdeInfo omProductionOrdeInfo = list.get(0);
                DaPassingStationCollection passingStationCollection = new DaPassingStationCollection();
                passingStationCollection.setWorkOrderNo(omProductionOrdeInfo.getWorkOrderNo());
                passingStationCollection.setSfcCode(productNum);
                passingStationCollection.setProductCode(omProductionOrdeInfo.getProductCode());
                passingStationCollection.setLocationCode(parentVO.getStationCode());
                passingStationCollection.setOutRsSign(parentVO.getTotalResult());
                passingStationCollection.setCreateTime(new Date());
                List<ChildVO> checkList = parentVO.getCheckList();
                if (CollUtil.isNotEmpty(checkList)){
                    List<String> collect = checkList.stream()
                            .filter(x -> Constants.IN_BOUND_TIME_CODE.equals(x.getItemCode()))
                            .map(ChildVO::getItemValue)
                            .collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)){
                        String s = collect.get(0);
                        if (StrUtil.isNotBlank(s)){
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                Date parse = simpleDateFormat.parse(s);
                                passingStationCollection.setInboundTime(parse);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                    List<String> collect2 = checkList.stream()
                            .filter(x -> Constants.OUT_BOUND_TIME_CODE.equals(x.getItemCode()))
                            .map(ChildVO::getItemValue)
                            .collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect2)){
                        String s = collect2.get(0);
                        if (StrUtil.isNotBlank(s)){
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                Date parse = simpleDateFormat.parse(s);
                                passingStationCollection.setOutboundTime(parse);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                    daPassingStationCollectionService.save(passingStationCollection);
                    //参数保存
                    List<DaParamCollection> paramCollectionList = new ArrayList<>();
                    for (ChildVO childVO : checkList) {
                        DaParamCollection daParamCollection = new DaParamCollection();
                        daParamCollection.setWorkOrderNo(omProductionOrdeInfo.getWorkOrderNo());
                        daParamCollection.setSfcCode(productNum);
                        daParamCollection.setProductCode(omProductionOrdeInfo.getProductCode());
                        daParamCollection.setLocationCode(omProductionOrdeInfo.getStationCode());
                        daParamCollection.setParamCode(childVO.getItemCode());
                        daParamCollection.setParamValue(childVO.getItemValue());
                        daParamCollection.setCollectionTime(new Date());
                        daParamCollection.setParamName(childVO.getItemText());
                        paramCollectionList.add(daParamCollection);
                    }
                    if (CollUtil.isNotEmpty(paramCollectionList)){
                        daParamCollectionService.insertBatch(paramCollectionList);
                    }
                }
            }
        ObjectMapper mapper = new ObjectMapper();
        List<ChildVO> li = parentVO.getCheckList();
        String s = null;
        try {
            s = mapper.writeValueAsString(li);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DaTestDeviceInterface daTestDeviceInterface = new DaTestDeviceInterface();
        daTestDeviceInterface.setRecordId(parentVO.getRecordId());
        daTestDeviceInterface.setStationCode(parentVO.getStationCode());
        daTestDeviceInterface.setProductNum(parentVO.getProductNum());
        daTestDeviceInterface.setTotalResult(parentVO.getTotalResult());
        daTestDeviceInterface.setCheckList(s);
        daTestDeviceInterface.setCreateTime(new Date());
        daTestDeviceInterfaceService.save(daTestDeviceInterface);
//        if(parentVO.getStationCode().contains("POP410")){
//            if(StringUtils.isNotBlank(parentVO.getProductNum())){
//                OmProductionOrdeInfo one = omProductionOrdeInfoService.getOne(new LambdaQueryWrapper<OmProductionOrdeInfo>().eq(OmProductionOrdeInfo::getProductNum, parentVO.getProductNum()));
//                if(ObjectUtil.isNotNull(one)){
//                    logger.info("解绑小车{},pack码是{}"+one.getTrolleyYard(),one.getProductNum());
//                    one.setTrolleyYard("");
//                    omProductionOrdeInfoService.saveOrUpdate(one);
//                }
//            }
//        }
//        try{
//            CompletableFuture<Void> cp1 = CompletableFuture.runAsync(() -> {
//                logger.info("开始执行异步方法");
//                HttpResponse execute = HttpRequest.post(url).body(JSONUtil.toJsonStr(parentVO)).execute();
//                logger.info("异步方法执行结束");
//                logger.info("接收清研,气密异步方法{}"+execute.body());
//            });
//        }catch (Exception e){
//            System.out.println(e.getMessage());
//        }
        logger.info("收到工位{}的测试设备数据入参VO{}" + parentVO.getStationCode(),new Gson().toJson(parentVO));
        HttpResponse execute = HttpRequest.post(url).body(JSONUtil.toJsonStr(parentVO)).execute();
        logger.info("工厂MES返回报文{}-工位{}" + execute.body(),parentVO.getStationCode());
        return AjaxResult.success(execute.body());
    }
    @PostMapping("/pushParamData")
    public void receivingData(@RequestBody PostEntity postEntity) throws JsonProcessingException {
//        ObjectMapper objectMapper = new ObjectMapper();
//        PostEntity person = objectMapper.readValue(postEntity, PostEntity.class);
        Class<?> entityClass = PostEntity.class; // 替换为你的实体类
        String packId = postEntity.getPEOL_PackID();
        OmProductionOrdeInfo one = productionOrdeInfoService.getOne(new LambdaQueryWrapper<OmProductionOrdeInfo>().eq(OmProductionOrdeInfo::getProductNum, packId));
        String productType = "type";
        String workOrderNo = one.getWorkOrderNo();
        for (Field field : entityClass.getDeclaredFields()) {
            String fieldName = field.getName();
            DaParamCollection daParamCollection = new DaParamCollection();
            daParamCollection.setWorkOrderNo(workOrderNo);
            daParamCollection.setProductCode(productType);
            daParamCollection.setSfcCode(packId);
            daParamCollection.setParamCode(field.getName());
            daParamCollection.setParamValue((String) getFieldValue(postEntity, fieldName));
            if(fieldName.contains("GDBH")){
                daParamCollection.setParamValue(workOrderNo);
            }
            if(fieldName.contains("CPXH")){
                daParamCollection.setParamValue(productType);
            }
            daParamCollectionService.save(daParamCollection);
        }
    @GetMapping("/productionWorkOrderRequest")
    public AjaxResult productionWorkOrderRequest(){
        List<RestFulOrder> restFulOrders = new ArrayList<>();
//        try{
//            CompletableFuture<Void> cp1 = CompletableFuture.runAsync(() -> {
//                List<OmProductionOrdeInfo> list = omProductionOrdeInfoService.list();
//                for (OmProductionOrdeInfo omProductionOrdeInfo : list) {
//                    RestFulOrder order = new RestFulOrder();
//                    order.setProductionOrderNum(omProductionOrdeInfo.getWorkOrderNo());
//                    order.setProductNum(omProductionOrdeInfo.getProductNum());
//                    order.setMaterialCode(omProductionOrdeInfo.getMaterialCode());
//                    order.setStationCode(omProductionOrdeInfo.getStationCode());
//                    order.setPlanQty(omProductionOrdeInfo.getPlanQty());
//                    order.setCreateTime(format.format(omProductionOrdeInfo.getCreateTime()));
//                    restFulOrders.add(order);
//                }
//            });
//        }catch (Exception e){
//            System.out.println(e.getMessage());
//        }
        return AjaxResult.success(restFulOrders);
    }
    @GetMapping("/getQualityData")
    public AjaxResult getQualityData(){
//        List<DaPassingStationCollection> qualified = daPassingStationCollectionService.list(new LambdaQueryWrapper<DaPassingStationCollection>().eq(DaPassingStationCollection::getOutRsSign, "1"));
//        List<DaPassingStationCollection> unQualified = daPassingStationCollectionService.list(new LambdaQueryWrapper<DaPassingStationCollection>().eq(DaPassingStationCollection::getOutRsSign, "2"));
//        Map<String,Integer> map = new HashMap<>();
//        map.put("qualified",qualified.size());
//        map.put("unQualified",unQualified.size());
//        for (BsBeatSetting bsBeatSetting : bsBeatSettingService.list()) {
//            String str = bsBeatSetting.getProductCode();
//            String[] split = str.split("  ");
//            String reportResult = RestfulService.getWorkReportResultFeedback(split[0], "", "2024-06-27 15:48:51");
//            JSONObject jsonObject = new JSONObject(reportResult);
//            String code = jsonObject.getStr("code");
//            String status = jsonObject.getJSONObject("data").getStr("resultCode");
//            if("success".equals(code)&&"S".equals(status)){
//                //如果成功,执行报工成功方法,修改是否报工为1,添加报工时间
//                bsBeatSetting.setProductName("S");
//                this.bsBeatSettingService.saveOrUpdate(bsBeatSetting);
//            }else{
//                bsBeatSetting.setProductName("F");
//                this.bsBeatSettingService.saveOrUpdate(bsBeatSetting);
//            }
//        }
        return AjaxResult.success();
    }
    @GetMapping("/productionOrderComponentRequest")
    public AjaxResult productionOrderComponentRequest(BsFormulaChildInfo bsFormulaChildInfo){
        List<ProductionOrderComponentRequest> requests = new ArrayList<>();
//        try{
//            CompletableFuture<Void> cp1 = CompletableFuture.runAsync(() -> {
//                List<BsFormulaChildInfo> list = bsFormulaChildInfoService.list(new LambdaQueryWrapper<BsFormulaChildInfo>()
//                        .eq(BsFormulaChildInfo::getProcessesCode, bsFormulaChildInfo.getProcessesCode())
//                        .eq(BsFormulaChildInfo::getOperationType, "2")
//                );
//                for (BsFormulaChildInfo info : list) {
//                    ProductionOrderComponentRequest request = new ProductionOrderComponentRequest();
//                    request.setMaterialCode(info.getMaterialCode());
//                    request.setOperationSteps(info.getOperationSteps());
//                    requests.add(request);
//                }
//            });
//        }catch (Exception e){
//            System.out.println(e.getMessage());
//        }
        return AjaxResult.success(requests);
    }
    /**
     * 使用反射获取对象的属性值
     *
     * @param obj       目标对象
     * @param fieldName 属性名
     * @return 属性值,如果获取失败则返回null
     * 放行请空状态
     */
    public static Object getFieldValue(Object obj, String fieldName) {
        if (obj == null) {
            throw new IllegalArgumentException("Object must not be null");
        }
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true); // 设置可访问性,以便访问私有字段
            return field.get(obj);
        } catch (NoSuchFieldException e) {
            // 如果当前类没有该字段,则尝试从父类中获取
            Class<?> superClass = obj.getClass().getSuperclass();
            if (superClass != null && !superClass.equals(Object.class)) {
                return getFieldValue(obj, fieldName, superClass);
            }
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    @PostMapping("/sendWebSocket")
    public void sendWebSocket(@RequestBody BsFormulaChildInfo bsFormulaChildInfo)
    {
        WebSocketUsers.sendMessageToUserByText(map.get(bsFormulaChildInfo.getLocationCode()), bsFormulaChildInfo.getResults());
    }
    private static Object getFieldValue(Object obj, String fieldName, Class<?> superClass) {
        try {
            Field field = superClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (NoSuchFieldException e) {
            // 如果父类也没有该字段,则继续向上查找
            Class<?> grandParentClass = superClass.getSuperclass();
            if (grandParentClass != null && !grandParentClass.equals(Object.class)) {
                return getFieldValue(obj, fieldName, grandParentClass);
            }
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}