package com.sy.logic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sy.crossDomain.buildBarCode;
import com.sy.model.*;
import com.sy.relation.VeManifestRelation;
import com.sy.service.*;
import com.sy.socket.CommandClient;
import com.sy.utils.FileTool;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.apache.log4j.Logger;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import static com.sy.service.impl.ResMessageServiceImpl.toStrArry;


@Component
public class LiftBar {
    private static final Logger logger = Logger.getLogger(LiftBar.class);
    private static final org.slf4j.Logger log4 = org.slf4j.LoggerFactory.getLogger(LiftBar.class);
    @Autowired
    private LandBusListService listService;//进出场申请表
    @Autowired
    private LandRoadVeService veService;//车辆信息备案表
    @Autowired
    private ResMessageService resMessageService;//查询运单放行表
    @Autowired
    private EnterCancelServer enterCancelServer;//调拨业务单独记录表
    @Autowired
    private BusnesslistinfoService busnesslistinfoService;
    @Autowired
    BusnessViewService busnessViewService;
    @Autowired
    CommandLogService commandLogService;

    @Autowired
    WeightCheckHandleService weightCheckHandleService;

    @Value("${wharf.interface.host}")
    private String wharfHost;

    @Value("${nmms.interface.host}")
    private String nmmsHost;

    private static LiftBar logic;

    //逻辑判断后的返回信息定义
    private static String PERMITTHOUGH = "直接放行";
    private static String GROWSSEXCETION = "禁止通行,重量不在可控范围";
    private static String NORECORD = "车辆未备案或者识别错误,车牌号:";
    private static String NO_CHEPAI = "未识别到车牌号:";
    private static String INPUTSTATION = "此车辆未做进站申请";
    private static String ENTERSTATION = "此车辆未做出站申请";
    private static String ISVALID = "二维码数据异常,请使用正确的二维码数据";
    private static String ERRORWT = "出起始场站的重量和进目的场站的重量不一致";
    private static String IEPORSE = "无相对应进出场申请";
    private static String FANGXING="有运单未放行";
    private static String FENBO = "装载运单的分拨申请舱单未通过校验";
    private static String NOGrossWt = "过磅重量异常";
    private static String BLACKLIST="此车辆已被拉进黑名单,不允许出区";


    //分拨申请回执
    private static String ALLOCATE_01 = "39301 分拨申请审核通过。";
    private static String ALLOCATE_04 = "39103 分拨申请重复传输,海关审核不通过。";

    //初始化装载货物重量
    private double goodsWt=0.0,inWt=0.0,diffVal=0.0,selfWt=0.0;
    private List<LAND_BUSINEESTYPE_LIST_INFO> listinfos;

    @Autowired
    private FeignService feignService;

    @Autowired
    private NmmsService nmmsService;

    @PostConstruct
    public void init() {
        logic = this;
        logic.listService = this.listService;
        logic.veService = this.veService;
        logic.resMessageService = this.resMessageService;
        logic.enterCancelServer = this.enterCancelServer;
        logic.feignService=this.feignService;
        logic.busnesslistinfoService=this.busnesslistinfoService;
        logic.busnessViewService=this.busnessViewService;
        logic.weightCheckHandleService=this.weightCheckHandleService;
        logic.wharfHost=this.wharfHost;
        logic.nmmsHost=this.nmmsHost;
        logic.feignService=this.feignService;
        logic.nmmsService=this.nmmsService;
        logic.commandLogService=this.commandLogService;
    }

