package com.dxhy.core.job.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.invoice.TDxHttpLog;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.CoreConstants;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.CustomsLogService;
import com.dxhy.common.utils.MakeAppSecService;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.core.dao.CoreConfirmDao;
import com.dxhy.core.dao.CoreSysEnterpriseConfigCoreDao;
import com.dxhy.core.dao.CoreTDxCustomsApplyRecordDao;
import com.dxhy.core.job.dao.CoreTDxCustomsRecordDao;
import com.dxhy.core.job.entity.CustomsInfo;
import com.dxhy.core.job.entity.InvoiceStateData;
import com.dxhy.core.job.entity.TAcOrg;
import com.dxhy.core.job.entity.TDxCustomsApplyRecord;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.CustomsInterfaceService;
import com.dxhy.jxpt.baseService.poolPush.PoolLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 功能描述
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */

@Service("customsInterfaceService")
@Slf4j
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
public class CustomsInterfaceServiceImpl implements CustomsInterfaceService {

    @Resource
    private CoreTDxCustomsRecordDao coreTDxCustomsRecordDao;
    @Resource
    private PoolLogService poolLogService;

    @Resource
    private CoreConfirmDao coreConfirmDao;

    @Resource
    private CoreTDxCustomsApplyRecordDao applyRecordDao;

    @Resource
    private MakeAppSecService makeAppSecService;

    @Resource
    private CustomsLogService logService;

    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;


