ChmConsignmentService.java 15.2 KB
package com.erry.iclear.dateInterface.service;

//import cn.hutool.core.date.DateUtil;
import com.erry.iclear.dateInterface.api.request.Mawb;
import com.erry.iclear.dateInterface.api.response.ResultRS;
import com.erry.iclear.dateInterface.common.Constant;
import com.erry.iclear.dateInterface.entity.ChmCarryPort;
import com.erry.iclear.dateInterface.entity.ChmConsignment;
import com.erry.iclear.dateInterface.entity.ChmConsignmentDetail;
import com.erry.iclear.dateInterface.entity.DictionaryEntries;
import com.erry.iclear.dateInterface.repository.ChmConsignmentRepository;
import com.erry.iclear.dateInterface.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Slf4j
@Transactional(rollbackOn = Exception.class)
public class ChmConsignmentService {

    @Autowired
    private ChmConsignmentRepository chmConsignmentRepository;

    @Autowired
    private ChmConsignmentDetailService chmConsignmentDetailService;

    /**
     * 转换主单
     * @return
     */
    public ChmConsignment convertToChmConsignment(Mawb mawb,Date pushTime,String creator){
        ChmConsignment result = new ChmConsignment();
        try{
            //进出口标志:固定值	E
            //TODO 报关类型:填写固定值EX,但字典表里没有这个值
//            result.setDeclaredDocTypeDic();
//            result.setDeclaredCode();
            //申报单位代码:固定值	1111980005
            result.setDeclaredUnitName(mawb.getAgentName());
            //申报单位名称:固定值	联邦快递(中国)有限公司
            //提单号:有总单号则取值“总单号_运单号”,没有总单号则取值“运单号”
            String[] billNo=mawb.getBillNo().split("_");
            if(billNo.length==1){
                result.setConsignmentCode(billNo[0]);
            }
            if(billNo.length==2){
                result.setConsignmentHeadCode(billNo[0]);
                result.setConsignmentCode(billNo[1]);
            }

            //合同号
            result.setContractCode(mawb.getContrNo());
            //主管海关(申报地海关)
            result.setCustomsNo(mawb.getCustomMaster());
            //征免性质
            DictionaryEntries levyTypeDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.NATURE_EXEMPTION+mawb.getCutMode());
            result.setTaxNatureDic(levyTypeDictionaryEntries);
            result.setTaxNature(levyTypeDictionaryEntries.getChineseName());
            //报关/转关关系标志:固定值0  ,但数据字典里没有0


            //经停港/指运港
            ChmCarryPort chmCarryPort =Constant.chmCarryPortCache.get(mawb.getDistinatePort());
            result.setThroughStopPortDic(chmCarryPort);
            result.setThroughStopPort(chmCarryPort.getPortNo());

            //TODO 报关标志【待确认】
            DictionaryEntries declaredDocTypeDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.DECLARED_DOC_TYPE + mawb.getEdiId());
            result.setDeclaredDocTypeDic(declaredDocTypeDictionaryEntries);
            result.setDeclaredDocType(declaredDocTypeDictionaryEntries.getChineseName());