    /**
     * @Param info 卡口采集数据
     * @Result 计算卡口采集数据并发送报文
     */
    public  boolean liftBar(GatherInfo info) throws InterruptedException {
        PropertyConfigurator.configure("config/log4j.properties");
        //默认返回值
        boolean result = false;
        //获取过磅重量
        double growssWt = info.getGrosswt().doubleValue();

        //取车牌号,判定卡口是否取到车牌号
        String vaName = info.getVename();

        //1. 若无车牌号,返回未识别错误
        if (vaName.length() <= 0) {
            logger.error(NO_CHEPAI+vaName);
            sendBw(info,false,NO_CHEPAI + vaName,new LandBusinessTypeList(),listinfos);
            //CommandClient.Client(info, NO_CHEPAI + vaName);
            return result;
        }

        //2. 校验车辆是否备案
        LandRoadVe ve = logic.veService.selectByFrameNo(vaName);
        //若无备案信息,返回车辆未备案或者识别错误
        if (ve == null) {
            logger.error(NORECORD+vaName);
            sendBw(info,false,NORECORD + vaName,new LandBusinessTypeList(),listinfos);
            //CommandClient.Client(info, NORECORD + vaName);
            return result;
        }
        if("Y".equals(ve.getVeState())){
            logger.info(BLACKLIST+vaName);
            sendBw(info,false,BLACKLIST + vaName,new LandBusinessTypeList(),listinfos);
            return result;
        }
        selfWt=Double.parseDouble(ve.getSelfWt());//车辆备案我不是
        if(info.getGrosswt().compareTo(BigDecimal.ZERO)==1){
            logger.info("过磅重量校验通过,过磅重量大于0");
        }else{
            sendBw(info,false,NOGrossWt + growssWt,new LandBusinessTypeList(),listinfos);
            return false;
        }

        /**
         * 3. 车牌号,二维码,场站ID/号,通道ID/号,进出业务类型标识I/E
         * 查询是否已有此场站通道的申请
         */
        //通过车牌号,二维码,场站,通道号,进出类型查询进出场站申请列表
        LandBusinessTypeList list = logic.listService.selectForOne(info.getVename(), info.getBarcode(), info.getAreaid(), info.getChnlno(), info.getIetype());
        //4. 若查询结果为null,返回无相对应进出场申请
        if (list == null) {
            logger.error(vaName+IEPORSE);
            sendBw(info,false,vaName+IEPORSE,list,listinfos);
            //CommandClient.Client(info, IEPORSE);
            return result;
        }

        //5. 判断进出场申请二维码是否已经失效,若失效,sendError ,0 未失效
        if ("0".equals(list.getIsvalid())) {
            //6. 校验重量开始
            boolean checkResult = false;
            boolean check = false;
            boolean checkMainfest =false;
            //查询运单列表
            listinfos=logic.busnesslistinfoService.selectmanilist(info.getBarcode());
            //7. 判断是进场申请还是出场申请
            if("I".equals(info.getIetype())){
                //进场申请宽进
                checkResult=true;
            } else {
                //出场判定

                //进出场重量差值计算
                //获取对应场站进场申请的货物重量,进场过磅重量,
                List<LandBusinessTypeList> listWt=logic.listService.selectwt(list.getTrailerFrameNo(),list.getBarcode(),list.getEndstation(),"I");
                for(LandBusinessTypeList typeList:listWt){
                    if(StringUtils.isNotEmpty(typeList.getRemark())){
                        //货物重量
                        goodsWt=Double.parseDouble(typeList.getRemark());
                    }
                    if(typeList.getAislewt()!=null){
                        //对应场站进场过磅重量
                        inWt=typeList.getAislewt();
                    }
                    diffVal = inWt- growssWt;
                }
                if (Double.doubleToLongBits(goodsWt)==Double.doubleToLongBits(0.0)){
                    goodsWt = Double.parseDouble(list.getRemark());
                }
                //TODO:进场校验 增加 车辆备案重量要 <= 进场过磅重量 ,要有误差判定

                log4.info("[CHECK-INFO]-出场过磅重量:{}-申报装载货物重量:{}-入场过磅重量:{}-进出差值:{}-车重:{}",growssWt,goodsWt,inWt,diffVal,ve.getSelfWt());

                //判断场站出场是否要重量校验,配置文件中配置的场站直接抬杆放行.
                if(FileTool.readProperties("stationsf").equals(list.getEndstation())){
                    checkResult=true;
                //货物类型判断,直接放行的.todo:这个逻辑比较强大,后期要看怎么处理
                }else if(!"普通货物".equals(list.getCocode())
                        && !"转关货物".equals(list.getCocode())
                        && !"退库货物".equals(list.getCocode()) ){
                    //todo:比如货物类型为快件货物,只走重量校验,不走放行信息等校验.
                    //todo:退库货物可以关联货运系统,得到退库信息进行比对
                    //todo:查验货物走查验信息比对
                    //todo:快件暂不校验直接放行,不过得录单
                    //todo:换单货物校验逻辑待定
                    //todo:未来取消货物类型判定.
                    logger.info("车辆装载货物为:"+list.getCocode());
                    checkResult=true;
                }else {
                    /**
                     * 因为货代老是进场后修改提货运单信息,造成申请单的进场货重与离场货重不匹配
                     * 进口提货,货物重量取进场提货的货物重量
                     */
                    goodsWt = Double.parseDouble(list.getRemark());
                    // 出场校验根据业务类型
                    logger.info("[进出场申请]-业务类型为:"+list.getCocode()+list.getBusinesstype());
                    switch (list.getBusinesstype()){
                        case "空车业务":
                            if(logic.weightCheckHandleService.checkEmpty(growssWt,selfWt)){
                                checkResult=true;
                            }else{
                                logger.error("[空车业务]-出场重量未通过校验:"+GROWSSEXCETION);
                                sendBw(info,false,GROWSSEXCETION,list,listinfos);
                                return false;
                            }
                            break;
                        case "出口转关":
                        case "出口送货":
                            if (logic.weightCheckHandleService.checkExportDownLoading(growssWt, Double.parseDouble(ve.getSelfWt()), goodsWt,inWt)){
                                checkResult=true;
                            }else{
                                logger.error("[出口送货]-出场重量未通过校验:"+GROWSSEXCETION);
                                sendBw(info,false,GROWSSEXCETION,list,listinfos);
                                //CommandClient.Client(info, GROWSSEXCETION);
                                return false;
                            }
                            break;
                        case "进口转关":
                        case "进口提货":
                            if (logic.weightCheckHandleService.checkImportDlv(growssWt, Double.parseDouble(ve.getSelfWt()), goodsWt,inWt)){
                                checkResult=true;
                                if ("退库货物".equals(list.getCocode())){
                                    /**
                                     * 退库货物不校验运单放行.
                                     */
                                    log4.info("[退库业务]-重量核验通过.");
                                }else{
                                    //检查运单放行
                                    if (logic.resMessageService.checkManifestRelease(info,listinfos)){
                                        checkResult=true;
                                    }else {
                                        //有运单未放行
                                        logger.error("[进口提货]-出场未通过校验:"+FANGXING+list.getMasterList());
                                        sendBw(info,false,FANGXING+list.getMasterList(),list,listinfos);
                                        //CommandClient.Client(info, FANGXING);
                                        return false;
                                    }
                                }
                                //todo:装载运单历史数据累加超重判定
                            }else{
                                logger.error("[进口提货]-出场重量未通过校验:"+GROWSSEXCETION);
                                sendBw(info,false,GROWSSEXCETION,list,listinfos);
                                //CommandClient.Client(info, GROWSSEXCETION);
                                return false;
                            }
                            break;
                        case "分拨业务":
                            if (logic.weightCheckHandleService.checkAllocateOrDispatch(growssWt, Double.parseDouble(ve.getSelfWt()), goodsWt,inWt)){
                                //todo:检查分拨申请
                                boolean allocatCheck = checkNmmsAllocate(list.getMasterList());
                                if(!allocatCheck){
                                    logger.error("[分拨业务]-分拨申请舱单未通过校验:"+FENBO);
                                    sendBw(info,false,FENBO,list,listinfos);
                                    //CommandClient.Client(info, FENBO);
                                    return false;
                                }
                                checkResult=true;
                                //todo:分拨运抵通知,重车入场视为运抵
                            }else{
                                logger.error("[分拨业务]-出场重量未通过校验:"+GROWSSEXCETION);
                                sendBw(info,false,GROWSSEXCETION,list,listinfos);
                                //CommandClient.Client(info, GROWSSEXCETION);
                                return false;
                            }
                            break;
                        case "调拨业务":
                            if (logic.weightCheckHandleService.checkAllocateOrDispatch(growssWt, Double.parseDouble(ve.getSelfWt()), goodsWt,inWt)){
                                checkResult=true;
                                //检查运单放行
                                if (logic.resMessageService.checkManifestRelease(info,listinfos)){
                                    checkResult=true;
                                }else {
                                    //有运单未放行
                                    logger.error("[调拨业务]-出场未通过校验:"+FANGXING+list.getMasterList());
                                    sendBw(info,false,FANGXING,list,listinfos);
                                    //CommandClient.Client(info, FANGXING);
                                    return false;
                                }
                                //todo:检查ULD放行.
                            }else{
                                logger.error("[调拨业务]-出场未通过校验:"+GROWSSEXCETION);
                                sendBw(info,false,GROWSSEXCETION,list,listinfos);
                                //CommandClient.Client(info, GROWSSEXCETION);
                                return false;
                            }
                            break;
                        default:
                            checkResult=false;
                            break;
                    }


                    //旧业务逻辑,不启用了
//                    check = logic.weightCheckHandleService.checkResult(growssWt, Double.parseDouble(ve.getSelfWt()), goodsWt,inWt);
//                    if("出口送货".equals(list.getBusinesstype())){
//                        if(check){
//                            checkResult=true;
//                        }else{
//                            CommandClient.Client(info, GROWSSEXCETION);
//                        }
//                    }else{
//                        //其他业务的装载运单放行判断
//                        checkMainfest = logic.checkManifest(list.getMasterList());
//                        if(checkMainfest){
//                            checkResult=check || checkMainfest;
//                        }else{
//                            CommandClient.Client(info, FANGXING);//有运单未放行
//                        }
//                    }


                }

            }

            //发送抬杆指令,todo:生产环境去掉下面注释
            boolean commandResult = sendBw(info, checkResult,PERMITTHOUGH,list,listinfos);
            //fortest 正式环境删除
//            boolean commandResult = true;
            if(commandResult){//发送抬杆儿报文
                if ("I".equals(info.getIetype())) {
                    //过卡重量
                    list.setAislewt(info.getGrosswt().doubleValue());
                    list.setUpdateDate(new Date());
                    //list.setRemark(String.format("%.1f", goodsWt));
                    //车辆备案重量
                    list.setRemark2(ve.getSelfWt());
                    list.setContrastflag("已进站");
//                    logic.checkData(list);
                } else {
                    LandRoadVe veName = logic.veService.selectByFrameNo(vaName);
                    list.setAislewt(info.getGrosswt().doubleValue());
                    list.setUpdateDate(new Date());
                    //装载货物总重量
                    list.setRemark(String.format("%.1f", goodsWt));
                    //进出差值
                    list.setRemark1(String.format("%.1f", diffVal));
                    list.setRemark2(veName.getSelfWt());
                    list.setContrastflag("已出站");
//                    logic.checkData(list);
                }

                //更新进出场申请业务表
                logic.listService.updateById(list);

                //进出场申请业务表对应场站的卡口失效
                if("I".equals(info.getIetype())){
                    logic.listService.updateisvalid(list.getTrailerFrameNo(),list.getBarcode(),list.getEndstation(),list.getTurnoverflag());
                }else{
                    logic.listService.updateisvalid(list.getTrailerFrameNo(),list.getBarcode(),list.getEndstation(),null);
                }

                //判断是否为最后一个场站,若是最后个场站申请为出,二维码失效
                int count=logic.listService.selectlaststation(list.getTrailerFrameNo(),list.getBarcode());
                //二维码失效
                if(count==0){
                    //todo:测试注释掉,二维码释放
                    logger.info("[进出场申请]-二维码释放:"+vaName);
                    buildBarCode.cancleBarCode(vaName);
                }

                /**
                * 提前运抵判断
                * 如果有提前运抵标识,判断是否分批,不分批直接通知
                 * 分批是否最后一批,最后一批通知
                * */
                /*if("I".equals(info.getIetype())){
                    try{
                        List<LAND_BUSINEESTYPE_LIST_INFO> arrive_infos=logic.busnesslistinfoService.selectarrvie(info.getBarcode());//查询是否提前运抵
                        if(arrive_infos!=null && arrive_infos.size()>0){
                            for (LAND_BUSINEESTYPE_LIST_INFO businees:arrive_infos) {
                                //判断运单是否分批
                                if ("0".equals(businees.getPartialidentity())){
                                    logger.info("运单号{}不分批,不从通知数组删除");
                                }else { //分批后的处理
                                    List<businesstypelistinfo_view> info_view=logic.busnessViewService.selectawb(businees.getAwba());
                                    // 装载运单的分批车辆还有未入场的,从通知数组中删除他
                                    if (info_view.size()>0){
                                        arrive_infos.remove(businees);
                                    }
                                }
                            }
                            //最后发送通知数组
                            try{
                                new LiftBar().sendMessage(info.getVename(),arrive_infos);
                            }catch (Exception e){
                               logger.info("新舱单发送消息异常---"+e.toString());
                            }
                        }
                    }catch (Exception e){
                        logger.info("运单分批消息异常---"+e.toString());
                    }
                }*/
                //调拨货冻结
                /*if (list.getBusinesstype().indexOf("业务") > 0) {
                    logic.inOrUpEnterCancel(list);
                }*/
            }

            //绑定车单关系,生成车单关系报文
            if(list.getMasterList().length()>0){
                boolean flag = VeManifestRelation.createFile(list);
                if(flag){
                    logger.info(">>>>>>>>>>-----车单关系报文生成成功-----<<<<<<<<<<<<");
                }
            }

        } else {
            logger.error("------->>>>>>>二维码数据异常,请使用正确的二维码数据<<<<<<<-----");
            sendError(info);
            return false;
        }
        return true;
    }


