package com.sunda.spmsoversea.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.sunda.spmscommon.Constans;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.service.ISysLogMqService;
import com.sunda.spmsoversea.dto.WerksAllStorageInvSearchDTO;
import com.sunda.spmsoversea.entity.*;
import com.sunda.spmsoversea.enums.OverseaWhsInventoryLossEnum;
import com.sunda.spmsoversea.mapper.EamReserveInventoryMapper;
import com.sunda.spmsoversea.service.*;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmsoversea.enums.OverseaRequisitionEnum.*;

/**
 * <p>
 * ESB接口同步
 * </p>
 *
 * @author hzc
 * @since 2022年12月28日09:49:10
 */
@Slf4j
@Service
public class EsbRfcServiceImpl implements IEsbRfcService {


    @Autowired
    IEamReserveInventoryService eamReserveInventoryService;

    @Autowired
    WhsStorageInventoryServiceImpl whsStorageInventoryService;
    @Autowired
    IWhsOperateLogService whsOperateLogService;
    @Autowired
    IOverseaRequisitionService overseaRequisitionService;
    @Autowired
    IOverseaOperateLogService iOverseaOperateLogService;
    @Autowired
    IOverseaRequisitionDtlService iOverseaRequisitionDtlService;
    @Autowired
    IEamReturnSkuService eamReturnSkuService;
    @Autowired
    IEamReturnSkuDtlService eamReturnSkuDtlService;
    @Autowired
    IEamFormerSkuService eamFormernSkuService;
    @Autowired
    IEamFormerSkuDtlService eamFormerSkuDtlService;
    @Autowired
    IOverseaWhsInventoryLossService iOverseaWhsInventoryLossService;
    
    @Autowired
    ISysLogMqService iSysLogMqService;