            //海关编号
            result.setCustomsNo(mawb.getEntryId());
            //运费币制
            DictionaryEntries currencyDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.CURRENCY_SYSTEM+mawb.getFeeCurr());
            result.setTransCurrencyDic(currencyDictionaryEntries);
            result.setTransCurrency(currencyDictionaryEntries.getChineseName());

            //TODO 运费标记:固定值	3 【iclear中, 和成交方式相关,只有成交方式 1、2 时,才能传 3 】


            //运费总价
            result.setTransCost(mawb.getFeeRate());
            //毛重
            result.setGrossWeight(BigDecimal.valueOf(mawb.getGrossWet()));
            //出入境关闭:固定值	0101
            //录入人名称:固定值	必填项,但填的值是空值

            //保险费币制
            DictionaryEntries insuranceDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.CURRENCY_SYSTEM+mawb.getInsurCurr());
            result.setInsuranceCostCurrencyDic(insuranceDictionaryEntries);
            result.setInsuranceCostCurrency(insuranceDictionaryEntries.getChineseName());

            //保险费标记 ,根据transMode决定

            //保险费/率
            result.setInsuranceCost(mawb.getInsurRate());
            //备案号
            result.setRecordCode(mawb.getManualNo());
            //净重
            result.setNetWeight(mawb.getNetWt());
            //杂费币制
            DictionaryEntries otherDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.CURRENCY_SYSTEM+mawb.getOtherCurr());
            result.setOtherCurrencyDic(otherDictionaryEntries);
            result.setOtherCurrency(otherDictionaryEntries.getChineseName());
            //杂费/率
            result.setOtherCost(mawb.getOtherRate());
            //杂费标志
            //TODO 消费使用/生产销售单位代码
            result.setOwnerCode(mawb.getOwnerCode());
            //TODO 消费使用/生产销售单位名称
            result.setOwnerName(mawb.getOwnerName());


            //件数
            result.setCounts(mawb.getPackNo().longValue());
            //预录入编号
            result.setEnteringNo(mawb.getPreEntryId());
            //启运国/运抵国
            DictionaryEntries fromCountryDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.COUNTRY+mawb.getTradeCountry());
            result.setFromCountryDic(fromCountryDictionaryEntries);
            result.setFromCountry(fromCountryDictionaryEntries.getChineseName());


            //监管方式
            DictionaryEntries tradeModeDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.SUPERVISION_MODE+mawb.getTradeMode());
            result.setTradeModeDic(tradeModeDictionaryEntries);
            result.setTradeMode(tradeModeDictionaryEntries.getChineseName());


            //境内收发货人编号
            result.setTradeCoSCC(mawb.getTradeCode());
            //运输方式代码
            DictionaryEntries vehicleWayDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.VEHICLE_WAY_CODE+mawb.getTrafMode());
            result.setVehicleWay(vehicleWayDictionaryEntries);
            result.setVehicleWayCode(vehicleWayDictionaryEntries.getCode());

            //境内收发货人名称
            result.setOperateUnitName(mawb.getTradeName());
            //成交方式
            DictionaryEntries dealModeDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.CLINCH_TYPE+mawb.getTransMode());
            result.setDealModeDic(dealModeDictionaryEntries);
            result.setDealMode(dealModeDictionaryEntries.getChineseName());

            //包装种类
            DictionaryEntries packageTypeDictionaryEntries = Constant.dictionaryEntriesCache.get(Constant.NEW_PACKAGE_TYPE+mawb.getWrapType());
            result.setPackageTypeDic(packageTypeDictionaryEntries);
            result.setPackageType(packageTypeDictionaryEntries.getChineseName());


            //TODO 生产核销单位统一信用代码---报关形式类型
            result.setTradeCoSCC(mawb.getTradeCodeScc());


            //TODO 消费使用/生产销售单位单位统一编码
            result.setOwnerCodeScc(mawb.getOwnerCodeScc());


            //贸易国别
            DictionaryEntries tradeAreaCodeDictionaryEntries=Constant.dictionaryEntriesCache.get(Constant.COUNTRY+mawb.getTradeAreaCode());
            result.setTradeAreaCodeDic(tradeAreaCodeDictionaryEntries);
            result.setTradeAreaCode(tradeAreaCodeDictionaryEntries.getChineseName());

            //标记及号码
            result.setDeclaredRemark(mawb.getMarkNo());

            //入境口岸代码:固定值	310302

            //存放地点:固定值	空值

            //申报人员姓名---报关员证号
            result.setDeclaredUnitName(mawb.getDeclareName());
            //境外发货人代码

            //境外收货人编码
            result.setOverseasConsignorCode(mawb.getOverseasConsigneeCode());
            //境外收货人名称(外文)
            result.setOverseasConsignorFnCname(mawb.getOverseasConsigneeEname());


            //运单状态: 待申报海关
            DictionaryEntries transferWaybillStatusDictionaryEntries=Constant.dictionaryEntriesCache.get(Constant.TRANSFER_WAY_BILL_STATUS+"5");
            result.setConsStatusDic(transferWaybillStatusDictionaryEntries);
            result.setConsStatus(transferWaybillStatusDictionaryEntries.getChineseName());
            //推送时间作为创建时间,可以用来校验数据的有序性,如果新的推送时间小于已有的创建时间,就不更新数据
            result.setCreateTime(new Date());
            result.setUpdateTime(pushTime);
            result.setCreator(creator);

        }catch (Exception e){
            result=null;
            e.printStackTrace();
            log.error("convertToChmConsignment() error:"+e.getMessage());
        }
        return result;
    }


    /**
     * 保存主单
     * @param chmConsignment
     * @return
     */
    public ChmConsignment saveChmConsignment(ChmConsignment chmConsignment){
        try{
            return chmConsignmentRepository.save(chmConsignment);
        }catch (Exception e){
            log.error("saveChmConsignment() error:"+e.getMessage());
        }
        return null;
    }


    /**
     * 保存主单
     * @param chmConsignment
     * @return
     */
    public ChmConsignment updateChmConsignment(ChmConsignment chmConsignment){
        try{
            return chmConsignmentRepository.save(chmConsignment);
        }catch (Exception e){
            log.error("updateChmConsignment() error:"+e.getMessage());
        }
        return null;
    }









    /**
     * 根据运单号查找数据
     * @param consignmentCode
     * @return
     */
    public ChmConsignment findChmConsignmentByConsignmentCode(String consignmentCode, Date startDate){
        try {
            return chmConsignmentRepository.findChmConsignmentByConsignmentCode(consignmentCode,startDate);
        }catch (Exception e){
            log.error("findChmConsignmentByConsignmentCode() error:"+ e.getMessage());
        }
        return null;
    }


    /**
     * 保存或更新 iclear中的运单信息
     * @param mawb
     * @param timeStamp
     */
    public ResultRS processChmConsignment(Mawb mawb, String timeStamp, String creator) {
        ResultRS result = new ResultRS(Boolean.FALSE,null,null);
        try {
            Date pushTime = DateUtils.timeStampToDate(Long.valueOf(timeStamp));

            //1、将请求转换为运单
            ChmConsignment chmConsignment=this.convertToChmConsignment(mawb,pushTime,creator);
            if(Objects.equals(chmConsignment,null)){
                result.setCode("30001");
                result.setMsg("数据格式不正确");
                return result;
            }
            List<ChmConsignmentDetail> chmConsignmentDetailList = new ArrayList<>();
            mawb.getMawbDetailList().forEach(detail ->{
                chmConsignmentDetailList.add(chmConsignmentDetailService.convertToChmConsignmentDetail(detail,chmConsignment));
            });
            chmConsignment.setChmConsignmentDetailList(chmConsignmentDetailList);


            //2、校验 7天+运单 ,如果有数据并且 还未报关就更新,如果数据就插入
            ChmConsignment chmConsignmentDB=this.findChmConsignmentByConsignmentCode(mawb.getBillNo(), DateUtils.addDate(DateUtils.getCurrentDate(),-7));


            //3、新增或更新
            //新增:如果没有就插入
            if (Objects.equals(chmConsignmentDB,null)){
                log.info("新增主单"+ mawb.getBillNo());
                ChmConsignment chmConsignmentSaveResult = this.saveChmConsignment(chmConsignment);
                if(!Objects.equals(chmConsignmentSaveResult,null)){
                    log.info("主单"+ mawb.getBillNo()+" 保存成功,chmConsignmentId:"+chmConsignmentSaveResult.getId());
                }else{
                    log.info("主单"+ mawb.getBillNo()+" 保存失败");
                    result.setCode("30002");
                    result.setMsg("主单"+ mawb.getBillNo()+" 保存失败");
                    return result;
                }
                //更新:
                //如果有数据并且满足条件后才能更新数据
                //条件1、状态为 待申报海关
                //条件2、本次推送时间 > 上次推送的时间
            }else if(!Objects.equals(chmConsignmentDB,null)
                    && Objects.equals(chmConsignmentDB.getConsStatusDic().getCode(),"transferWaybillStatus_5")
                    //TODO 提交时需要打开
                    && pushTime.getTime()>chmConsignmentDB.getUpdateTime().getTime()
                    ){
                //更新数据
                log.info("更新主单"+ mawb.getBillNo());


                //由于订单明细中,无法确定唯一一条数据,所以无法做到update,只能先删除在插入
//                for(ChmConsignmentDetail newDetail:chmConsignment.getChmConsignmentDetailList()){
//                    for(ChmConsignmentDetail oldDetail: chmConsignmentDB.getChmConsignmentDetailList()){
//                        if(Objects.equals(newDetail.getSkuCode(),oldDetail.getSkuCode())){
//                            //newDetail.setChmConsignment(chmConsignmentDB);
//                            newDetail.setId(oldDetail.getId());
//                        }
//                    }
//                }
                List<Long> detailIdList = new ArrayList();
                chmConsignmentDB.getChmConsignmentDetailList().forEach(detail->{
                    detailIdList.add(detail.getId());
                });
                if(detailIdList.size()>0){
                    chmConsignmentDetailService.deleteChmConsignmentDetailBatch(detailIdList);
                    chmConsignmentDB.setChmConsignmentDetailList(null);
                }

                chmConsignment.setId(chmConsignmentDB.getId());
                chmConsignment.setCreateTime(chmConsignmentDB.getCreateTime());
                chmConsignment.setUpdateTime(pushTime);
                ChmConsignment updateResult = this.saveChmConsignment(chmConsignment);
                if(!Objects.equals(updateResult,null)){
                    log.info("主单"+ mawb.getBillNo()+" 更新成功,chmConsignmentId:"+updateResult.getId());
                }else{
                    log.info("主单"+ mawb.getBillNo()+" 更新失败");
                    result.setCode("30003");
                    result.setMsg("主单"+ mawb.getBillNo()+" 更新失败");
                    return result;
                }
            }
        }catch (Exception e){
            log.error(""+e.getMessage());
        }

        result.setSuccess(Boolean.TRUE);
        return result;
    }


















}