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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.constant.IntegrationTypeConstant;
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.erp.ZprodordconfStruIn;
import com.foreverwin.mesnac.common.erp.ZprodordconfStruOut;
import com.foreverwin.mesnac.common.erp.holders.TableOfZprodordconfStruInHolder;
import com.foreverwin.mesnac.common.erp.holders.TableOfZprodordconfStruOutHolder;
import com.foreverwin.mesnac.common.model.InspectionItemDetail;
import com.foreverwin.mesnac.common.model.InspectionTask;
import com.foreverwin.mesnac.common.service.CommonService;
import com.foreverwin.mesnac.common.service.InspectionItemService;
import com.foreverwin.mesnac.common.service.InspectionTaskService;
import com.foreverwin.mesnac.common.service.SfcDispatchCommonService;
import com.foreverwin.mesnac.common.util.ERPAPI;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.dispatch.model.SfcDispatch;
import com.foreverwin.mesnac.dispatch.service.SfcDispatchService;
import com.foreverwin.mesnac.integration.model.IntegrationLog;
import com.foreverwin.mesnac.integration.service.IntegrationLogService;
import com.foreverwin.mesnac.meapi.dto.BomComponentDto;
import com.foreverwin.mesnac.meapi.dto.SfcDto;
import com.foreverwin.mesnac.meapi.dto.WorkCenterDto;
import com.foreverwin.mesnac.meapi.mapper.ResrceMapper;
import com.foreverwin.mesnac.meapi.model.*;
import com.foreverwin.mesnac.meapi.service.*;
import com.foreverwin.mesnac.production.mapper.SfcCrossMapper;
import com.foreverwin.mesnac.production.mapper.SfcDataAssembleMapper;
import com.foreverwin.mesnac.production.model.LoadInventory;
import com.foreverwin.mesnac.production.model.SfcHoldLog;
import com.foreverwin.mesnac.production.service.LoadInventoryService;
import com.foreverwin.mesnac.production.service.PodTemplateService;
import com.foreverwin.mesnac.production.service.SfcCrossService;
import com.foreverwin.mesnac.production.service.SfcHoldLogService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.meext.MEServices;
import com.foreverwin.modular.core.util.CommonMethods;
import com.sap.me.production.AssembleComponentsRequest;
import com.sap.me.production.AssemblyComponent;
import com.sap.me.production.AssemblyDataField;
import com.sap.me.production.AssemblyServiceInterface;
import org.apache.axis.AxisFault;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
@Transactional(rollbackFor = Exception.class)
public class PodTemplateServiceImpl implements PodTemplateService {
    @Value("${ws.erp.enabled}")
    private boolean enabled;
    @Autowired
    private ResrceService resrceService;
    @Autowired
    private SfcService sfcService;
    @Autowired
    private RouterService routerService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private SfcBomService sfcBomService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SfcCrossMapper sfcCrossMapper;
    @Autowired
    private SfcCrossService sfcCrossService;
    @Autowired
    private OperationService operationService;
    @Autowired
    private SfcHoldLogService sfcHoldLogService;
    @Autowired
    private CustomFieldsService customFieldsService;
    @Autowired
    private BomComponentService bomComponentService;
    @Autowired
    private LoadInventoryService loadInventoryService;
    @Autowired
    private SfcDataAssembleMapper sfcDataAssembleMapper;
    @Autowired
    private InspectionTaskService inspectionTaskService;
    @Autowired
    private InspectionItemService inspectionItemService;
    @Autowired
    private IntegrationLogService integrationLogService;
    @Autowired
    private SfcDispatchCommonService sfcDispatchCommonService;
    @Autowired
    private ResrceMapper resrceMapper;
    @Autowired
    private SfcDispatchService sfcDispatchService;


    @Override
    public Map<String, Object> resrceEnter(WorkCenterDto workCenterDto) {
        String site = CommonMethods.getSite();
        String resrce = workCenterDto.getResrce();
        String resrceBO = HandleEnum.RESOURCE.getHandle(site, resrce);
        Resrce model = resrceService.getById(resrceBO);
        if (model == null) {
            throw new BaseException("资源 " + resrce + " 不存在");
        }
        String workCenter = workCenterDto.getWorkCenter();
        //校验
        String workShopBo = commonService.getWorkShopBo(resrceBO);
        if (StringUtil.isBlank(workShopBo)) {
            throw new BaseException("资源 " + resrce + " 未匹配到车间");
        }
        if (!workCenter.equals(StringUtil.trimHandle(workShopBo))) {
            throw new BaseException("资源 " + resrce + " 与车间不匹配");
        }
        //查询在该设备存在活动中的SFC
        List<SfcDto> sfcList = sfcCrossService.getSfcListByResrce(site, resrce);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("SFC_LIST", sfcList);
        return resultMap;
    }