    @Autowired
    EamReserveInventoryMapper eamReserveInventoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult reserveInventory(JSONObject doc)  throws Exception {
        List<Map> dataList = (List) doc.get("IT_REQUEST");
        List<EamReserveInventory> addList = new ArrayList<EamReserveInventory>();
        List<EamReserveInventory> updateList = new ArrayList<EamReserveInventory>();
        for (int i = 0; i < dataList.size(); i++){
            EamReserveInventory vo = new EamReserveInventory();
            vo.setRequestnum(dataList.get(i).get("REQUESTNUM")==null?"":dataList.get(i).get("REQUESTNUM").toString());
            vo.setItemnum(dataList.get(i).get("ITEMNUM")==null?"":dataList.get(i).get("ITEMNUM").toString());
            vo.setLocation(dataList.get(i).get("LOCATION")==null?"":dataList.get(i).get("LOCATION").toString());
            vo.setWonum(dataList.get(i).get("WONUM")==null?"":dataList.get(i).get("WONUM").toString());

            if(dataList.get(i).get("ACTUALQTY")!=null && dataList.get(i).get("ACTUALQTY").toString().length()>0){
                vo.setActualqty(new BigDecimal(dataList.get(i).get("ACTUALQTY").toString()));
            }else{
                vo.setActualqty(new BigDecimal("0"));
            }

            if(dataList.get(i).get("RESERVEDQTY")!=null && dataList.get(i).get("RESERVEDQTY").toString().length()>0){
                vo.setReservedqty(new BigDecimal(dataList.get(i).get("RESERVEDQTY").toString()));
            }else{
                vo.setReservedqty(new BigDecimal("0"));
            }
            vo.setInitflag(dataList.get(i).get("INITFLAG")==null?"":dataList.get(i).get("INITFLAG").toString());
            vo.setDirectreq(dataList.get(i).get("DIRECTREQ")==null?"":dataList.get(i).get("DIRECTREQ").toString());
            vo.setOrgid(dataList.get(i).get("ORGID")==null?"":dataList.get(i).get("ORGID").toString());
            vo.setSiteid(dataList.get(i).get("SITEID")==null?"":dataList.get(i).get("SITEID").toString());
            vo.setInvreserveid(dataList.get(i).get("INVRESERVEID")==null?"":dataList.get(i).get("INVRESERVEID").toString());
            vo.setLangcode(dataList.get(i).get("LANGCODE")==null?"":dataList.get(i).get("LANGCODE").toString());
            vo.setHasld(dataList.get(i).get("HASLD")==null?"":dataList.get(i).get("HASLD").toString());
            vo.setShowallreservation(dataList.get(i).get("SHOWALLRESERVATION")==null?"":dataList.get(i).get("SHOWALLRESERVATION").toString());
            vo.setRestype(dataList.get(i).get("RESTYPE")==null?"":dataList.get(i).get("RESTYPE").toString());
            vo.setBinnum(dataList.get(i).get("BINNUM")==null?"":dataList.get(i).get("BINNUM").toString());
            vo.setZdel(dataList.get(i).get("ZDEL")==null?"":dataList.get(i).get("ZDEL").toString());

            EamReserveInventory  objectMap = eamReserveInventoryService.getOne(new QueryWrapper<EamReserveInventory>().eq("REQUESTNUM", vo.getRequestnum()).eq("ITEMNUM", vo.getItemnum()));
            if(objectMap!=null){
                updateList.add(vo);
            }else{
                addList.add(vo);
            }
        }
        if(addList!=null && addList.size()>0){
            eamReserveInventoryService.saveOrUpdateBatch(addList);
            for (int i = 0; i < addList.size(); i++){
                double qty = addList.get(i).getActualqty().doubleValue();
                String materialNo = addList.get(i).getItemnum();
                String whsLocationCode = addList.get(i).getLocation();//仓库
                String storageNo = addList.get(i).getBinnum();//储位
                String werks = addList.get(i).getSiteid();
                String storageUuid = "";
                List<Map<String, String>> whsStorageList = eamReserveInventoryMapper.getWhsStorageUuid(werks, storageNo);
                if(whsStorageList!=null && whsStorageList.size()>0){
                    storageUuid = whsStorageList.get(0).get("UUID");
                }else{
                    throw new Exception(werks+"工厂不存在储位" + storageNo );
                }
                WhsStorageInventory whSI = whsStorageInventoryService.getOne(
                        new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                if (whSI == null) {
                    throw new MybatisPlusException("物料" + materialNo + "不存在库存！");
                }else{
                    double quantity = whSI.getQuantity() - qty;
                    if(quantity>=0){
                        WhsStorageInventory storageInventory = new WhsStorageInventory();
                        storageInventory.setQuantity(quantity);
                        storageInventory.setAvailableQty(quantity);
                        whsStorageInventoryService.update(storageInventory,
                                new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                    }else{
                        throw new Exception("物料" + materialNo + "库存不足。当前库存数量为："+whSI.getQuantity());
                    }
                    whsOperateLogService.insertWhsOperateLog(storageUuid, materialNo, qty,
                            "4", addList.get(i).getRequestnum(), Constans.WHS_WhsOut_WithEAM, "EAM系统", Constans.WHS_WhsOut_WithEAM + materialNo + ":" + qty,
                            werks, whsLocationCode, "", "");
                }
            }

        }
        if(updateList!=null && updateList.size()>0){
            for (int i = 0; i < updateList.size(); i++){
                eamReserveInventoryService.update(updateList.get(i),new QueryWrapper<EamReserveInventory>().eq("REQUESTNUM", updateList.get(i).getRequestnum()).eq("ITEMNUM", updateList.get(i).getItemnum()));
                if("X".equals(updateList.get(i).getZdel())){
                    double qty = updateList.get(i).getActualqty().doubleValue();
                    String materialNo = updateList.get(i).getItemnum();
                    String whsLocationCode = updateList.get(i).getLocation();//仓库
                    String storageNo = updateList.get(i).getBinnum();//储位
                    String werks = updateList.get(i).getSiteid();
                    String storageUuid = "";
                    List<Map<String, String>> whsStorageList = eamReserveInventoryMapper.getWhsStorageUuid(werks, storageNo);
                    if(whsStorageList!=null && whsStorageList.size()>0){
                        storageUuid = whsStorageList.get(0).get("UUID");
                    }else{
                        throw new Exception(werks+"工厂不存在储位" + storageNo );
                    }
                    WhsStorageInventory whSI = whsStorageInventoryService.getOne(
                            new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                    if (whSI == null) {
                        throw new MybatisPlusException("物料" + materialNo + "不存在库存！");
                    }else{
                        double quantity = whSI.getQuantity() + qty;
                        WhsStorageInventory storageInventory = new WhsStorageInventory();
                        storageInventory.setQuantity(quantity);
                        storageInventory.setAvailableQty(quantity);
                        whsStorageInventoryService.update(storageInventory,
                                new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                    }
                    whsOperateLogService.insertWhsOperateLog(storageUuid, materialNo, qty,
                            "2", updateList.get(i).getRequestnum(), Constans.WHS_WhsIn_WithEAM,
                            "EAM系统", Constans.WHS_WhsIn_WithEAM + materialNo + ":" + qty,
                            werks, whsLocationCode, "", "");
                }else{
                    double qty = updateList.get(i).getActualqty().doubleValue();
                    String materialNo = updateList.get(i).getItemnum();
                    String whsLocationCode = updateList.get(i).getLocation();//仓库
                    String storageNo = updateList.get(i).getBinnum();//储位
                    String werks = updateList.get(i).getSiteid();
                    String storageUuid = "";
                    List<Map<String, String>> whsStorageList = eamReserveInventoryMapper.getWhsStorageUuid(werks, storageNo);
                    if(whsStorageList!=null && whsStorageList.size()>0){
                        storageUuid = whsStorageList.get(0).get("UUID");
                    }else{
                        throw new Exception(werks+"工厂不存在储位" + storageNo );
                    }
                    WhsStorageInventory whSI = whsStorageInventoryService.getOne(
                            new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                    if (whSI == null) {
                        throw new MybatisPlusException("物料" + materialNo + "不存在库存！");
                    }else{
                        double quantity = whSI.getQuantity() - qty;
                        if(quantity>=0){
                            WhsStorageInventory storageInventory = new WhsStorageInventory();
                            storageInventory.setQuantity(quantity);
                            storageInventory.setAvailableQty(quantity);
                            whsStorageInventoryService.update(storageInventory,
                                    new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                        }else{
                            throw new Exception("物料" + materialNo + "库存不足。当前库存数量为："+whSI.getQuantity());
                        }
                        whsOperateLogService.insertWhsOperateLog(storageUuid, materialNo, qty,
                                "4", addList.get(i).getRequestnum(), Constans.WHS_WhsOut_WithEAM, "EAM系统", Constans.WHS_WhsOut_WithEAM + materialNo + ":" + qty,
                                werks, whsLocationCode, "", "");
                    }
                }
            }
        }

        return ResponseResult.success("预留成功!");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult eamRequisitionlist(JSONObject doc)  throws Exception {
        if(doc == null){
            throw new Exception("报文异常！");
        }else{
            log.info(doc.toJSONString());
        }
        Map head =  (Map) doc.get("WORKORDER");
        List<Map> item = (List) doc.get("WPITEM");

        if(head.get("WONUM")!=null && head.get("WONUM").toString().length()>0){

        }else{
            throw new Exception("工单编码不能为空！");
        }
        log.info("head");
//        if(head.get("REQUESTNUM")!=null && head.get("REQUESTNUM").toString().length()>0){
//
//        }else{
//            throw new Exception("预留单号不能为空！");
//        }
        log.info("item");
        if(item!=null && item.size()>0){

        }else{
            throw new Exception("行明细不能为空！");
        }

        String uuidRequisition = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfM = new SimpleDateFormat("yyyyMMdd");
        OverseaRequisition overseaRequisition = new OverseaRequisition();
        overseaRequisition.setUuidRequisition(uuidRequisition);
        overseaRequisition.setCreateDate(sdf.format(new Date()));
        overseaRequisition.setSpmsStatus(REQUISITION_APPROVED.getCode());//EAM提交的领用申请默认审核通过
        //overseaRequisition.setBusinessType(overseaRequisitionDTO.getBusinessType());
        overseaRequisition.setCreateUserid(head.get("CREATEBY")==null?"":head.get("CREATEBY").toString());
        overseaRequisition.setWerks(head.get("SITEID")==null?"":head.get("SITEID").toString());
        overseaRequisition.setWorkshopCode(head.get("WORKSHOP")==null?"":head.get("WORKSHOP").toString());
        overseaRequisition.setWhsLocationCode(head.get("LOCNUM")==null?"":head.get("LOCNUM").toString());
        overseaRequisition.setRelateDocument(head.get("WONUM")==null?"":head.get("WONUM").toString());//来源单号(EAM)
        //overseaRequisition.setRequestNum(head.get("REQUESTNUM")==null?"":head.get("REQUESTNUM").toString());//EAM预留单号
        overseaRequisition.setRequestNum("EAM");//EAM不再推送预留单号，默认是EAM
        overseaRequisition.setCostCenter(head.get("KOSTL")==null?"":head.get("KOSTL").toString());//成本中心
        overseaRequisition.setEamAppType(head.get("APPTYPE")==null?"":head.get("APPTYPE").toString());//触发类型：区分是工单领料触发还是手动创建领料
        //overseaRequisition.setCostCenterName(head.get("")==null?"":head.get("").toString());
        //overseaRequisition.setRemarks(head.get("")==null?"":head.get("").toString());
        overseaRequisition.setComments(head.get("SITEID")+"-"+head.get("WORKSHOP")+"-"+sdfM.format(new Date()));//标题
        //overseaRequisition.setOaNumber(head.get("")==null?"":head.get("").toString());
        overseaRequisitionService.save(overseaRequisition);

        log.info("head save!");
        for (int i = 0; i < item.size(); i ++){
            Map<String,String> dtlDTO = item.get(i);
            OverseaRequisitionDtl overseaRequisitionDtl = new OverseaRequisitionDtl();
            overseaRequisitionDtl.setUuidRequisition(uuidRequisition);
            overseaRequisitionDtl.setItem((i + 1) * 10);
            overseaRequisitionDtl.setWerks(head.get("SITEID")==null?"":head.get("SITEID").toString());
            overseaRequisitionDtl.setWorkshopCode(dtlDTO.get("WORKSHOP")==null?"":dtlDTO.get("WORKSHOP").toString());
            overseaRequisitionDtl.setWhsLocationCode(head.get("LOCNUM")==null?"":head.get("LOCNUM").toString());
            if(dtlDTO.get("ITEMNUM")!=null && dtlDTO.get("ITEMNUM").toString().length()>0){
                overseaRequisitionDtl.setMaterialNo(dtlDTO.get("ITEMNUM").toString());
            }else{
                throw new Exception("物料号不能为空！");
            }
            overseaRequisitionDtl.setApplyQtyBasicUnit(dtlDTO.get("ORDERQTY")==null? 0 : Double.parseDouble(dtlDTO.get("ORDERQTY").toString()));
            overseaRequisitionDtl.setActualQtyBasicUnit(dtlDTO.get("APPRQUANTITY")==null? 0 : Double.parseDouble(dtlDTO.get("APPRQUANTITY").toString()));
            overseaRequisitionDtl.setBasicUnit(dtlDTO.get("ORDERUNIT")==null?"":dtlDTO.get("ORDERUNIT").toString());//基本单位
            overseaRequisitionDtl.setApplyQtyUnitSales(dtlDTO.get("ORDERQTY")==null? 0 : Double.parseDouble(dtlDTO.get("ORDERQTY").toString()));
            overseaRequisitionDtl.setActualQtyUnitSales(dtlDTO.get("APPRQUANTITY")==null? 0 : Double.parseDouble(dtlDTO.get("APPRQUANTITY").toString()));
            overseaRequisitionDtl.setUnitSales(dtlDTO.get("ORDERUNIT")==null?"":dtlDTO.get("ORDERUNIT").toString());//销售单位
            overseaRequisitionDtl.setRemarks(dtlDTO.get("REMARKS")==null?"":dtlDTO.get("REMARKS").toString());
            overseaRequisitionDtl.setMovementType(dtlDTO.get("SJYDTYPE")==null?"":dtlDTO.get("SJYDTYPE").toString());
            overseaRequisitionDtl.setActualMovementType(dtlDTO.get("SJYDTYPE")==null?"":dtlDTO.get("SJYDTYPE").toString());
            overseaRequisitionDtl.setStorageCode(dtlDTO.get("BINNUM")==null?"":dtlDTO.get("BINNUM").toString());
            overseaRequisitionDtl.setEamItemNo(dtlDTO.get("LINENUM")==null?"":dtlDTO.get("LINENUM").toString());
            // 内部订单号
            if (StringUtils.isNotBlank(dtlDTO.get("AUFNR"))) {
            	List<Map<String, String>> nbddNoList = eamReserveInventoryMapper.selectNbddNo(dtlDTO.get("AUFNR").toString(), head.get("SITEID").toString());
            	if (CollectionUtils.isEmpty(nbddNoList) || "X".equals(nbddNoList.get(0).get("PHAS2")) || "X".equals(nbddNoList.get(0).get("PHAS3"))) {
            		throw new Exception("内部订单号在SPMS不存在或内部订单号已禁用");
            	}
            	overseaRequisitionDtl.setProjectOaNumber(nbddNoList.get(0).get("AUFNR")+"-"+nbddNoList.get(0).get("KTEXT"));
            } else {
            	overseaRequisitionDtl.setProjectOaNumber("");
            }
            //overseaRequisitionDtl.setCountry(dtlDTO.getCountry());


            double qty = overseaRequisitionDtl.getActualQtyBasicUnit();//基本单位出库数量
            String materialNo = overseaRequisitionDtl.getMaterialNo();//物料编码
//            String whsLocationCode = overseaRequisitionDtl.getWhsLocationCode();//仓库
            String storageNo = overseaRequisitionDtl.getStorageCode();//储位
            String werks = overseaRequisitionDtl.getWerks();//工厂
            String storageUuid = "";
            List<Map<String, String>> whsStorageList = eamReserveInventoryMapper.getWhsStorageUuid(werks, storageNo);
            if(whsStorageList!=null && whsStorageList.size()>0){
                storageUuid = whsStorageList.get(0).get("UUID");
            }else{
                throw new Exception(werks+"工厂不存在储位" + storageNo );
            }
            WhsStorageInventory whSI = whsStorageInventoryService.getOne(
                    new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
            if (whSI == null) {
                throw new MybatisPlusException("物料" + materialNo + "不存在库存！");
            }else{
                double quantity = whSI.getQuantity() - qty;
                if(quantity>=0){
//                    WhsStorageInventory storageInventory = new WhsStorageInventory();
//                    storageInventory.setQuantity(quantity);
//                    storageInventory.setAvailableQty(quantity);
//                    whsStorageInventoryService.update(storageInventory,
//                            new QueryWrapper<WhsStorageInventory>().eq("UUID", storageUuid).eq("MATERIAL_NO", materialNo));
                }else{
                    throw new Exception("物料" + materialNo + "库存不足。当前库存数量为："+whSI.getQuantity());
                }
            }

            iOverseaRequisitionDtlService.addRequisitionDtl(overseaRequisitionDtl);
        }

        log.info("item save!");
        // 根据UUID查询保存后的领用单信息
        QueryWrapper<OverseaRequisition> qw = new QueryWrapper<OverseaRequisition>().eq("UUID_REQUISITION", uuidRequisition);
        OverseaRequisition selectOne = overseaRequisitionService.getOne(qw);

        iOverseaOperateLogService.addOverseaOperateLog("EAM系统", uuidRequisition, REQUISITION_CREATE.getDescZh(), REQUISITION_CREATE.getDescEn(), "", REQUISITION_CREATE.getDescRu());
        iSysLogMqService.addSysLogMq("4", "eamRequisitionlist", "EAM推送领用单到SPMS", "eamRequisitionlist", JSON.toJSONString(doc), uuidRequisition, null);
        //getRequisitionAndDtl(uuidRequisition);
        return ResponseResult.success("领用单接口传输成功!").add("SPMS_ID", selectOne.getSpmsId()).add("SPMS_TITLE", selectOne.getComments());
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult eamReturnSkus(JSONObject doc)  throws Exception {
        if(doc == null){
            throw new Exception("报文异常！");
        }else{
            log.info(doc.toJSONString());
        }
        Map head =  (Map) doc.get("WORKORDER");
        List<Map> item = (List) doc.get("WPITEM");

        if(head.get("WONUM")!=null && head.get("WONUM").toString().length()>0){

        }else{
            throw new Exception("工单编码不能为空！");
        }
        log.info("head");
        log.info("item");
        if(item!=null && item.size()>0){

        }else{
            throw new Exception("行明细不能为空！");
        }

        String uuidRequisition = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfM = new SimpleDateFormat("yyyyMMdd");
        EamReturnSku eamReturnSku = new EamReturnSku();
        eamReturnSku.setUuidRequisition(uuidRequisition);
        eamReturnSku.setCreateDate(sdf.format(new Date()));
        eamReturnSku.setSpmsStatus(REQUISITION_APPROVED.getCode());//EAM提交的领用申请默认审核通过
        //eamReturnSku.setBusinessType(eamReturnSku.getBusinessType());
        eamReturnSku.setCreateUserid(head.get("CREATEBY")==null?"":head.get("CREATEBY").toString());//申请人
        eamReturnSku.setWerks(head.get("SITEID")==null?"":head.get("SITEID").toString());//工厂
        eamReturnSku.setWorkshopCode(head.get("WORKSHOP")==null?"":head.get("WORKSHOP").toString());//车间
        eamReturnSku.setWhsLocationCode(head.get("LOCNUM")==null?"":head.get("LOCNUM").toString());//仓库
        eamReturnSku.setRelateDocument(head.get("WONUM")==null?"":head.get("WONUM").toString());//来源单号(EAM)
        eamReturnSku.setRequestnum(head.get("YWONUM")==null?"":head.get("YWONUM").toString());//EAM领用单号
        //eamReturnSku.setRequestNum("EAM");//EAM不再推送预留单号，默认是EAM
        eamReturnSku.setCostCenter(head.get("KOSTL")==null?"":head.get("KOSTL").toString());//成本中心
        //eamReturnSku.setCostCenterName(head.get("")==null?"":head.get("").toString());
        eamReturnSku.setRemarks(head.get("REMARKS")==null?"":head.get("REMARKS").toString());//备注
        eamReturnSku.setComments(head.get("SITEID")+"-"+head.get("WORKSHOP")+"-"+sdfM.format(new Date()));//标题
        //eamReturnSku.setOaNumber(head.get("")==null?"":head.get("").toString());
        eamReturnSkuService.save(eamReturnSku);

        log.info("head save!");
        for (int i = 0; i < item.size(); i ++){
            Map<String,String> dtlDTO = item.get(i);
            EamReturnSkuDtl eamReturnSkuDtl = new EamReturnSkuDtl();
            eamReturnSkuDtl.setUuidRequisition(uuidRequisition);
            //eamReturnSkuDtl.setItem((i + 1) * 10);
            eamReturnSkuDtl.setItem(dtlDTO.get("LINENUM")==null? 0 :  Integer.parseInt(dtlDTO.get("LINENUM").toString()));
            eamReturnSkuDtl.setWerks(dtlDTO.get("SITEID")==null?"":dtlDTO.get("SITEID").toString());
            eamReturnSkuDtl.setWorkshopCode(dtlDTO.get("DEPTNUM")==null?"":dtlDTO.get("DEPTNUM").toString());
            eamReturnSkuDtl.setWhsLocationCode(dtlDTO.get("LOCATION")==null?"":dtlDTO.get("LOCATION").toString());
            if(dtlDTO.get("ITEMNUM")!=null && dtlDTO.get("ITEMNUM").toString().length()>0){
                eamReturnSkuDtl.setMaterialNo(dtlDTO.get("ITEMNUM").toString());
            }else{
                throw new Exception("物料号不能为空！");
            }
            eamReturnSkuDtl.setApplyQtyBasicUnit(dtlDTO.get("ORDERQTY")==null? 0 : Double.parseDouble(dtlDTO.get("ORDERQTY").toString()));//申请数量
            eamReturnSkuDtl.setActualQtyBasicUnit(dtlDTO.get("APPRQUANTITY")==null? 0 : Double.parseDouble(dtlDTO.get("APPRQUANTITY").toString()));//审批数量
            eamReturnSkuDtl.setBasicUnit(dtlDTO.get("ORDERUNIT")==null?"":dtlDTO.get("ORDERUNIT").toString());//退库单位
            //eamReturnSkuDtl.setApplyQtyUnitSales(dtlDTO.get("ITEMQTY")==null? 0 : Double.parseDouble(dtlDTO.get("ITEMQTY").toString()));
            //eamReturnSkuDtl.setActualQtyUnitSales(dtlDTO.get("ITEMQTY")==null? 0 : Double.parseDouble(dtlDTO.get("ITEMQTY").toString()));
            //eamReturnSkuDtl.setUnitSales(dtlDTO.get("ORDERUNIT")==null?"":dtlDTO.get("ORDERUNIT").toString());//销售单位
            eamReturnSkuDtl.setRemarks(dtlDTO.get("REMARKS")==null?"":dtlDTO.get("REMARKS").toString());
            eamReturnSkuDtl.setMovementType(dtlDTO.get("SJYDTYPE")==null?"":dtlDTO.get("SJYDTYPE").toString());//移动类型
            eamReturnSkuDtl.setActualMovementType(dtlDTO.get("SJYDTYPE")==null?"":dtlDTO.get("SJYDTYPE").toString());
            eamReturnSkuDtl.setStorageCode(dtlDTO.get("BINNUM")==null?"":dtlDTO.get("BINNUM").toString());//储位编号
            eamReturnSkuDtl.setProjectOaNumber(dtlDTO.get("AUFNR")==null?"":dtlDTO.get("AUFNR").toString());//内部订单号
            //eamReturnSkuDtl.setCountry(dtlDTO.getCountry());

            eamReturnSkuDtlService.save(eamReturnSkuDtl);
        }

        log.info("item save!");

        iOverseaOperateLogService.addOverseaOperateLog("EAM系统", uuidRequisition, REQUISITION_CREATE.getDescZh(), REQUISITION_CREATE.getDescEn(), "", REQUISITION_CREATE.getDescRu());

        //getRequisitionAndDtl(uuidRequisition);
        return ResponseResult.success("退库单接口传输成功!");
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult eamFormerSkus(JSONObject doc)  throws Exception {
        if(doc == null){
            throw new Exception("报文异常！");
        }else{
            log.info(doc.toJSONString());
        }
        Map head =  (Map) doc.get("WORKORDER");
        List<Map> item = (List) doc.get("WPITEM");

        if(head.get("RCNUM")!=null && head.get("RCNUM").toString().length()>0){

        }else{
            throw new Exception("旧件单编码不能为空！");
        }
        if(item!=null && item.size()>0){

        }else{
            throw new Exception("行明细不能为空！");
        }

        String uuidRequisition = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfM = new SimpleDateFormat("yyyyMMdd");
        EamFormerSku eamReturnSku = new EamFormerSku();
        eamReturnSku.setUuidRequisition(uuidRequisition);
        eamReturnSku.setCreateDate(sdf.format(new Date()));
        eamReturnSku.setSpmsStatus("0");//EAM提交的领用申请默认审核通过
        //eamReturnSku.setBusinessType(eamReturnSku.getBusinessType());
        eamReturnSku.setRelateDocument(head.get("RCNUM")==null?"":head.get("RCNUM").toString());//来源单号(EAM)
        eamReturnSku.setRequestnum(head.get("WONUM")==null?"":head.get("WONUM").toString());//EAM领用单号
        eamReturnSku.setCreateUserid(head.get("CREATEBY")==null?"":head.get("CREATEBY").toString());//申请人
        eamReturnSku.setWerks(head.get("SITEID")==null?"":head.get("SITEID").toString());//工厂
        eamReturnSku.setWhsLocationCode(head.get("LOCNUM")==null?"":head.get("LOCNUM").toString());//仓库
        eamReturnSku.setWorkshopCode(head.get("WORKSHOP")==null?"":head.get("WORKSHOP").toString());//车间
        eamReturnSku.setRemarks(head.get("REASON")==null?"":head.get("REASON").toString());//备注
        eamReturnSku.setBusinessType(head.get("FLAG")==null?"":head.get("FLAG").toString());//旧件回收入库标识，固定值：RC（旧件入库）
        eamReturnSku.setComments(head.get("SITEID")+"-"+head.get("WORKSHOP")+"-"+sdfM.format(new Date()));//标题
        eamFormernSkuService.save(eamReturnSku);

        log.info("head save!");
        for (int i = 0; i < item.size(); i ++){
            Map<String,String> dtlDTO = item.get(i);
            EamFormerSkuDtl eamReturnSkuDtl = new EamFormerSkuDtl();
            eamReturnSkuDtl.setUuidRequisition(uuidRequisition);
            eamReturnSkuDtl.setItem((i + 1) * 10);
            //eamReturnSkuDtl.setItem(dtlDTO.get("LINENUM")==null? 0 :  Integer.parseInt(dtlDTO.get("LINENUM").toString()));
            eamReturnSkuDtl.setWerks(head.get("SITEID")==null?"":head.get("SITEID").toString());
            eamReturnSkuDtl.setWorkshopCode(head.get("WORKSHOP")==null?"":head.get("WORKSHOP").toString());
            eamReturnSkuDtl.setWhsLocationCode(head.get("LOCNUM")==null?"":head.get("LOCNUM").toString());
            if(dtlDTO.get("ITEMNUM")!=null && dtlDTO.get("ITEMNUM").toString().length()>0){
                eamReturnSkuDtl.setMaterialNo(dtlDTO.get("ITEMNUM").toString());
            }else{
                throw new Exception("物料号不能为空！");
            }
            eamReturnSkuDtl.setApplyQtyBasicUnit(dtlDTO.get("RKNUM")==null? 0 : Double.parseDouble(dtlDTO.get("RKNUM").toString()));//新建旧件入库，可入库SPMS数量 申请数量
            eamReturnSkuDtl.setActualQtyBasicUnit(dtlDTO.get("RKNUM")==null? 0 : Double.parseDouble(dtlDTO.get("RKNUM").toString()));//审批数量
            eamReturnSkuDtl.setBasicUnit(dtlDTO.get("ITEMUNIT")==null?"":dtlDTO.get("ITEMUNIT").toString());//入库单位
            eamReturnSkuDtl.setRemarks(dtlDTO.get("REMARKS")==null?"":dtlDTO.get("REMARKS").toString());

            eamReturnSkuDtl.setRknum(dtlDTO.get("RKNUM")==null? 0 : Double.parseDouble(dtlDTO.get("RKNUM").toString()));//回收数量
            eamReturnSkuDtl.setYhnum(dtlDTO.get("YYNUM")==null? 0 : Double.parseDouble(dtlDTO.get("YYNUM").toString()));//应还数量（领料）	EAM推送下来领料单数量，给到仓储参考
            eamReturnSkuDtl.setBfnum(dtlDTO.get("BFNUM")==null? 0 : Double.parseDouble(dtlDTO.get("BFNUM").toString()));//报废数量	EAM推送下来报废数量，给到仓储参考
            eamReturnSkuDtl.setLynum(dtlDTO.get("LYNUM")==null? 0 : Double.parseDouble(dtlDTO.get("LYNUM").toString()));//留用数量	EAM推送下来留用数量，给到仓储参考

            eamReturnSkuDtl.setMovementType("Z551");//移动类型 默认旧件储位发生旧件移动类型：旧件回收入库Z551
            eamReturnSkuDtl.setActualMovementType("Z551");
//            eamReturnSkuDtl.setStorageCode(dtlDTO.get("BINNUM")==null?"":dtlDTO.get("BINNUM").toString());//储位编号
//            eamReturnSkuDtl.setProjectOaNumber(dtlDTO.get("AUFNR")==null?"":dtlDTO.get("AUFNR").toString());//内部订单号

            eamFormerSkuDtlService.save(eamReturnSkuDtl);
        }

        log.info("item save!");

        iOverseaOperateLogService.addOverseaOperateLog("EAM系统", uuidRequisition, REQUISITION_CREATE.getDescZh(), REQUISITION_CREATE.getDescEn(), "", REQUISITION_CREATE.getDescRu());

        //getRequisitionAndDtl(uuidRequisition);
        return ResponseResult.success("旧件申请接口传输成功!");
    }


	@Override
	public ResponseResult eamGetAllStorageInventory(JSONObject doc) throws Exception {
		JSONObject siteObj = doc.getJSONObject("SITE");
		if (siteObj == null) {
			throw new Exception("参数为空，接口调用失败");
		}
		String inWerks = siteObj.getString("SITEID");
		if (StringUtils.isBlank(inWerks)) {
			throw new Exception("工厂参数为空，接口调用失败");
		}
		String[] werksSplit = inWerks.split(",");
		// 根据工厂查询此工厂下的全部储位库存数量
		List<Map<String, Object>> allList = new ArrayList<>();
		for (int i = 0; i < werksSplit.length; i++) {
			String werks = werksSplit[i];
			WerksAllStorageInvSearchDTO dto = new WerksAllStorageInvSearchDTO();
			dto.setWerks(werks);
			List<Map<String, Object>> invM = this.whsStorageInventoryService.getWerksAllStorageInvM(dto);
			allList.addAll(invM);
		}
		return ResponseResult.success("接口调用成功").add("itemList", allList);
	}


	@Override
	public ResponseResult oaReturnOverseaWhsLoss(JSONObject doc) throws Exception {
		String spmsId = doc.getString("spmsId");
		if (StringUtils.isBlank(spmsId)) {
			throw new Exception("SPMS单据号为空，接口调用失败");
		}
		QueryWrapper<OverseaWhsInventoryLoss> query = new QueryWrapper<OverseaWhsInventoryLoss>().eq("SPMS_ID", spmsId);
		OverseaWhsInventoryLoss selectHead = iOverseaWhsInventoryLossService.getOne(query);
		if (selectHead == null) {
			throw new Exception("SPMS单据号："+spmsId+"在SPMS不存在，接口调用失败");
		}
		String status = doc.getString("status");
		OverseaWhsInventoryLoss updateVO = new OverseaWhsInventoryLoss();
		updateVO.setUuid(selectHead.getUuid());
		updateVO.setUpdateTime(new Date());
		if ("S".equals(status)) {
			// 审批通过
			updateVO.setSpmsStatus(OverseaWhsInventoryLossEnum.OA_APPROVED.getCode());
			updateVO.setOaApprovalDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
		} else {
			// 审批拒绝
			updateVO.setSpmsStatus(OverseaWhsInventoryLossEnum.OA_APPROVAL_RETURN.getCode());
		}
		iOverseaWhsInventoryLossService.updateById(updateVO);
		return ResponseResult.success("接口调用成功");
	}

}