    @Override
    public void getCustoms(String taxno, String db, String aceId, String aceKey, String company, String taxName) {

        // 具体参数
        CollectData collectData = new CollectData();
        int totalRow = 0;
        int addRow = 0;
        log.info("--封装参数");
        try {

            // 封装参数
            String exchangeId = getDataExchangeId();
            collectData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            collectData.setBatchNo(batchNo);
            collectData.setAcquisitionDateBegin("20200629002003");
            collectData.setAcquisitionDateEnd(getEndTime());
            collectData.setStartRow(1);
            collectData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(collectData);
                log.info("data：" + dataStr);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSecService.makeAppSec(aceId, CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.customspcGet, CoreConstants.version,
                    base64Data, exchangeId, aceKey);
                // 请求报文拼接
                String collectDataStr = requestData(appSec, exchangeId, base64Data, CoreConstants.customspcGet, aceId);
                log.info("url:" + CoreConstants.collectUrl);
                log.info("请求参数：" + collectDataStr);
                log.info("发送请求-");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("11");
                httpLog.setReqText(collectDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(CoreConstants.collectUrl, collectDataStr, 120000);
                httpLog.setResDate(new Date());
                log.info(responseJson);
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                log.info("返回报文：" + responseJson);
                log.info(gatherData.toString());
                String base64data = gatherData.getData();
                String dataJson = "{}";
                if (base64data != null) {
                    dataJson = Base64.decodeStr(base64data);
                }
                log.info("data体：" + dataJson);
                CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
                httpLog.setResText(responseJson);
                httpLog.setStatus("0");
                httpLog.setCompany(company);
                if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                    if (gather.getList() != null && gather.getList().size() != 0) {
                        totalRow = gather.getTotalRows();
                        addRow += gather.getContentRows();
                        customsConsumer(responseJson, httpLog, company, db, taxName);
                    } else {
                        break;
                    }
                    if (addRow < totalRow) {
                        collectData.setStartRow(addRow);
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
    }

    @Override
    public void getCustomsState(String taxno, String db, String aceId, String aceKey) {

        // 具体参数
        InvoiceStateData stateData = new InvoiceStateData();
        int totalRow = 0;
        int addRow = 0;
        log.info("--封装参数");
        try {
            String exchangeId = getDataExchangeId();
            stateData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            stateData.setBatchNo(batchNo);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            stateData.setStatusChangeDateBegin(getStateBeginTime(taxno, "12"));
            stateData.setStatusChangeDateEnd(getEndTime());
            stateData.setStartRow(1);
            stateData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(stateData);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSecService.makeAppSec(aceId, CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.customspcState, CoreConstants.version,
                    base64Data, exchangeId, aceKey);

                // 请求报文拼接
                String stateDataStr = requestData(appSec, exchangeId, base64Data, CoreConstants.customspcState, aceId);
                log.info("url:" + CoreConstants.collectUrl);
                log.info("请求参数：" + stateDataStr);
                log.info("发送请求-");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("12");
                httpLog.setReqText(stateDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(CoreConstants.collectUrl, stateDataStr, 30000);
                httpLog.setResDate(new Date());
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                String base64data = gatherData.getData();
                httpLog.setResText(responseJson);
                httpLog.setStatus("0");
                if (base64data != null) {
                    String dataJson = Base64.decodeStr(base64data);
                    CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
                    if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                        if (gather.getList() != null && gather.getList().size() != 0) {
                            totalRow = gather.getTotalRows();
                            addRow += gather.getContentRows();
                            customsStateConsumer(responseJson, httpLog, db, taxno);
                        } else {
                            break;
                        }
                        if (addRow < totalRow) {
                            stateData.setStartRow(addRow);
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }

                } else {
                    break;
                }
            }

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);

        }
    }

    @Override
    public void getLtgalizeResult() {
        log.info("进入缴款书认证结果获取执行方法");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("14");
        BatchData batchData = new BatchData();

        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = coreConfirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询认证申请记录表中状态为N的批次号
                List<TDxCustomsApplyRecord> list = coreTDxCustomsRecordDao.getBatchNo("1");
                if (list != null && list.size() > 0) {
                    for (TDxCustomsApplyRecord tDxCustomsApplyRecord : list) {
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", tDxCustomsApplyRecord.getGfTaxNo()));
                        if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                            continue;
                        }
                        String batchNo = tDxCustomsApplyRecord.getBatchNo();
                        // 请求数据加密
                        batchData.setBatchNo(batchNo);
                        String dataStr = JSONObject.toJSONString(batchData);
                        String base64Data = Base64.encode(dataStr);
                        // 加密串生成
                        String appSec = makeAppSecService.makeAppSec(tDxCustomsApplyRecord.getAceId(), CoreConstants.appId,
                                CoreConstants.enterpriseCode, CoreConstants.customspcLegalizeStatus, CoreConstants.version, base64Data, dataExchangeId,
                            tDxCustomsApplyRecord.getAceKey());
                        log.info("本地请求生成加密串=======" + appSec);

                        // 请求报文拼接
                        String requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.customspcLegalizeStatus,
                            tDxCustomsApplyRecord.getAceId());
                        log.info("缴款书认证结果获取请求报文为=======" + requstData);
                        // 发送请求返回请求报文
                        tDxHttpLog.setReqText(requstData);
                        tDxHttpLog.setReqDate(new Date());
                        String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                        tDxHttpLog.setResText(responseJson);
                        tDxHttpLog.setResDate(new Date());
                        log.info("响应请求数据为=" + responseJson);
                        try {
                            if (responseJson != null) {
                                // 将返回报文转换成实体
                                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                if ("0000".equals(returnStateInfo.getReturnCode())) {
                                    String data = gatherData.getData();
                                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                    if ("Y".equals(dataJosn.getString("batchState"))) {
                                        Date rzhDate = null;
                                        List<LegalizeResult> datalist =
                                            JSONArray.parseArray(dataJosn.getString("list"), LegalizeResult.class);
                                        List<CustomsLog> logList = new ArrayList<>();
                                        //要推送票池的uuid集合
                                        List<String> uuids = new LinkedList();
                                        for (LegalizeResult legalizeResult : datalist) {
                                            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                            if (!"".equals(legalizeResult.getLegalizeDate())
                                                && legalizeResult.getLegalizeDate() != null
                                                && !" ".equals(legalizeResult.getLegalizeDate())) {
                                                rzhDate = tempDate.parse(legalizeResult.getLegalizeDate());
                                            }
                                            if ("0".equals(legalizeResult.getLegalizeState())) {
                                                legalizeResult.setLegalizeType("");
                                            }

                                            CustomsLog customsLog = new CustomsLog();
                                            customsLog.setCustomsCode(legalizeResult.getCustomsNo());
                                            customsLog.setRzType(legalizeResult.getLegalizeType());
                                            customsLog.setCreateDate(new Date());
                                            // 转换失败原因
                                            String failCode = exchangeFailCode(legalizeResult.getFailureReason());
                                            legalizeResult.setFailureReason(failCode);
                                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                            if ("2".equals(legalizeResult.getRzlx())) {
                                                // 退税认证
                                                customsLog.setType("7");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("1");
                                                    customsLog.setInputStatus("3");
                                                } else {
                                                    customsLog.setInputStatus("4");
                                                }
                                                coreTDxCustomsRecordDao.updateRecordForDrawback(legalizeResult, rzhDate);
                                                coreTDxCustomsRecordDao.updateApply(legalizeResult.getCustomsNo(), "1");
                                            } else if ("4".equals(legalizeResult.getRzlx())) {
                                                // 认证不抵扣
                                                customsLog.setType("5");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("2");
                                                    customsLog.setInputStatus("8");
                                                } else {
                                                    customsLog.setInputStatus("9");
                                                }
                                                coreTDxCustomsRecordDao.updateRecordForNoDeduction(legalizeResult, rzhDate);
                                                coreTDxCustomsRecordDao.updateApply(legalizeResult.getCustomsNo(), "1");
                                            } else if ("5".equals(legalizeResult.getRzlx())) {
                                                customsLog.setType("2");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("16");
                                                } else {
                                                    customsLog.setInputStatus("17");
                                                }

                                                // 撤销抵扣 清空认证等字段
                                                coreTDxCustomsRecordDao.updateRecordForRebackRz(legalizeResult, rzhDate);
                                                coreTDxCustomsRecordDao.updateApply(legalizeResult.getCustomsNo(), "1");
                                            } else if ("6".equals(legalizeResult.getRzlx())) {

                                                customsLog.setType("5");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("11");
                                                } else {
                                                    customsLog.setInputStatus("12");
                                                }
                                                // 如果撤销不抵扣申请成功 更新不抵扣相关字段
                                                coreTDxCustomsRecordDao.updateRecordForRebackNoDeduction(legalizeResult,
                                                    rzhDate);
                                                coreTDxCustomsRecordDao.updateApply(legalizeResult.getCustomsNo(), "1");
                                            } else if ("1".equals(legalizeResult.getRzlx())) {
                                                // 认证抵扣
                                                customsLog.setType("2");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("3");
                                                } else {
                                                    customsLog.setInputStatus("4");
                                                }
                                                coreTDxCustomsRecordDao.updateRecord(legalizeResult, rzhDate);
                                                coreTDxCustomsRecordDao.updateApply(legalizeResult.getCustomsNo(), "1");

                                            }
                                            logList.add(customsLog);
                                            if("4".equals(legalizeResult.getAuthState())){
                                                uuids.add(legalizeResult.getCustomsNo());
                                            }
                                        }
                                        //推送新票池记录表
                                        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JKS_2, uuids, ConfigureConstant.POOL_BGLX_ZTBG_2);

                                        if (logList.size() > 0) {
                                            logService.toCustomsLog(logList);
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                            tDxHttpLog.setStatus("2");
                            coreConfirmDao.insert(tDxHttpLog);
                           log.info("业务处理异常：{}", e);
                        }
                    }

                } else {
                    log.info("数据库没有未返回缴款书认证结果的记录");
                }
            }
        } catch (Exception e) {
            log.info("缴款书认证结果获取执行失败");
           log.info("业务处理异常：{}", e);
        }
    }

    @Override
    public void customsLegalize() {

        log.info("进入缴款书认证申请认证执行方法");
        CustomsApplyInfo applyInfo = new CustomsApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("13");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = coreConfirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送认证缴款书的税号
                List<String> taxList = coreTDxCustomsRecordDao.getNeedSendTaxNo();
                for (String taxno : taxList) {
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", taxno));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 通过税号查询发票数据
                    // 查询需要发送认证的缴款书
                    int count = coreTDxCustomsRecordDao.getApplyCustomsCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TdxCustomsRecord> list = coreTDxCustomsRecordDao.getApplyCustoms(taxno);
                            String batchNo = null;
                            // 申请认证请求报文缴款书list
                            List<ApplyCustoms> customsList = new ArrayList<>();
                            // 申请认证记录缴款书list
                            List<TDxCustomsApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxCustomsApplyRecord applyRecord = new TDxCustomsApplyRecord();
                                ApplyCustoms applyCustoms = new ApplyCustoms();
                                // 申请记录表
                                applyRecord.setCustomsCode(list.get(i).getCustomsCode());
                                applyRecord.setRzlx(list.get(i).getRzlx());
                                // 申请数据准备
                                applyCustoms.setCustomsNo(list.get(i).getCustomsCode());
                                applyCustoms.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyCustoms.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyCustoms.setFillInDate(
                                    new SimpleDateFormat("yyyyMMdd").format(list.get(i).getFillInDate()));
                                applyCustoms.setAmount(list.get(i).getTaxAmount());
                                applyCustoms.setApplyRzlx(list.get(i).getRzlx());
                                if (list.get(i).getYxTaxAmount() == null) {
                                    applyCustoms.setYxse(list.get(i).getTaxAmount());
                                } else {
                                    applyCustoms.setYxse(list.get(i).getYxTaxAmount());
                                }
                                if("4".equals(list.get(i).getRzlx()) && StringUtils.isNotBlank(list.get(i).getBdkMessage())){
                                    applyCustoms.setBdkMessage(list.get(i).getBdkMessage());
                                }
                                customsList.add(applyCustoms);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    batchNo = getBatchNo();
                                    applyInfo.setList(customsList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(customsList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode,
                                            CoreConstants.customspcLegalize, CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData = requestData(appSec, dataExchangeId, base64Data,
                                            CoreConstants.customspcLegalize, org.getAceId());
                                    log.info("申请认证取请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxCustomsApplyRecord apply1 : recordList) {
                                                    apply1.setBatchNo(batchNo);
                                                    apply1.setCreateDate(new Date());
                                                    apply1.setGfTaxNo(taxno);
                                                    apply1.setResultStatus("N");
                                                    apply1.setAceId(org.getAceId());
                                                    apply1.setAceKey(org.getAceKey());
                                                    apply1.setRecordType("1");
                                                    applyRecordDao.insert(apply1);
                                                    coreTDxCustomsRecordDao.updateCustomsRecord(apply1.getCustomsCode(),
                                                        apply1.getRzlx());
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        coreConfirmDao.insert(tDxHttpLog);
                                       log.info("业务处理异常：{}", e);
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请认证的缴款书");
                    }
                }
            }
        } catch (Exception e) {
            log.info("缴款书申请认证执行失败");
           log.info("业务处理异常：{}", e);
        }
    }

    @Override
    public void customsEntry() {
        log.info("进入缴款书录入执行方法");
        CustomsApplyInfo applyInfo = new CustomsApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("15");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = coreConfirmDao.getDbSource();
            for (String db : dbList) {
                // 流水号
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送录入缴款书的税号
                List<String> taxList = coreTDxCustomsRecordDao.getNeedUploadTaxNo();
                for (String taxno : taxList) {
                    TAcOrg org = selectIdAndKey(taxno);
                    if(ObjectUtil.isEmpty(org)){
                        log.info("此税号没有查到数据，请核实");
                        continue;
                    }
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", taxno));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 通过税号查询发票数据// 查询需要发送录入的缴款书
                    int count = coreTDxCustomsRecordDao.getUploadCustomsCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TdxCustomsRecord> list = coreTDxCustomsRecordDao.getUploadCustoms(taxno);
                            String batchNo = null;
                            // 申请录入请求报文缴款书list
                            List<EntryCustoms> customsList = new ArrayList<>();
                            // 申请录入记录缴款书list
                            List<TDxCustomsApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxCustomsApplyRecord applyRecord = new TDxCustomsApplyRecord();
                                EntryCustoms entryCustoms = new EntryCustoms();

                                // 申请记录表
                                applyRecord.setCustomsCode(list.get(i).getCustomsCode());

                                // 申请数据准备
                                entryCustoms.setCustomsCode(list.get(i).getCustomsCode());
                                entryCustoms.setFillInDate(
                                    new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getFillInDate()));
                                entryCustoms.setTaxAmount(list.get(i).getTaxAmount());
                                customsList.add(entryCustoms);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    batchNo = getBatchNo();
                                    applyInfo.setList(customsList);
                                    applyInfo.setBuyerTaxNo(taxno);
                                    applyInfo.setContentRows(customsList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode,
                                            CoreConstants.customspcEntry, CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, CoreConstants.customspcEntry, org.getAceId());
                                    log.info("录入请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxCustomsApplyRecord apply1 : recordList) {
                                                    apply1.setBatchNo(batchNo);
                                                    apply1.setGfTaxNo(taxno);
                                                    apply1.setCreateDate(new Date());
                                                    apply1.setResultStatus("N");
                                                    apply1.setAceId(org.getAceId());
                                                    apply1.setAceKey(org.getAceKey());
                                                    apply1.setRecordType("2");
                                                    applyRecordDao.insert(apply1);
                                                    coreTDxCustomsRecordDao
                                                        .updateCustomsUploadInfo(apply1.getCustomsCode());
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        coreConfirmDao.insert(tDxHttpLog);
                                       log.info("业务处理异常：{}", e);
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要录入的缴款书");
                    }
                }
            }
        } catch (Exception e) {
            log.info("缴款书录入执行失败");
           log.info("业务处理异常：{}", e);
        }
    }

    @Override
    public void customsEntryResult() {

        log.info("进入缴款书录入结果获取执行方法");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("16");
        UploadBatchData batchData = new UploadBatchData();

        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = coreConfirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询录入申请记录表中状态为N的批次号
                List<TDxCustomsApplyRecord> list = coreTDxCustomsRecordDao.getBatchNo("2");
                if (list != null && list.size() > 0) {
                    for (TDxCustomsApplyRecord tDxCustomsApplyRecord : list) {
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", tDxCustomsApplyRecord.getGfTaxNo()));
                        if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                            continue;
                        }
                        String batchNo = tDxCustomsApplyRecord.getBatchNo();
                        // 请求数据加密
                        batchData.setBatchNo(batchNo);
                        batchData.setBuyerTaxNo(tDxCustomsApplyRecord.getGfTaxNo());
                        String dataStr = JSONObject.toJSONString(batchData);
                        String base64Data = Base64.encode(dataStr);
                        // 加密串生成
                        String appSec = makeAppSecService.makeAppSec(tDxCustomsApplyRecord.getAceId(), CoreConstants.appId,
                                CoreConstants.enterpriseCode, CoreConstants.customspcEntryResult, CoreConstants.version, base64Data, dataExchangeId,
                            tDxCustomsApplyRecord.getAceKey());
                        log.info("本地请求生成加密串=======" + appSec);

                        // 请求报文拼接
                        String requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.customspcEntryResult,
                            tDxCustomsApplyRecord.getAceId());
                        log.info("缴款书录入结果获取请求报文为=======" + requstData);
                        // 发送请求返回请求报文
                        tDxHttpLog.setReqText(requstData);
                        tDxHttpLog.setReqDate(new Date());
                        String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                        tDxHttpLog.setResText(responseJson);
                        tDxHttpLog.setResDate(new Date());
                        log.info("响应请求数据为=" + responseJson);
                        try {
                            if (responseJson != null) {
                                // 将返回报文转换成实体
                                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                if ("0000".equals(returnStateInfo.getReturnCode())) {
                                    String data = gatherData.getData();
                                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                    if ("Y".equals(dataJosn.getString("batchState"))) {
                                        Date rzhDate = null;
                                        List<UploadBackInfo> datalist =
                                            JSONArray.parseArray(dataJosn.getString("list"), UploadBackInfo.class);
                                        for (UploadBackInfo uploadBackInfo : datalist) {
                                            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");

                                            TdxCustomsRecord updateRecord = new TdxCustomsRecord();
                                            updateRecord.setCustomsCode(uploadBackInfo.getCustomsCode());
                                            updateRecord.setTaxAmount(uploadBackInfo.getTaxAmount());
                                            if (!"".equals(uploadBackInfo.getFillInDate())
                                                && uploadBackInfo.getFillInDate() != null
                                                && !" ".equals(uploadBackInfo.getFillInDate())) {
                                                updateRecord
                                                    .setFillInDate(tempDate.parse(uploadBackInfo.getFillInDate()));
                                            }

                                            if (!"".equals(uploadBackInfo.getEntryDate())
                                                && uploadBackInfo.getEntryDate() != null
                                                && !" ".equals(uploadBackInfo.getEntryDate())) {
                                                updateRecord
                                                    .setUploadDate(tempDate.parse(uploadBackInfo.getEntryDate()));
                                            }
                                            updateRecord.setAuditStatus(uploadBackInfo.getAuditResult());
                                            updateRecord.setApplyCheck(uploadBackInfo.getApplyCheckYesorno());
                                            updateRecord.setCheckStatus(uploadBackInfo.getExamineResult());
                                            updateRecord.setFailReason(uploadBackInfo.getFailureReason());

                                            if ("4".equals(uploadBackInfo.getAuthState())) {
                                                updateRecord.setCollectUploadStatus("2");
                                            } else if ("5".equals(uploadBackInfo.getAuthState())) {
                                                updateRecord.setCollectUploadStatus("3");
                                            }
                                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                            coreTDxCustomsRecordDao.updateUploadResult(updateRecord);
                                            coreTDxCustomsRecordDao.updateApply(uploadBackInfo.getCustomsCode(), "2");

                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            DynamicContextHolder.push(DbConstant.BUSINESS_WRITE);
                            tDxHttpLog.setStatus("2");
                            coreConfirmDao.insert(tDxHttpLog);
                           log.info("业务处理异常：{}", e);
                        }
                    }

                } else {
                    log.info("数据库没有未返回缴款书录入结果的记录");
                }
            }
        } catch (Exception e) {
            log.info("缴款书录入结果获取执行失败");
           log.info("业务处理异常：{}", e);
        }
    }

    public String getDataExchangeId() {
        // enterpriseCode+8 位日期
        // (YYYYMMDD)+9 位序列号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 9; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return CoreConstants.enterpriseCode + simpleDateFormat.format(new Date()) + data;
    }

    /**
     * 获取批次号
     */
    public String getBatchNo() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 24; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return date + data;
    }

    private String getBeginTime(String taxno, String db) {
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        String lastTime = coreTDxCustomsRecordDao.selectLastCustomsDate(taxno);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (lastTime == null || "".equals(lastTime)) {
            Calendar c2 = new GregorianCalendar();
            c2.set(Calendar.HOUR_OF_DAY, 0);
            c2.set(Calendar.MINUTE, 0);
            c2.set(Calendar.SECOND, 0);
            c2.set(Calendar.DAY_OF_MONTH, 1);
            lastTime = simpleDateFormat.format(c2.getTime());
        } else {
            // 避免防止漏票，提前一小时
            Calendar cal = Calendar.getInstance();
            try {
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                Date date = simpleDateFormat.parse(lastTime);
                cal.setTime(date);
                if (hour >= 22) {
                    cal.add(Calendar.HOUR_OF_DAY, -30);
                } else {
                    cal.add(Calendar.HOUR_OF_DAY, -1);
                }
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }
        }
        return lastTime;
    }

    private String getStateBeginTime(String taxno, String type) {
        String lastTime = coreTDxCustomsRecordDao.selectLastReqDate(taxno, type);
        if (lastTime == null || "".equals(lastTime)) {
            Calendar c2 = new GregorianCalendar();
            c2.set(Calendar.HOUR_OF_DAY, 0);
            c2.set(Calendar.MINUTE, 0);
            c2.set(Calendar.SECOND, 0);
            c2.set(Calendar.DAY_OF_MONTH, 1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            lastTime = simpleDateFormat.format(c2.getTime());
        } else {
            // 避免防止漏票，提前一小时
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            try {
                Date date = simpleDateFormat.parse(lastTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.HOUR_OF_DAY, -1);
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }
        }

        return lastTime;
    }

    /**
     * 获取结束时间
     *
     * @return
     */
    private String getEndTime() {
        Calendar c2 = new GregorianCalendar();
        c2.set(Calendar.HOUR_OF_DAY, 23);
        c2.set(Calendar.MINUTE, 59);
        c2.set(Calendar.SECOND, 59);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(c2.getTime());
    }

    private TAcOrg selectIdAndKey(String taxno) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 通过税号查询id和Key
        return coreConfirmDao.findIdAndKeyByTaxno(taxno);
    }

    public void customsConsumer(String responseJson, TDxHttpLog httpLog, String company, String db, String taxName) {

        String total = "";
        try {

            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info("返回报文：" + responseJson);
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
            String lists = gather.getList().toString();
            List<CustomsInfo> list = JSONObject.parseArray(lists, CustomsInfo.class);
            total = list.size() + "";
            List<CustomsLog> logList = new ArrayList<>();
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (CustomsInfo info : list) {

                // 判断库里是否已经存在，存在则只更新状态更新时间，认证状态以及相关字段更新
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TdxCustomsRecord entity = coreTDxCustomsRecordDao.getByCustomsCode(info.getCustomsNo());
                int export = coreTDxCustomsRecordDao.getExportByCustomsCode(info.getCustomsNo());

                if (entity != null) {

                    boolean flag = false;
                    String source = entity.getDataSources();
                    if (!"0".equals(source)) {
                        entity = exchangePoToEntity(info);
                        entity.setDataSources(source);
                        if (export > 0) {
                            entity.setExportMark("1");
                        }
                        flag = true;
                    } else {
                        if (export > 0) {
                            // 出口转内销标志
                            entity.setExportMark("1");
                        }
                        if ("0".equals(entity.getRzhYesorno())
                            && !entity.getRzhYesorno().equals(info.getLegalizeState())) {
                            // 认证抵扣
                            if ("1".equals(info.getRzlx())) {
                                entity.setRzhYesorno(info.getLegalizeState());
                                entity.setRzhBelongDate(info.getLegalizeBelongDate());
                                entity.setRzlx(info.getRzlx());
                                if (StringUtils.isNotBlank(info.getLegalizeDate())) {
                                    SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                    entity.setRzhDate(sim.parse(info.getLegalizeDate()));
                                }
                                if ("1".equals(info.getLegalizeState())) {
                                    entity.setAuthStatus("4");
                                } else {
                                    entity.setAuthStatus("0");
                                }
                                entity.setBdkStatus("1");
                                // 认证不抵扣
                            } else if ("4".equals(info.getRzlx())) {
                                entity.setRzhYesorno("2");
                                entity.setRzhBelongDate(info.getLegalizeBelongDate());
                                entity.setRzlx(info.getRzlx());
                                if (StringUtils.isNotBlank(info.getLegalizeDate())) {
                                    SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                    entity.setRzhDate(sim.parse(info.getLegalizeDate()));
                                }
                                if ("1".equals(info.getLegalizeState())) {
                                    entity.setAuthStatus("4");
                                } else {
                                    entity.setAuthStatus("0");
                                }
                                entity.setBdkStatus("2");
                                if(StringUtils.isNotBlank(info.getBdkMessage())){
                                    entity.setBdkMessage(info.getBdkMessage());
                                }
                                // 退税认证
                            } else if ("2".equals(info.getRzlx())) {
                                entity.setRzhYesorno("1");
                                entity.setRzhBelongDate(info.getLegalizeBelongDate());
                                entity.setRzlx(info.getRzlx());
                                if (StringUtils.isNotBlank(info.getLegalizeDate())) {
                                    SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                    entity.setRzhDate(sim.parse(info.getLegalizeDate()));
                                }
                                if ("1".equals(info.getLegalizeState())) {
                                    entity.setAuthStatus("4");
                                } else {
                                    entity.setAuthStatus("0");
                                }
                                entity.setBdkStatus("3");
                            }
                            flag = true;
                            // 局端撤销了认证
                        } else if (!"0".equals(entity.getRzhYesorno()) && !"1".equals(info.getLegalizeState())) {
                            entity.setRzhYesorno("0");
                            entity.setRzhBelongDate(null);
                            entity.setRzlx("0");
                            entity.setRzhType(null);
                            entity.setRzhDate(null);
                            entity.setAuthStatus("0");
                            entity.setBdkStatus("0");
                            flag = true;
                        }
                    }

                    if (flag) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        coreTDxCustomsRecordDao.updateCustoms(entity);
                    }

                } else {
                    if (StringUtils.isBlank(info.getLegalizeDate())) {
                        info.setLegalizeDate(null);
                    }
                    TdxCustomsRecord record = exchangePoToEntity(info);
                    if (export > 0) {
                        record.setExportMark("1");
                    }
                    record.setCompany(company);
                    record.setGfName(taxName);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    coreTDxCustomsRecordDao.insert(record);
                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(info.getCustomsNo());
                    customsLog.setType("1");
                    customsLog.setInputStatus("0");
                    customsLog.setCreateDate(new Date());
                    customsLog.setInputName("系统自动");
                    logList.add(customsLog);
                }

                uuids.add(info.getCustomsNo());
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JKS_2, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

            httpLog.setStatus("1");
            httpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(httpLog);

            if (logList.size() > 0) {
                logService.toCustomsLog(logList);
            }

        } catch (Exception e) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            httpLog.setStatus("2");
            httpLog.setTotal(total);
            coreConfirmDao.insert(httpLog);
           log.info("业务处理异常：{}", e);
        }
    }

    public void customsStateConsumer(String responseJson, TDxHttpLog tDxHttpLog, String db, String taxno) {
        String total = "";
        try {
            log.info("开始解析报文  报文内容：" + responseJson);
            // 根据发票类型保存不同实体
            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info(gatherData.toString());
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
            String lists = gather.getList().toString();
            List<CustomsInfo> list = JSONObject.parseArray(lists, CustomsInfo.class);
            total = list.size() + "";
            List<CustomsLog> logList = new ArrayList<>();
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (CustomsInfo stateInfo : list) {
                TdxCustomsRecord state = poToStateInfo(stateInfo);
                String lx = state.getRzlx();
                // 添加不同的认证类型，更新对应字段 0918
                if (StringUtils.isNotEmpty(lx)) {
                    if ("5".equals(lx) || "6".equals(lx)) {
                        continue;
                    } else {
                        switch (lx) {
                            case "1":
                                state.setBdkStatus("1");
                                break;
                            case "4":
                                state.setBdkStatus("2");
                                state.setRzhYesorno("2");
                                break;
                            case "0":
                                state.setBdkStatus("0");
                                break;
                            case "2":
                                // 退税
                                state.setBdkStatus("3");
                                state.setRzhYesorno("1");
                                break;
                            default:
                                break;
                        }
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        coreTDxCustomsRecordDao.updateCustomsState(state);
                    }
                } else {
                    // 更新发票数据
                    state.setBdkStatus("0");
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    coreTDxCustomsRecordDao.updateCustomsState(state);
                }

                if (!"0".equals(stateInfo.getGlzt())) {
                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(stateInfo.getCustomsNo());
                    customsLog.setType("6");
                    customsLog.setInputStatus("19");
                    customsLog.setCreateDate(new Date());
                    logList.add(customsLog);
                }

                uuids.add(state.getCustomsCode());
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JKS_2, uuids, ConfigureConstant.POOL_BGLX_ZTBG_2);

            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(tDxHttpLog);
            if (logList.size() > 0) {
                logService.toCustomsLog(logList);
            }

        } catch (Exception e) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(tDxHttpLog);
           log.info("业务处理异常：{}", e);
        }
    }

    private TdxCustomsRecord exchangePoToEntity(CustomsInfo po) {

        TdxCustomsRecord entity = new TdxCustomsRecord();
        entity.setCustomsCode(po.getCustomsNo());
        entity.setTaxAmount(po.getAmount());
        entity.setGfTaxNo(po.getBuyerTaxNo());
        try {
            if (po.getFillInDate() != null) {

                entity.setFillInDate(new SimpleDateFormat("yyyyMMdd").parse(po.getFillInDate()));
            }
        } catch (ParseException e) {
            entity.setFillInDate(null);
        }
        entity.setGxjzr(po.getLegalizeEndDate());
        entity.setGxfwq(po.getLegalizeInvoiceDateBegin());
        entity.setGxfwz(po.getLegalizeInvoiceDateEnd());
        entity.setRzlx(po.getRzlx());
        entity.setCreateDate(new Date());
        entity.setDetailYesorno("0");
        entity.setDataSources("0");
        entity.setDataType("17");
        entity.setDqskssq(po.getCurrentTaxPeriod());
        // 认证抵扣
        if ("1".equals(po.getLegalizeState()) && "1".equals(po.getRzlx())) {
            entity.setRzhYesorno(po.getLegalizeState());
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBelongDate());
            try {
                if (po.getLegalizeDate() != null) {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                }
            } catch (ParseException e) {
                entity.setRzhDate(null);
            }
            entity.setBdkStatus("1");
        }
        // 认证不抵扣
        if ("1".equals(po.getLegalizeState()) && "4".equals(po.getRzlx())) {
            entity.setRzhYesorno("2");
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBelongDate());
            entity.setBdkStatus("2");
            if (po.getLegalizeDate() != null) {
                try {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                } catch (ParseException e) {
                    entity.setRzhDate(null);
                }
            }
            if(StringUtils.isNotBlank(po.getBdkMessage())){
                entity.setBdkMessage(po.getBdkMessage());
            }
        }
        // 退税认证
        if ("1".equals(po.getLegalizeState()) && "2".equals(po.getRzlx())) {
            entity.setRzhYesorno("3");
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBelongDate());
            entity.setBdkStatus("3");
            if (po.getLegalizeDate() != null) {
                try {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                } catch (ParseException e) {
                    entity.setRzhDate(null);
                }
            }

        }

        entity.setEntryDiscrepancy(po.getIsDiscrepancy());
        entity.setXxly(po.getXxly());
        entity.setGlzt(po.getGlzt());
        if (po.getYxse() != null && !"".equals(po.getYxse())) {
            entity.setYxTaxAmount(po.getYxse());
        } else {
            entity.setYxTaxAmount(po.getAmount());
        }
        return entity;
    }

    public TdxCustomsRecord poToStateInfo(CustomsInfo info) throws ParseException {
        TdxCustomsRecord state = new TdxCustomsRecord();

        if ("".equals(info.getLegalizeDate())) {
            state.setRzhDate(null);
        } else {
            state.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(info.getLegalizeDate()));
        }

        state.setRzhYesorno(info.getLegalizeState());
        if ("1".equals(info.getLegalizeState())) {
            state.setAuthStatus("4");
        } else {
            state.setAuthStatus("0");
        }
        if ("".equals(info.getLegalizeBelongDate())) {
            state.setRzhBelongDate(null);
        } else {
            state.setRzhBelongDate(info.getLegalizeBelongDate());
        }

        if (info.getRzlx() == null || "".equals(info.getRzlx())) {
            state.setRzlx(null);
        } else {
            state.setRzlx(info.getRzlx());
        }

        if (StringUtils.isNotBlank(info.getYxse())) {
            state.setYxTaxAmount(info.getYxse());
        }
        if (StringUtils.isNotBlank(info.getGlzt())) {
            state.setGlzt(info.getGlzt());
        }
        if (StringUtils.isNotBlank(info.getXxly())) {
            state.setXxly(info.getXxly());
        }
        if(StringUtils.isNotBlank(info.getBdkMessage())){
            state.setBdkMessage(info.getBdkMessage());
        }
        state.setCustomsCode(info.getCustomsNo());
        return state;
    }

    private static Boolean isBlank(String str) {
        return str == null || str.trim().length() == 0;

    }

    private String exchangeFailCode(String failureReason) {
        if (!isBlank(failureReason)) {
            if ("1".equals(failureReason)) {
                return "成功";
            }
            if ("2".equals(failureReason)) {
                return "无此票";
            }
            if ("3".equals(failureReason)) {
                return "该票异常无法认证";
            }
            if ("4".equals(failureReason)) {
                return "该票已认证";
            }
            if ("5".equals(failureReason)) {
                return "该票已经逾期无法认证";
            }
            if ("6".equals(failureReason)) {
                return "该票已经申请认证";
            }
            if ("7".equals(failureReason)) {
                return "申请认证月份不匹配";
            }
            if ("8".equals(failureReason)) {
                return "其他异常";
            }
            if ("9".equals(failureReason)) {
                return "该票未到期";
            }
            if ("10".equals(failureReason)) {
                return "红票无法认证";
            }
            if ("11".equals(failureReason)) {
                return "认证类型不匹配";
            }
            if ("12".equals(failureReason)) {
                return "信用等级异常";
            }
            if ("13".equals(failureReason)) {
                return "token超过五天未获取";
            }
            if ("14".equals(failureReason)) {
                return "该票不可勾选为逾期";
            }
            if ("15".equals(failureReason)) {
                return "有效税额异常（有效税额大于实际税额）";
            }
            if ("16".equals(failureReason)) {
                return "当期已锁定";
            }
            if ("17".equals(failureReason)) {
                return "逾期不可勾选";
            }
            if ("18".equals(failureReason)) {
                return "发票未勾选（确认）";
            }
            if ("19".equals(failureReason)) {
                return "取消操作不匹配";
            }
            if ("98".equals(failureReason)) {
                return "管理状态异常";
            }
            if ("23".equals(failureReason)) {
                return "不抵扣原因为空或者异常";
            }
        }
        return "";
    }

    public String requestData(String appSec, String dataExchangeId, String base64Data, String interfaceCode,
        String aceId) {
        String requstData = null;
        try {
            Authorize authorize = new Authorize();
            GlobalInfo globalInfo = new GlobalInfo();
            BaseQueJson bqj = new BaseQueJson();
            authorize.setAppSecId(aceId);
            authorize.setAppSec(appSec);
            bqj.setAuthorize(authorize);
            globalInfo.setAppId(CoreConstants.appId);
            globalInfo.setDataExchangeId(dataExchangeId);
            globalInfo.setEnterpriseCode(CoreConstants.enterpriseCode);
            globalInfo.setInterfaceCode(interfaceCode);
            globalInfo.setVersion(CoreConstants.version);
            bqj.setGlobalInfo(globalInfo);
            bqj.setData(base64Data);
            requstData = JSONObject.toJSONString(bqj);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return requstData;
    }
}