    @Override
    public Map<String, Object> sfcEnter(SfcDto sfcDto) {
        String site = CommonMethods.getSite();
        String sfc = sfcDto.getSfc();
        String locale = LocaleContextHolder.getLocale().getLanguage();
        String resrce = sfcDto.getResrce();
        //校验产品条码是否存在
        Sfc sfcById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfc));
        if (sfcById == null) {
            throw new BaseException("产品条码" + sfc + "不存在");
        }
        String status = StringUtil.trimHandle(sfcById.getStatusBo());
        if (!status.equals("404")&&!status.equals("403") && !status.equals("401") && !status.equals("402")) {
            throw new BaseException("产品条码" + sfc + "不在工作中或排队中");
        }
        //校验产品条码是否在当前工序排队
        Operation operationBySfcBo = commonService.getOperationBySfcBo(sfcById.getHandle());
        //校验SFC+工序+设备+STEP_ID是否与当前设备确认的派工单匹配
        String sfcDispatchStatus = sfcCrossMapper.getSfcDispatch(site, sfc, operationBySfcBo.getOperation(), operationBySfcBo.getStepId(), resrce);
        if (StringUtil.isBlank(sfcDispatchStatus)) {
            throw new BaseException("产品条码与当前设备工序确认的派工单不匹配");
        }
        if (!sfcDispatchStatus.equals(DispatchStatusEnum.RELEASE.getCode())&&!sfcDispatchStatus.equals(DispatchStatusEnum.START.getCode())) {
            throw new BaseException("派工单状态不可用");
        }

        //构造前台所需要的数据
        Map<String, Object> resultMap = sfcCrossMapper.querySfcData(site, locale, sfcDto);
        if (resultMap == null) {
            throw new BaseException("根据当前资源未找到条码[" + sfc + "]的基本信息！");
        }
        //List<Map<String, Object>> substepList = sfcCrossMapper.querySfcStep(site, sfc, operationBySfcBo.getOperation());
        List<Map<String, Object>> substepList = new ArrayList<>();
        resultMap.put("SFC_STEP_LIST", substepList);

        //是否需要自检和互检
        String isCreateH = "N";
        String isCreateZ = "N";
        resultMap.put("IS_CREATE_W", "N");
        List<InspectionItemDetail> inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operationBySfcBo.getOperation(), operationBySfcBo.getStepId(), Constants.INSPECTION_TYPE_H);
        if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
            InspectionTask createTask = inspectionTaskService.isCreateTask(site, Constants.INSPECTION_TYPE_H, sfc, operationBySfcBo.getOperation(), operationBySfcBo.getStepId());
            if (createTask == null || !createTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)) {
                isCreateH = "Y";
            }

        }
        inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operationBySfcBo.getOperation(), operationBySfcBo.getStepId(), Constants.INSPECTION_TYPE_Z);
        if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
            InspectionTask createTask = inspectionTaskService.isCreateTask(site, Constants.INSPECTION_TYPE_Z, sfc, operationBySfcBo.getOperation(), operationBySfcBo.getStepId());
            if (createTask == null || !createTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)) {
                isCreateZ = "Y";
            }
        }
        resultMap.put("IS_CREATE_H", isCreateH);
        resultMap.put("IS_CREATE_Z", isCreateZ);
        return resultMap;
    }

    @Override
    public Object getSfcInfo(SfcDto sfcDto) {
        String site = CommonMethods.getSite();
        String operation = sfcDto.getOperation();
        String sfc = sfcDto.getSfc();
        Map<String, Object> substepList = sfcCrossMapper.getSfcInfo(site, sfc, operation);
        return substepList;
    }

    @Override
    public void sfcStart(Map<String, Object> map) {
        List<SfcDto> sfcDtoList = (List<SfcDto>) map.get("sfcDtoList");
        ObjectMapper mapper = new ObjectMapper();
        sfcDtoList = mapper.convertValue(sfcDtoList, new TypeReference<List<SfcDto>>() {
        });
        String resrce = (String) map.get("resrce");
        String site = CommonMethods.getSite();

        if (sfcDtoList == null || sfcDtoList.size() < 1) {
            throw new BaseException("作业列表不能为空");
        }
        if (StringUtil.isBlank(resrce)) {
            throw new BaseException("资源不能为空");
        }
        //是否设备点检
        sfcCrossService.resourceCheck(resrce);
        sfcDtoList.forEach(sfcDto -> {
            String operation = sfcDto.getOperation();
            Operation currentRevisionRef = operationService.getCurrentRevisionRef(site, operation);
            String sfc = sfcDto.getSfc();
            String stepId = sfcDto.getStepId();
            String dispatchNo = sfcDto.getDispatchNo();
            Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfc));
            BigDecimal qty = new BigDecimal(sfcServiceById.getQty().toString());

            if (!operation.equals("WX_6106GX")){
                //是否有互检检验项目
                List<InspectionItemDetail> inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operation, stepId, Constants.INSPECTION_TYPE_H);
                if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
                    //是否有互检检验任务及已完成
                    InspectionTask createTask = inspectionTaskService.isCreateTask(site, Constants.INSPECTION_TYPE_H, sfc, operation, stepId);
                    if (createTask == null || !createTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)) {
                        throw new BaseException("请完成互检检验任务");
                    }
                    if (!createTask.getResult().equals(Constants.RSESULT_OK)) {
                        throw new BaseException("互检任务不合格，不能开始请检查");
                    }
                }
            }
            //是否完成专检
            QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(InspectionTask.CATEGORY, Constants.INSPECTION_TYPE_P);
            queryWrapper.eq(InspectionTask.SFC, sfc);
            queryWrapper.orderByDesc(InspectionTask.CREATED_DATE_TIME);
            List<InspectionTask> list = inspectionTaskService.list(queryWrapper);
            if (!list.isEmpty()) {
                InspectionTask inspectionTask = list.get(0);
                String result = inspectionTask.getResult();
                if (!inspectionTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)||StringUtil.isBlank(result)||!result.equals(Constants.RSESULT_OK)){
                    String checkUser = resrceMapper.findCustomFieldByResrce(site, inspectionTask.getResrce(), "CHECK_USR");
                    throw new BaseException("请联系"+checkUser+",处理专检任务。");
                }
            }
            try {
                sfcCrossService.startAction(site, currentRevisionRef.getHandle(), resrce, sfcServiceById.getHandle(), qty);
            } catch (Exception e) {
                ExceptionUtil.throwException(e);
            }
            //更改派工单状态
            sfcDispatchCommonService.updateSfcDispatchStatus(site, CommonMethods.getUser(), dispatchNo, DispatchStatusEnum.START.getCode(),null);

        });
    }

    @Override
    public String sfcComplete(SfcDto sfcDto, String resrce) {
        String site = CommonMethods.getSite();
        String operation = sfcDto.getOperation();
        Operation currentRevisionRef = operationService.getCurrentRevisionRef(site, operation);
        String sfc = sfcDto.getSfc();
        String stepId = sfcDto.getStepId();

        String dispatchNo = sfcDto.getDispatchNo();
        SfcDispatch sfcDispatchById = sfcDispatchService.getById(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
        Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfc));
        String status = StringUtil.trimHandle(sfcServiceById.getStatusBo());
        if (status.equals("404")) {
            throw new BaseException("产品条码" + sfc + "已暂停");
        }
        BigDecimal workHour=BigDecimal.ZERO;
        BigDecimal qty = new BigDecimal(sfcServiceById.getQty().toString());
        if (!operation.equals("WX_6106GX")) {
            //是否有自检检验项目
            List<InspectionItemDetail> inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operation, stepId, Constants.INSPECTION_TYPE_Z);
            if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
                //是否有自检检验任务
                InspectionTask createTask = inspectionTaskService.isCreateTask(site, Constants.INSPECTION_TYPE_Z, sfc, operation, stepId);
                if (createTask == null || !createTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)) {
                    throw new BaseException("请完成自检检验任务");
                }
                if (!createTask.getResult().equals(Constants.RSESULT_OK)) {
                    throw new BaseException("自检任务不合格，不能完成请检查");
                }
            }
            //是否装配完成
            List<Map<String, Object>> assembleList = sfcDataAssembleMapper.querySfcAssemble(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
            if (assembleList != null && assembleList.size() > 0) {
                for (Map<String, Object> objectMap : assembleList) {
                    String isAssemble = (String) objectMap.get("IS_ASSEMBLE");
                    if (!isAssemble.equals("GREEN")) {
                        throw new BaseException("未装配完成");
                    }
                }
            }
            //物料消耗
            materialConsumption(site, operation, HandleEnum.SFC.getHandle(site, sfc), stepId, resrce);
            //专检创建
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("SFC", sfc);
            paramMap.put("SHOP_ORDER", StringUtil.trimHandle(sfcServiceById.getShopOrderBo()));
            paramMap.put("OPERATION", operation);
            paramMap.put("STEP_ID", stepId);
            String workShopBo = commonService.getWorkShopBo(HandleEnum.RESOURCE.getHandle(site, resrce));
            if (StringUtil.isBlank(workShopBo)){
                throw new BaseException("设备与车间关系未维护");
            }
            paramMap.put("WORK_CENTER", StringUtil.trimHandle(workShopBo));
            paramMap.put("RESRCE", resrce);
            paramMap.put("SFC_DISPATCH_DETAIL_BO", HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));

            inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operation, stepId, Constants.INSPECTION_TYPE_P);
            if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
                paramMap.put("CATEGORY", Constants.INSPECTION_TYPE_P);
                inspectionTaskService.createTask(paramMap);
            } else {
                String special = customFieldsService.getCustomFieldsValue(currentRevisionRef.getHandle(), "SPECIAL");
                paramMap.put("CATEGORY", Constants.INSPECTION_TYPE_P);
                if (StringUtil.isBlank(special)|| !special.equals("N")){
                    inspectionTaskService.createNewTask(paramMap);
                }
            }
            //首件创建
            inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operation, stepId, Constants.INSPECTION_TYPE_S);
            if (inspectionItemDetails.size() > 0 && inspectionItemDetails.get(0) != null) {
                paramMap.put("CATEGORY", Constants.INSPECTION_TYPE_S);
                inspectionTaskService.createTask(paramMap);
            }
            //计算工时
            //LocalDateTime startTime = sfcService.getSfcStartTime(HandleEnum.SFC.getHandle(site, sfc));
            // 派工表实际开始时间
            LocalDateTime startTime = sfcDispatchById.getActualStartDate();
            long workHourSeconds = Duration.between(startTime, LocalDateTime.now()).getSeconds();
            workHour = new BigDecimal(workHourSeconds).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP);
            //减去暂停时间
            QueryWrapper<SfcHoldLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SfcHoldLog.SFC, sfc);
            queryWrapper.eq(SfcHoldLog.STEP_ID, stepId);
            queryWrapper.eq(SfcHoldLog.TYPE, "CANCEL");
            List<SfcHoldLog> list = sfcHoldLogService.list(queryWrapper);
            if (!list.isEmpty()) {
                BigDecimal holdTime = list.stream().map(SfcHoldLog::getHoldDuration).reduce(BigDecimal.ZERO, BigDecimal::add);
                workHour = workHour.subtract(holdTime);
            }
        }
        try {

            sfcCrossService.completeAction(site, currentRevisionRef.getHandle(), resrce, sfcServiceById.getHandle(), qty);
            //更改派工单状态
            sfcDispatchCommonService.updateSfcDispatchStatus(site, CommonMethods.getUser(), dispatchNo, DispatchStatusEnum.COMPLETE.getCode(),workHour);
            //报工
            if (enabled){
                SfcDispatchDto sfcdispatch = new SfcDispatchDto();
                sfcdispatch.setHandle(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
                sfcdispatch = sfcDispatchCommonService.findSfcDispatchBySfc(sfcdispatch);
                if (sfcdispatch.getProdHours() == null){
                    throw BusinessException.build("产品条码["+ sfcdispatch.getSfc() +"]的标准工时为空，无法报工！");
                }
                sendErp(sfc, stepId, qty, BigDecimal.ZERO, qty.multiply(sfcdispatch.getProdHours()));
            }
        } catch (Exception e) {
            ExceptionUtil.throwException(e);
        }
        return sfc;

    }

    public void materialConsumption(String site, String operation, String sfcBo, String stepId, String resource) {
        Sfc sfcServiceById = sfcService.getById(sfcBo);
        SfcBom queryEntity = new SfcBom();
        queryEntity.setSfcBo(sfcBo);
        List<SfcBom> sfcBoms = sfcBomService.selectList(queryEntity);
        if (sfcBoms.isEmpty()) {
            return;
        }
        //查询bom组件
        List<BomComponentDto> bomComponents = bomComponentService.getSfcBomComponent(sfcBo);
        if (bomComponents.isEmpty()) {
            return;
        }
        for (BomComponentDto BomComponentDto : bomComponents) {
            String accessoryType = BomComponentDto.getAccessoryType();
            String componentGbo = BomComponentDto.getComponentGbo();
            Item currentReversionItem = itemService.selectCurrent(site, StringUtil.trimHandle(componentGbo));
            //消耗辅料类型为空或null
            if ((accessoryType == null || accessoryType.equals("0")) && stepId.equals(BomComponentDto.getStepId())) {
                //查询设备上的料
                QueryWrapper<LoadInventory> wrapper = new QueryWrapper<>();
                wrapper.eq(LoadInventory.RESRCE, resource);
                wrapper.eq(LoadInventory.ITEM, StringUtil.trimHandle(componentGbo));
                wrapper.orderByAsc(LoadInventory.CREATED_DATE_TIME);
                List<LoadInventory> inventoryList = loadInventoryService.list(wrapper);
                if (inventoryList.isEmpty()) {
                    throw new BaseException("设备没有上" + StringUtil.trimHandle(componentGbo) + "/" + currentReversionItem.getDescription() + "料");
                }
                BigDecimal needQty = new BigDecimal(String.valueOf(BomComponentDto.getQty())).multiply(new BigDecimal(sfcServiceById.getQty()));
                for (LoadInventory loadInventory : inventoryList) {
                    BigDecimal qtyOnHand = loadInventory.getQtyOnHand();
                    BigDecimal costQty;
                    if (needQty.doubleValue() > qtyOnHand.doubleValue()) {
                        costQty = qtyOnHand;
                        needQty = needQty.subtract(costQty);
                    } else {
                        costQty = needQty;
                        needQty = BigDecimal.ZERO;
                    }
                    //删除上料数据
                    Inventory inventory = loadInventoryService.consumption(loadInventory, costQty);
                    //消耗
                    try {
                        assembly(site, BomComponentDto.getHandle(), operation, inventory, sfcBo, resource, costQty, stepId, sfcServiceById.getShopOrderBo());
                    } catch (Exception e) {
                        ExceptionUtil.throwException(e);
                    }
                    if (needQty.doubleValue() == 0) {
                        break;
                    }
                }
                if (needQty.doubleValue() > 0) {
                    throw new BaseException("组件[" + StringUtil.trimHandle(componentGbo) + "]耗用数量差[" + needQty + "]");
                }
            }
        }
    }

    public void assembly(String site, String BomComponentRef, String operation, Inventory inventory, String sfcBo, String resource, BigDecimal costQty, String stepId, String shopOrderBo) throws Exception {
        //装配
        AssemblyServiceInterface assemblyServiceInterface = MEServices.create("com.sap.me.production", "AssemblyService", site);
        AssembleComponentsRequest assembleComponentsRequest = new AssembleComponentsRequest();
        List<AssemblyComponent> assemblyComponentList = new ArrayList<>();
        String itemBo = inventory.getItemBo();
        AssemblyComponent assemblyComponent = new AssemblyComponent();
        assemblyComponent.setBomComponentRef(BomComponentRef);
        assemblyComponent.setTimeBased(false);
        assemblyComponent.setQty(costQty);
        assemblyComponent.setActualComponentRef(itemBo);
        List<AssemblyDataField> assemblyDataFieldList = new ArrayList<>();
        AssemblyDataField assemblyDataField = new AssemblyDataField();
        assemblyDataField.setAttribute("INVENTORY_ID_SFC");
        assemblyDataField.setValue(inventory.getInventoryId());
        assemblyDataFieldList.add(assemblyDataField);

        assemblyComponent.setAssemblyDataFields(assemblyDataFieldList);
        assemblyComponentList.add(assemblyComponent);
        assembleComponentsRequest.setComponentList(assemblyComponentList);
        assembleComponentsRequest.setSfcRef(sfcBo);
        assembleComponentsRequest.setOperationRef(operationService.getCurrentRevisionRef(site, operation).getHandle());
        assembleComponentsRequest.setShopOrderRef(shopOrderBo);
        assembleComponentsRequest.setResourceRef(HandleEnum.RESOURCE.getHandle(site, resource));
        assembleComponentsRequest.setRouterRef(routerService.getRouterBySfcBo(sfcBo).getHandle());
        assembleComponentsRequest.setStepId(stepId);
        assembleComponentsRequest.setQuantity(costQty);
        assembleComponentsRequest.setEvent("baseFinished:AssemblyPoint");
        assemblyServiceInterface.assembleByComponents(assembleComponentsRequest);
    }

    @Override
    public void sendErp(String sfc, String stepId, BigDecimal qty, BigDecimal scrapQty, BigDecimal workHour) {
        //请求参数
        ZprodordconfStruIn[] ins = new ZprodordconfStruIn[1];
        Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(CommonMethods.getSite(), sfc));
        String shopOrderBo = sfcServiceById.getShopOrderBo();
        String shopOrder = StringUtil.trimHandle(shopOrderBo);
        ZprodordconfStruIn struIn = new ZprodordconfStruIn();
        workHour = workHour.setScale(3,RoundingMode.DOWN);
        //生产订单
        struIn.setAufnr(shopOrder);
        //步骤标示
        struIn.setVornr(stepId);
        struIn.setAueru("1");
        //良品数量
        struIn.setLmnga(qty);
        //报废数量
        struIn.setXmnga(scrapQty);
        //机器工时
        struIn.setIsm01(workHour);
        //人工工时
        struIn.setIsm02(workHour);
        struIn.setIsm03(workHour);
        struIn.setIsm04(workHour);
        struIn.setIsm05(workHour);
        struIn.setIsm06(workHour);
        ins[0] = struIn;
        TableOfZprodordconfStruInHolder inHolder = new TableOfZprodordconfStruInHolder(ins);

        //返回对象
        ZprodordconfStruOut[] outs = new ZprodordconfStruOut[1];

        ZprodordconfStruOut struOut = new ZprodordconfStruOut();
        struOut.setAufnr(ins[0].getAufnr());
        struOut.setVornr(ins[0].getVornr());
        struOut.setAueru("1");
        struOut.setLmnga(ins[0].getLmnga());
        struOut.setRet("");
        struOut.setMsg("");
        outs[0] = struOut;
        TableOfZprodordconfStruOutHolder outHolder = new TableOfZprodordconfStruOutHolder(outs);
        IntegrationLog log = new IntegrationLog();

        //调用WS
        try {
            ERPAPI.erpWebService().zmesProdordconf(inHolder, outHolder);
            String status = outHolder.value[1].getRet();
            String message = outHolder.value[1].getMsg();
            if (!status.equals("S")) {
                throw new BaseException(message);
            }
            log.setStatus(status);
            log.setResultMessage(message);
        } catch (Exception e) {
            log.setStatus("E");
            log.setResultMessage("ERP接口错误: " + e.getMessage());
            if (outHolder.value.length == 1){
                String faultString = ((AxisFault) e).getFaultString();
                if (StringUtil.isBlank(faultString)||!faultString.equals("(401)Unauthorized")){
                    throw new BaseException("ERP接口错误: " + e.getMessage());
                }
                log.setStatus("R");
            }else {
                throw new BaseException("ERP接口错误: " + e.getMessage());
            }
        } finally {
            //记录接口日志
            log.setHandle(UUID.randomUUID().toString());
            log.setSite(CommonMethods.getSite());
            log.setIntegrationType(IntegrationTypeConstant.REPORT_ORDER);
            log.setCategory("REQUEST");
            log.setIntegrationWay("ERP");
            log.setIntegrationMethod("erpWebService.zmesProdordconf");
            log.setParam(JSONObject.toJSONString(struIn));
            log.setTransactionId("");
            log.setRequestDateTime(LocalDateTime.now());
            log.setCreatedDateTime(LocalDateTime.now());
            integrationLogService.saveIntegrationLog(log);
        }
    }

    @Override
    public SfcDto getInfoBySfc(Sfc sfc) {
        String site = CommonMethods.getSite();
        sfc.setSite(site);
        return sfcCrossMapper.getInfoBySfc(sfc);
    }
}