    /**
     * 校验重量后并发送抬杆指令报文
     * @param info 车辆过卡信息
     * @param check 是否放行抬杆
     */
    public boolean sendBw(GatherInfo info, boolean check,String reason,LandBusinessTypeList land,List<LAND_BUSINEESTYPE_LIST_INFO> list_infos) {
        logger.info(String.format("开始发送指令:车牌%s,场站%s,通道%s,重量%s",info.getVename(),info.getAreaid(),info.getChnlno(),info.getGrosswt()));
        boolean flag = false;
        if (check) {
            CommandClient.Client(info, PERMITTHOUGH);
            logger.info("=============>>>>>>>>放行报文发送成功<<<<<<<<<==============");
            flag = true;
        } else {
            CommandClient.Client(info, reason);
            logger.info("=============>>>>>>>>"+reason+"<<<<<<<<<==============");
        }
        commandlog(info,check,reason,land,list_infos);
        return flag;
    }
    public void commandlog(GatherInfo info,boolean check,String reason,LandBusinessTypeList land,List<LAND_BUSINEESTYPE_LIST_INFO> list_infos){
        String flag="",type="";
        commandLog command=new commandLog();
        command.setId(UUID.randomUUID().toString());
        command.setBarcode(info.getBarcode());

        if(land!=null){
            command.setBarcode(land.getBarcode());
            command.setBusnessType(land.getBusinesstype());
        }
        command.setAreaId(info.getAreaid());
        command.setChnlNo(info.getChnlno());
        if (check){
            flag = "00";
        } else{
            flag = "11";
        }
        if("I".equals(info.getIetype())){
            type="000000200000000000";
        }else{
            type="000000100000000000";
        }
        command.setReasonCode(flag+type);
        command.setReasonText(reason);
        command.setVeName(info.getVename());
        command.setVeWeight(selfWt);
        command.setIeType(info.getIetype());
        command.setExitGrossWeight(info.getGrosswt().doubleValue());
        command.setInGrossWeight(inWt);
        command.setGoodsWeight(goodsWt);
        command.setActualGoodsWeight(diffVal);
        if(list_infos !=null && list_infos.size()>0){
            command.setMasterList(Arrays.toString(toStrArry(list_infos)));
        }
        logic.commandLogService.insert(command);
    }
    /**
     * 给码头发送卡口数据
     *
     * @param stationCode 场站编号
     * @param carNo       车牌
     * @param IEtype      进出
     */
    public static void sendData(String stationCode, String carNo, boolean IEtype) {
        String url = logic.wharfHost+"air-api/car/channelCar?stationCode=" + stationCode + "&carNo=" + carNo + "&isPickup=" + IEtype;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String entityStr = EntityUtils.toString(entity);
            logger.info("------------>>>>>>>>>>>>>>发送车辆信息:{stationCode:" + stationCode + ",carNo:" + carNo + ",isPickup:" + IEtype + "}");
            logger.info("------------>>>>>>>>>>>>>>响应返回内容:" + entityStr + "<<<<<<<<<<<<-----------");
        } catch (Exception e) {
            logger.info(e.toString());
        }
    }

    /**
     * 给码头发送卡口数据
     *
     * @param list 进出场申请数据
     */
    public void checkData(LandBusinessTypeList list) {
        String sationCode = null;
        boolean flag = false;
        if ("出口送货".equals(list.getBusinesstype()) || "出口流转".equals(list.getBusinesstype())) {
            flag = false;
        }
        if ("进口提货".equals(list.getBusinesstype()) || "进口流转".equals(list.getBusinesstype())) {
            flag = true;
        }
        if ("4604000000".equals(list.getEndstation())) {
            if ("I".equals(list.getTurnoverflag())) {
                sationCode = "HK05";
            } else {
                sationCode = "HK06";
            }
            //TODO:加场站判定
        }
        try{
            sendData(sationCode, list.getTrailerFrameNo(), flag);
        }catch (Exception e){
            logger.info("码头发送消息异常---"+e.toString());
        }
    }


    /**
     * 查询运单是否全部放行
     *
     * @param manifestList 运单号数组
     * @return
     */
    public boolean checkManifest(String manifestList) {
        if (manifestList.length() < 1) {
            return false;
        }
        manifestList = manifestList.replace("-", "");
        //中文逗号替换
        manifestList = manifestList.replace(",", ",");
        String[] maifest = manifestList.split(",");
        boolean flag = false;
        int count = 0;
        for (int i = 0; i < maifest.length; i++) {
            RESMESSAGE resmessage = logic.resMessageService.selectByManifest(maifest[i]);
            if (resmessage != null) {
                if ("11".equals(resmessage.getResponsecode())) {
                    count++;
                }else {
                    logger.error("车辆装载运单未有放行信息---" + maifest[i]);
                }

            }else {
                logger.error("车辆装载运单未有放行信息---" + maifest[i]);
            }

        }
        if (count == maifest.length) {
            flag = true;
        }
        return flag;
    }





    /**
     * 排除当前系统问题发送错误commandInfo
     */
    public static void sendError(GatherInfo info) {
        //二维码数据异常,请使用正确的二维码数据
        CommandClient.Client(info, ISVALID);
    }

    /**
     * @Param mainifast 主单列表
     * @Param ietype 进出标志
     * 获取货物总重
     */
    public double GoodsWt(String mainifast, String ietype) {
        Double sum = 0.0;
        if (mainifast.length() > 0) {
            String[] mainifastList = mainifast.split(",");
            for (String mainBill : mainifastList) {
                sum += getGrossWt(mainBill, ietype);
            }
        }
        return sum;
    }

    /**
     * @Param waybill 主单号
     * @Param imp 进出港标识
     * @Result 获取运单重量
     */
    public double getGrossWt(String waybill, String imp) {
        logger.info("进入获取重量action");
        if (!(waybill.indexOf("-") != -1)) {
            waybill = waybill.substring(0, 3) + "-" + waybill.substring(3);
        }
        //todo:生产环境用下面这个
        String url = logic.nmmsHost+"orig/orig?waybill=" + waybill + "&imp=" + imp;
//          String url = "http://tjfx.15miaoo.com:8003/tj/orig/orig?waybill=" + waybill + "&imp=" + imp;
        StringBuilder json = new StringBuilder();
        Map map = null;
        double bg = 0;
        try {
            URL Url = new URL(url);
            URLConnection yc = Url.openConnection();
            //设置接口超时
            yc.setReadTimeout(5000);
            yc.setConnectTimeout(3000);
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            logger.info("返回数据:" + json);
            JSONArray array = JSONArray.parseArray(json.toString());
            for (int i = 0; i < array.size(); i++) {
                map = JSON.parseObject(array.getString(i));
                if (map.containsKey("receiptinformation")) {
                    if (map.get("receiptinformation").toString().startsWith("41301") || map.get("receiptinformation")
                            .toString().startsWith("41106") || map.get("receiptinformation")
                            .toString().startsWith("31301") || map.get("receiptinformation")
                            .toString().startsWith("31106") || map.get("receiptinformation")
                            .toString().indexOf("提运单放行") != -1) {
                        logger.info(map);
                        bg = Double.parseDouble((String) map.get("totalweight"));
                        logger.info("for循环取重量:" + bg);
                        return bg;
                    }
                }
            }
            logger.info("访问返回的数据重量:" + bg);
            in.close();
        } catch (MalformedURLException e) {
            logger.info("运单放行消息异常---"+e.toString());
            logger.error(e);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        }
        return bg;
    }



    /**
     * 生成或者更新货物冻结标识
     *
     * @param landBusinessTypeList
     */
    public void inOrUpEnterCancel(LandBusinessTypeList landBusinessTypeList) {
        if (landBusinessTypeList.getMasterList().length() < 1) return;
        String[] list = landBusinessTypeList.getMasterList().split(",");
        String flag = null;
        for (int i = 0; i < list.length; i++) {
            if("调拨业务".equals(landBusinessTypeList.getBusinesstype())){
                flag = "E";
            }else {
                flag = "I";
            }
            double wt = getGrossWt(list[i],flag);

            ENTERCANCCEL entercanccel = logic.enterCancelServer.selectByManifest(list[i]);
            if (entercanccel != null) {
                if(entercanccel.getVename().equals(landBusinessTypeList.getTrailerFrameNo())){
                    if ("0".equals(entercanccel.getIsfreeze())) {
                        entercanccel.setIsfreeze("1");
                        entercanccel.setEndport(landBusinessTypeList.getEndstation());
                        entercanccel.setUpdateBy(landBusinessTypeList.getCreateBy());
                        entercanccel.setUpdateTime(new Date());
                        logic.enterCancelServer.updateByPermaryKey(entercanccel);
                    }
                }
            }else {
                if("E".equals(landBusinessTypeList.getTurnoverflag())){
                    ENTERCANCCEL canccel = new ENTERCANCCEL();
                    canccel.setIsfreeze("0");
                    canccel.setVename(landBusinessTypeList.getTrailerFrameNo());
                    canccel.setId(String.valueOf(System.currentTimeMillis()));
                    canccel.setVeCompanyName(landBusinessTypeList.getAgentno());
                    canccel.setBusinesstype(landBusinessTypeList.getBusinesstype());
                    canccel.setManifest(list[i]);
                    canccel.setAgentname(landBusinessTypeList.getAgentname());
                    canccel.setStartport(landBusinessTypeList.getEndstation());
                    canccel.setGrosswt(landBusinessTypeList.getAislewt());
                    canccel.setCreateBy(landBusinessTypeList.getCreateBy());
                    canccel.setCreateTime(new Date());
                    canccel.setUpdateBy(landBusinessTypeList.getCreateBy());
                    canccel.setUpdateTime(new Date());
                    canccel.setWeight(wt);
                    logic.enterCancelServer.insertEntry(canccel);
                }

            }
        }
    }

    /**
     * 为提前运抵服务发送数据
     *
     * @param
     * @param
     * @return
     */
    @Async("asyncPoolTaskExecutor")
    public void sendMessage(String vname, List<LAND_BUSINEESTYPE_LIST_INFO> list_infos)throws InterruptedException{
        logger.info("新舱单发送服务开始");
        AdvanceArrive arrive=new AdvanceArrive();
        arrive.setVname(vname);
        arrive.setMasterList(list_infos);
        logger.info("新舱单发送服务数据",arrive);
        Map<String,Object> map=logic.feignService.sendMessage(arrive);
        logger.info(""+map);
    }

    /**
     * 新舱单分拨申请数据查询
     * @param waybill 查询的运单号
     * @return
     */
    public Map nmmsAllocate(@NotNull String waybill){
        logger.info("新舱单查询分拨申请数据开始");
        Feign_Allocate_Search feignAllocateSearch = new Feign_Allocate_Search(waybill,0,10);
        Map map = logic.nmmsService.getAllocate(feignAllocateSearch);
        logger.info(""+map);
        return map;
    }

    public boolean checkNmmsAllocate(String waybill){
        if (waybill.length() < 1) {
            return false;
        }
        waybill = waybill.replace("-", "");
        //中文逗号替换
        waybill = waybill.replace(",", ",");
        String[] maifest = waybill.split(",");
        logger.info("运单列表:" + waybill);
        boolean flag = false;

        for (String awb : maifest) {
            Map map= nmmsAllocate(awb);
            if (map.containsKey("reslut")){
                String result = map.get("reslut").toString();
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.containsKey("ds")) {
                    JSONArray ds = jsonObject.getJSONArray("ds");
                    JSONObject awbinfo = ds.getJSONObject(0);
                    if (awbinfo.containsKey("RECEIPTINFORMATION")){
                        if (awbinfo.getString("RECEIPTINFORMATION").contains("39301") || awbinfo.getString("RECEIPTINFORMATION").contains("39103")){
                            log4.info("运单:{},分拨回执查询结果:{}",awb,awbinfo.getString("RECEIPTINFORMATION"));
                        }else {
                            log4.info("运单{}分拨申请回执不正常:{}",awb,awbinfo.getString("RECEIPTINFORMATION"));
                            return false;
                        }
                    }
                }else {
                    log4.info("运单:{}分拨申请回执未查询到,或未进行分拨申请",awb);
                    return false;
                }
            }else{
                log4.info("运单:{}分拨申请回执未查询到,或未进行分拨申请",awb);
                return false;
            }

        }
        return true;
    }
}