MT8204ServiceImp.java 8.7 KB
package com.tianbo.analysis.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianbo.analysis.dao.MANIFEST_AIR_CHANGEMapper;
import com.tianbo.analysis.dao.SENDLOGMapper;
import com.tianbo.analysis.model.*;
import com.tianbo.analysis.service.MT8204Service;
import com.tianbo.util.Date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.springframework.util.ResourceUtils;
import org.apache.commons.io.FileUtils;
import com.tianbo.analysis.model.CustomsHead;
import org.thymeleaf.exceptions.TemplateInputException;
import org.xml.sax.SAXException;

import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;


@Service
@Slf4j
public class MT8204ServiceImp implements MT8204Service {

    @Resource
    MANIFEST_AIR_CHANGEMapper manifest_air_changeMapper;

    @Resource
    SENDLOGMapper sendlogMapper;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${customs.xml-path}")
    private String saveXmlDir;


    @Value("${customs.transport-number}")
    private String transportNo;

    @Override
    public PageInfo<MANIFEST_AIR_CHANGE> selectList(MANIFEST_AIR_CHANGE record, int pageNum, int pageSize){

        Page<MANIFEST_AIR_CHANGE> page =  PageHelper.startPage(pageNum,pageSize);
        List<MANIFEST_AIR_CHANGE> list =  manifest_air_changeMapper.selectList(record);
        PageInfo<MANIFEST_AIR_CHANGE> result = new PageInfo<MANIFEST_AIR_CHANGE>(list);
        return result;
    }

    @Override
    public List<MANIFEST_AIR_CHANGE> selectListByAutoIDS(List<String> autoIDlist){
        List<MANIFEST_AIR_CHANGE> list =  manifest_air_changeMapper.selectListByAutoIDS(autoIDlist);
        return list;
    }

    @Override
    public boolean add(MANIFEST_AIR_CHANGE record) {
        if (record.getWaybillList()!=null && !record.getWaybillList().isEmpty()){
            int i=0;
            for (String waybillNo : record.getWaybillList()) {
                MANIFEST_AIR_CHANGE manifest_air_change = new MANIFEST_AIR_CHANGE();
                manifest_air_change = record;
                manifest_air_change.setWaybillnomaster(waybillNo);
                manifest_air_change.setChangeWaybillnomaster(waybillNo);
                manifest_air_change.setAutoid(UUID.randomUUID().toString());

                //TODO:插入前的重复校验
                if (add_checkRpeat(manifest_air_change)){
                    i =+ manifest_air_changeMapper.insertSelective(manifest_air_change);
                }else {
                    log.info("运单号{}存在直接改配申请",manifest_air_change.getWaybillnomaster());
                }
                log.info(String.valueOf(i));
            }
            return i>0;
        }else {
            if (add_checkRpeat(record)){
                record.setAutoid(UUID.randomUUID().toString());
                return manifest_air_changeMapper.insertSelective(record)>0;
            }else {
                log.info("运单号{}存在直接改配申请",record.getWaybillnomaster());
            }
            return false;
        }
    }
    boolean add_checkRpeat(MANIFEST_AIR_CHANGE manifest_air_change){
        //TODO:插入前的重复校验
        List<MANIFEST_AIR_CHANGE> l = manifest_air_changeMapper.insertCheckRepeat(manifest_air_change);
        return l.isEmpty();
    }
    @Override
    public boolean edit(MANIFEST_AIR_CHANGE record) {
        if (StringUtils.isNotEmpty(record.getAutoid())){
            return manifest_air_changeMapper.updateByPrimaryKeySelective(record)>0;
        }
        return false;
    }

    @Override
    public boolean del(MANIFEST_AIR_CHANGE record) {
        if (StringUtils.isNotEmpty(record.getAutoid())){
            return manifest_air_changeMapper.deleteByPrimaryKey(record.getAutoid())>0;
        }
        return false;
    }

    @Override
    public boolean send(MANIFEST_AIR_CHANGE record,String username) {
        try{
            record.setWaybillnomaster(record.getWaybillnomaster().replace("-",""));
            record.setChangeWaybillnomaster(record.getChangeWaybillnomaster().replace("-",""));
            CustomsHead customsHead = new CustomsHead();

            //从配置文件读取

            String nowStr = DateUtil.getCurrentTime17();
            String messageID = "CN_"
                    + "MT8204"
                    + "_1P0_"
                    + transportNo+
                    "_" + nowStr;

            Context context = new Context();
            context.setVariable("body",record);
            context.setVariable("head",customsHead);
            context.setLocale(Locale.SIMPLIFIED_CHINESE);

            customsHead.setMessageId(messageID);
            customsHead.setSendTime(nowStr);

            //生成的文件名
            String fileName = messageID + ".xml";
            //生成的报文路径,带斜杠
            String filePath = saveXmlDir+fileName;
            File file = ResourceUtils.getFile(filePath);
            /**
             * 中文的地方在模板中要用utext,否则中文会被 escape 转义
             */
            String xmlStr = templateEngine.process("mt8204/MT8204",context);

            boolean valied =  validateXMLSchema("xsd/Manifest_Change_Transport_Air_8204_2.xsd",xmlStr);
            if (valied){
                FileUtils.writeStringToFile(file,xmlStr, StandardCharsets.UTF_8);
                SENDLOG sendlog = new SENDLOG();
                sendlog.setAutoid(UUID.randomUUID().toString());
                sendlog.setMessageautoid(record.getAutoid());
                sendlog.setMessagetype("MT8204");
                sendlog.setCreatedate(new Date());
                StringBuilder sb = new StringBuilder("已申请直接改配,改配后信息")
                        .append(record.getChangeWaybillnomaster())
                        .append("/")
                        .append(record.getChangeFlightno())
                        .append("/")
                        .append(DateUtil.dateToString(record.getChangeFlightDate(),"yyyyMMdd"));
                sendlog.setReceiption(sb.toString());
                sendlog.setOpauthor(username);
                sendlogMapper.insertSelective(sendlog);
                return true;
            }else {
                return false;
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }catch (TemplateInputException e){
            return false;
        }
    }

    @Override
    public ResultJson batchSend(List<String> autoIDlist, String username) {
        ResultJson resultJson = new ResultJson();
        String message = "";
        List<MANIFEST_AIR_CHANGE> list = selectListByAutoIDS(autoIDlist);
        for (MANIFEST_AIR_CHANGE manifestAirChange : list) {
            boolean result = send(manifestAirChange,username);
            if (!result){
                message = message + manifestAirChange.getWaybillnomaster() +"发送失败\n";
            }
        }
        resultJson.setCode("200");
        resultJson.setMsg(message);
        return  resultJson;

    }

    public boolean validateXMLSchema(String xsdPath, String xmlStr) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
        try {
            SchemaFactory factory =
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();

            Source source = new StreamSource(bais);
            validator.validate(source);
        } catch (IOException | SAXException e) {
            e.printStackTrace();
            log.error("Exception:{}",e.getMessage());
            return false;
        }finally {
            bais.close();
        }
        return true;
    }
}