package com.dxhy.erp.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigDto;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.custom.TdxCustomsRecordVO;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.DataSourceEnum;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.erp.dao.AuthRecordDao;
import com.dxhy.erp.dao.SysEnterpriseConfigErpDao;
import com.dxhy.erp.dao.ErpTdxCustomsRecordDao;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.model.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.CustomspcService;
import com.dxhy.erp.service.TdxUploadRecordService;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.erp.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaAvoidComplexCondition"})
@Service("customspcService")
@Slf4j
public class CustomspcServiceImpl extends MpBaseServiceImpl<ErpTdxCustomsRecordDao, TdxCustomsRecord>
        implements CustomspcService {

    private static final Map<String, Integer> HASH = new HashMap<>();
    @Value("${erp.collectNum}")
    private String collectNum;
    @Value("${erp.stateNum}")
    private String stateNum;

    @Autowired
    private SysEnterpriseConfigErpDao enterpriseConfigErpDao;

    @Autowired
    private AuthRecordDao authRecordDao;

    @Autowired
    private TdxUploadRecordService tdxUploadRecordService;

    @Override
    public String getCustoms(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                             HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<TdxCustomsRecord> list;
        CustomsCollectPo data;
        try {
            data = JSON.parseObject(map.get("data"), CustomsCollectPo.class);
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total = 0;
            try {

                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = selectByAllCount(data);
            } catch (Exception e) {
                log.info("获取总条数错误：" + e);
               log.info("业务处理异常：{}", e);
            }
            // if ("1".equals(data.getStatus())){

            int startRow = data.getStartRow();
            if (startRow <= 0) {
                startRow = 1;
            }
            int endRow = 0;

            if (total > Integer.parseInt(collectNum)) {

                endRow = Integer.parseInt(collectNum);
            } else {
                endRow = total;
            }

            if ("1".equals(data.getStatus())) {
                List<CustomsResInfo> customsResInfos = new ArrayList<>();
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                list = selectCustoms(data, startRow, endRow);
                log.info("-----------获取海关缴款书完成----------" + globalInfo.getDataExchangeId());
                startRow += list.size();
                for (TdxCustomsRecord info : list) {
                    CustomsResInfo customsInfo = getCustomsInfo(info);
                    customsResInfos.add(customsInfo);
                }

                log.info("===========海关缴款书实体转换完成============" + globalInfo.getDataExchangeId());
                CustomsResData gather = new CustomsResData();
                gather.setStartRow(data.getStartRow());
                gather.setTotalRows(total);
                gather.setContentRows(customsResInfos.size());
                if (customsResInfos.size() > 0) {
                    gather.setList(customsResInfos);
                }

                String result = JSON.toJSONString(gather);
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData(Base64.encode(result));
                return JSON.toJSONString(interfaceCode);

            } else if ("0".equals(data.getStatus())) {

                run.setReturnCode("0000");
                run.setReturnMessage("处理成功");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            } else {
                run.setReturnCode("9999");
                run.setReturnMessage("处理失败");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    @Override
    public String getCustomsState(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                  HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<CustomsResInfo> list = new ArrayList<>();
        try {
            StateData data = JSONObject.parseObject(map.get("data"), StateData.class);
            run = getCheckState(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total;
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            try {
                total = HASH.get(data.getBatchNo());
                if (total == null || total == 0) {

                    total = selectByStateAllCount(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                            data.getBuyerTaxNo());
                    HASH.put(data.getBatchNo(), total);
                }
            } catch (Exception e) {
                log.info("业务处理异常：{}", e);
                total = selectByStateAllCount(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                        data.getBuyerTaxNo());
                HASH.put(data.getBatchNo(), total);
            }

            if ("1".equals(data.getStatus())) {
                int startRow = data.getStartRow();
                boolean continueQuery = true;

                while (continueQuery && list.size() < Integer.parseInt(stateNum) && list.size() < total
                        && startRow <= total) {
                    list = selectByState(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                            data.getBuyerTaxNo(), startRow, 1000);
                    startRow += 1000;
                    if (list.size() >= Integer.parseInt(stateNum)) {
                        continueQuery = false;
                        break;
                    }

                }
                CustomsResData status = new CustomsResData();
                status.setContentRows(list.size());
                status.setStartRow(data.getStartRow());
                status.setTotalRows(total);
                status.setList(list);
                String result = JSON.toJSONString(status);
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData(Base64.encode(result));
                return JSON.toJSONString(interfaceCode);
            } else if ("0".equals(data.getStatus())) {
                HASH.remove(data.getBatchNo());
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);

            } else {
                run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
            log.info("海关缴款书状态采集接口异常:{}",e);
            run.setReturnCode(ReturnCodeEnum.QTYC.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QTYC.getFhzMc(ReturnCodeEnum.QTYC.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();

            try {
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
            } catch (Exception ignored) {
            }
            return JSON.toJSONString(interfaceCode);
        }
    }

    @Override
    public String applyCustomsAuth(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                   HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        CustomsCollectPo data = null;
        try {
            data = JSONObject.parseObject(map.get("data"), CustomsCollectPo.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        if (StringUtils.isBlank(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }

        List<CustomsApplyReq> authStateList = data.getList();
        run = getCheckData(authStateList, data.getContentRows());
        if (run.getReturnCode() != null || run.getReturnMessage() != null) {
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            return JSON.toJSONString(interfaceCode);
        }
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
        String dbName = null;
        if (deptEntity != null && deptEntity.getDbName() != null) {
            dbName = deptEntity.getDbName();
        } else {
            ReturnStateInfo runInfo = new ReturnStateInfo();
            runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
            runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(runInfo);
            return JSON.toJSONString(interfaceCode);
        }

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        int resultNum = authRecordDao.selectCountRecord(data.getBatchNo(),data.getBuyerTaxNo(),ConfigureConstant.STRING_2);
        if (resultNum > 0) {
            ReturnStateInfo runInfo = new ReturnStateInfo();
            runInfo.setReturnCode("2099");
            runInfo.setReturnMessage("批次号已存在");
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(runInfo);
            return JSON.toJSONString(interfaceCode);
        }
        List<AuthRecord> authRecordList = bulidAuthRecord(authStateList, data.getBatchNo());
        // 申请认证记录保存
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        authRecordDao.insertAuthRecord(authRecordList, ConfigureConstant.STRING_2);

        for (CustomsApplyReq authState : authStateList) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            TdxCustomsRecord customsRecord =
                    this.baseMapper.getCustomsRecord(authState.getBuyerTaxNo(), authState.getCustomsNo());
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            if (customsRecord != null) {
                if ("5".equals(authState.getApplyRzlx())) {
                    if (!"4".equals(customsRecord.getCxrzStatus())) {
                        this.baseMapper.updateCxrz(authState.getApplyTaxPeriod(), authState.getCustomsNo());
                    }
                } else if ("6".equals(authState.getApplyRzlx())) {
                    if (!"4".equals(customsRecord.getCxbdkStatus())) {
                        this.baseMapper.updateCxbdk((String) authState.getApplyTaxPeriod(), authState.getCustomsNo());
                    }
                } else {
                    if (!"4".equals(customsRecord.getAuthStatus())) {
                        if ("1".equals(authState.getApplyRzlx())) {
                            this.baseMapper.updateRz(authState, "1");
                        } else if ("4".equals(authState.getApplyRzlx())) {
                            this.baseMapper.updateRz(authState, "2");
                        } else {
                            this.baseMapper.updateRz(authState, "3");
                        }
                    }
                }

            }
        }
        if (run.getReturnCode() == null) {
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
        }
        interfaceCode.setReturnStateInfo(run);
        interfaceCode.setGlobalInfo(globalInfo);
        return JSON.toJSONString(interfaceCode);
    }

    @Override
    public String getCustomsAuthResult(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                       HttpServletResponse response, Authorize authorize) {

        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        CustomsResData resData = new CustomsResData();
        AuthDateReq data = null;
        try {
            data = JSONObject.parseObject(map.get("data"), AuthDateReq.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        if (StringUtils.isBlank(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        if (StringUtils.isBlank(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
        String dbName = null;
        if (deptEntity != null && deptEntity.getDbName() != null) {
            dbName = deptEntity.getDbName();
        } else {
            ReturnStateInfo runInfo = new ReturnStateInfo();
            runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
            runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(runInfo);
            return JSON.toJSONString(interfaceCode);
        }
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        int resultNum = authRecordDao.selectCountRecord(data.getBatchNo(),data.getBuyerTaxNo(),ConfigureConstant.STRING_2);
        Integer r = this.baseMapper.selectAuthResult(data.getBatchNo());

        resData.setBatchNo(data.getBatchNo());
        resData.setBuyerTaxNo(data.getBuyerTaxNo());
        if (resultNum == 0 || r > 0) {
            resData.setContentRows(0);
            resData.setBatchState("N");
            String resultData = JSON.toJSONString(resData);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);

            interfaceCode.setData(Base64.encode(resultData));

            return JSON.toJSONString(interfaceCode);
        }
        List<CustomsResInfo> authStatusList = this.baseMapper.selectAuthResultBack(data.getBatchNo());
        DecimalFormat df = new DecimalFormat("#0.00");
        for (CustomsResInfo authStatus : authStatusList) {
            if ("0".equals(authStatus.getAuthState())) {
                authStatus.setFailureReason("未认证");
            }
            if ("6".equals(authStatus.getAuthState())) {
                authStatus.setAuthState("0");
            }
            if (authStatus.getAuthState() == null) {
                authStatus.setAuthState("5");
                authStatus.setLegalizeState("0");
                authStatus.setFailureReason("无此底账");
            }
            if (authStatus.getLegalizeDate() == null) {
                authStatus.setLegalizeDate("");
            }
            if (authStatus.getFailureReason() == null) {
                authStatus.setFailureReason("");
            }
            if (authStatus.getLegalizeBelongDate() == null) {
                authStatus.setLegalizeBelongDate("");
            }
            if (authStatus.getAmount() == null) {
                authStatus.setAmount("");
            }
            if (authStatus.getGlzt() == null) {
                authStatus.setGlzt("");
            }

            if ("1".equals(authStatus.getRzlx()) || "4".equals(authStatus.getRzlx())) {
                if (authStatus.getYxse() != null) {

                    authStatus.setYxse(df.format(new BigDecimal(authStatus.getYxse())));
                } else {
                    authStatus.setYxse("");
                }
            } else {
                authStatus.setYxse("");
            }
        }
        resData.setBatchState("Y");
        resData.setContentRows(authStatusList.size());
        resData.setList(authStatusList);
        String resultData = JSON.toJSONString(resData);
        run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
        run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
        interfaceCode.setReturnStateInfo(run);
        interfaceCode.setGlobalInfo(globalInfo);

        interfaceCode.setData(Base64.encode(resultData));

        return JSON.toJSONString(interfaceCode);
    }

    @Override
    public String applyCustomsUpload(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                     HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        try {

            CustomsCollectPo data = null;
            try {
                data = JSONObject.parseObject(map.get("data"), CustomsCollectPo.class);
            } catch (Exception e) {
                run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            if (StringUtils.isBlank(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            QueryWrapper<TdxUploadRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("batch_no", data.getBatchNo());
            List<TdxUploadRecord> tdxUploadRecords = tdxUploadRecordService.getBaseMapper().selectList(queryWrapper);

            if (tdxUploadRecords != null && tdxUploadRecords.size() > 0) {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode("2099");
                runInfo.setReturnMessage("批次号已存在");
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }

            List<CustomsApplyReq> authStateList = data.getList();
            run = checkUploadData(authStateList, data.getContentRows(), data.getBuyerTaxNo());
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);
            }

            List<TdxUploadRecord> uploadRecords = buliduploadRecord(authStateList, data.getBatchNo());
            // 申请认证记录保存
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            tdxUploadRecordService.saveBatch(uploadRecords);

            List<TdxCustomsRecord> insertList = new ArrayList<>();
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            for (CustomsApplyReq authState : authStateList) {
                TdxCustomsRecord customsRecord = new TdxCustomsRecord();
                customsRecord = new TdxCustomsRecord();
                customsRecord.setCustomsCode(authState.getCustomsNo());
                customsRecord.setGfName(deptEntity.getNsrmc());
                customsRecord.setGfTaxNo(deptEntity.getNsrsbh());
                customsRecord.setFillInDate(DateUtils.strToDate(authState.getFillInDate()));
                customsRecord.setTaxAmount(authState.getAmount());
                customsRecord.setPayerOneTaxno(deptEntity.getNsrsbh());
                customsRecord.setPayerOneName(deptEntity.getNsrmc());
                customsRecord.setYxTaxAmount(authState.getAmount());
                customsRecord.setDataSources(DataSourceEnum.G.getKey());
                customsRecord.setCreateDate(new Date());
                customsRecord.setDataType("17");
                customsRecord.setCollectUploadStatus("0");
                customsRecord.setGlzt("0");
                customsRecord.setApplyCheck("0");
                customsRecord.setEntryDate(new Date());
                customsRecord.setCompany(deptEntity.getCompany());
                insertList.add(customsRecord);

            }
            if (insertList.size() > 0) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                this.saveBatch(insertList);
            }
            if (run.getReturnCode() == null) {
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        interfaceCode.setReturnStateInfo(run);
        interfaceCode.setGlobalInfo(globalInfo);
        return JSON.toJSONString(interfaceCode);
    }

    @Override
    public String getCustomsUploadResult(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                         HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        AuthDateReq data = null;
        CustomsResData resData = new CustomsResData();
        try {
            data = JSONObject.parseObject(map.get("data"), AuthDateReq.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        if (StringUtils.isBlank(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        if (StringUtils.isBlank(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
        String dbName = null;
        if (deptEntity != null && deptEntity.getDbName() != null) {
            dbName = deptEntity.getDbName();
        } else {
            ReturnStateInfo runInfo = new ReturnStateInfo();
            runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
            runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(runInfo);
            return JSON.toJSONString(interfaceCode);
        }
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        QueryWrapper<TdxUploadRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_no", data.getBatchNo());
        Integer resultNum = Math.toIntExact(tdxUploadRecordService.getBaseMapper().selectCount(queryWrapper));
        Integer r = this.baseMapper.selectUploadResult(data.getBatchNo());

        resData.setBuyerTaxNo(data.getBuyerTaxNo());
        resData.setBatchNo(data.getBatchNo());
        if (resultNum == 0 || r > 0) {
            resData.setContentRows(0);
            resData.setBatchState("N");
            String resultData = JSON.toJSONString(resData);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);

            interfaceCode.setData(Base64.encode(resultData));

            return JSON.toJSONString(interfaceCode);
        }
        List<CustomsUploadBackInfo> authStatusList = this.baseMapper.selectUploadResultBack(data.getBatchNo());
        DecimalFormat df = new DecimalFormat("#0.00");
        resData.setBatchState("Y");
        resData.setContentRows(authStatusList.size());
        resData.setList(authStatusList);
        String resultData = JSON.toJSONString(resData);
        run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
        run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
        interfaceCode.setReturnStateInfo(run);
        interfaceCode.setGlobalInfo(globalInfo);

        interfaceCode.setData(Base64.encode(resultData));

        return JSON.toJSONString(interfaceCode);
    }

    /**
     * 海关缴款书入账接口
     *
     * @param globalInfo   请求信息
     *                     请求信息
     * @param requestParam
     * @param request      请求信息
     * @param response     请求信息
     * @param authorize    请求信息
     * @return
     */
    @Override
    public String customspcInAccount(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request, HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        CustomsInAccountEntity custom = null;
        try {
            custom = JSONObject.parseObject(requestParam.get("data"), CustomsInAccountEntity.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            return JSONObject.toJSONString(interfaceCode);
        }
        try {

            if (StringUtils.isBlank(custom.getBuyerTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSONObject.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(custom.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setReturnStateInfo(runInfo);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);
            }
            if (StringUtils.isBlank(custom.getBatchNo()) || custom.getContentRows() == null) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSONObject.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            // 判断批次号是否申请过
            int batChCount = super.baseMapper.countBatChno(custom.getBatchNo());
            if (batChCount > 0) {
                run.setReturnCode("9999");
                run.setReturnMessage("批次号已存在");
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSONObject.toJSONString(interfaceCode);
            }
            List<CustomsInAccountData> customsList = custom.getCustomsList();
            if (customsList.size() != custom.getContentRows()) {
                run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSONObject.toJSONString(interfaceCode);
            }
            List<CustomsInAccountData> accountReturnList = new ArrayList<>();
            for (CustomsInAccountData customs : customsList) {
                if(customs.getInAccountDate()==null||"".equals(customs.getInAccountDate().trim())){
                    customs.setInAccountDate(null);
                }
                if (StringUtils.isBlank(customs.getCustomsCode())) {
                    customs.setStatus("1");
                    customs.setFailureReason("9");
                    accountReturnList.add(customs);
                    continue;
                }

                customs.setUuid(customs.getCustomsCode());
                if (StringUtils.isBlank(customs.getInAccountStatus())) {
                    customs.setStatus("1");
                    customs.setFailureReason("3");
                    accountReturnList.add(customs);
                    continue;
                }
                if (!"1".equals(customs.getInAccountStatus())
                        && !"0".equals(customs.getInAccountStatus())) {
                    customs.setStatus("1");
                    customs.setFailureReason("13");
                    accountReturnList.add(customs);
                    continue;
                }
                // 是否入账为1时，校验字段非空
                if ("1".equals(customs.getInAccountStatus())) {
                    if (StringUtils.isBlank(customs.getInAccountDate())
                            || (!CheckUtils.stringLength(customs.getInAccountDate(), 14))) {
                        customs.setStatus("1");
                        customs.setFailureReason("4");
                        accountReturnList.add(customs);
                        continue;
                    }
                    if (StringUtils.isBlank(customs.getVoucherNumber())) {
                        customs.setStatus("1");
                        customs.setFailureReason("5");
                        accountReturnList.add(customs);
                        continue;
                    }
                    if (StringUtils.isBlank(customs.getDocumentNumber())) {
                        customs.setStatus("1");
                        customs.setFailureReason("6");
                        accountReturnList.add(customs);
                        continue;
                    }
                } else {
                    customs.setInAccountDate("");
                }
                // 判断抵帐表是否有票
                TdxCustomsRecord customsRecord = super.baseMapper.getCustomsRecord(custom.getBuyerTaxNo(), customs.getCustomsCode());
                if (customsRecord == null) {
                    log.info("线程{},抵账无此票{}", Thread.currentThread().getId(), customs.getCustomsCode());
                    customs.setStatus("1");
                    customs.setFailureReason("2");
                } else {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    int updateResult = baseMapper.setAccount(customs);
                    //int updateResult = super.baseMapper.updateById(customsRecord);
                    if (updateResult > 0) {
                        customs.setStatus("0");
                        customs.setFailureReason("");
                        log.info("线程{},入账完成{}", Thread.currentThread().getId(), customs.getUuid());
                    } else {
                        customs.setStatus("1");
                        customs.setFailureReason("99");
                        log.info("线程{},入账异常{}", Thread.currentThread().getId(), customs.getUuid());
                    }
                }
                accountReturnList.add(customs);
            }
            super.baseMapper.saveAccountBat(accountReturnList, custom.getBatchNo());
            // 返回报文拼接
            String data = this.returnPar(accountReturnList, custom);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encode(data));
            return JSONObject.toJSONString(interfaceCode);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            return JSONObject.toJSONString(interfaceCode);
        }
    }

    private String returnPar(List<CustomsInAccountData> customList, CustomsInAccountEntity customsInAccountEntity) {
        CustomsInAccountEntity customEntity = new CustomsInAccountEntity();
        List<CustomsInAccountData> dataList = new ArrayList<>();
        for (CustomsInAccountData customs : customList) {
            CustomsInAccountData data = new CustomsInAccountData();
            data.setCustomsCode(customs.getCustomsCode());
            data.setStatus(customs.getStatus());
            data.setFailureReason(customs.getFailureReason());
            dataList.add(data);
        }
        customEntity.setBatchNo(customsInAccountEntity.getBatchNo());
        customEntity.setBuyerTaxNo(customsInAccountEntity.getBuyerTaxNo());
        customEntity.setCustomsList(dataList);
        String data = JSON.toJSONString(customEntity);
        log.info("线程{},海关缴款书入账结果信息{}", Thread.currentThread().getId(), data);
        return data;
    }

    public ReturnStateInfo getCheckData(List<CustomsApplyReq> authStateList, Integer contentRows) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (contentRows == null || authStateList.size() != contentRows) {
            run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
            return run;
        }

        for (CustomsApplyReq customsApplyReq : authStateList) {

            if (StringUtils.isBlank(customsApplyReq.getApplyRzlx())) {
                run.setReturnCode(ReturnCodeEnum.RZLXBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.RZLXBNWK.getFhzMc(ReturnCodeEnum.RZLXBNWK.getIndex()));
                return run;
            }
            if (StringUtils.isBlank(customsApplyReq.getCustomsNo())) {
                run.setReturnCode(ReturnCodeEnum.JKSHMBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JKSHMBNWK.getFhzMc(ReturnCodeEnum.JKSHMBNWK.getIndex()));
                return run;
            }
            if (StringUtils.isBlank(customsApplyReq.getFillInDate())) {
                run.setReturnCode(ReturnCodeEnum.TFRQBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.TFRQBNWK.getFhzMc(ReturnCodeEnum.TFRQBNWK.getIndex()));
                return run;
            }
            if (StringUtils.isBlank(customsApplyReq.getApplyTaxPeriod())
                    || (customsApplyReq.getApplyTaxPeriod()).length() != 6) {
                run.setReturnCode(ReturnCodeEnum.SKSSQBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SKSSQBF.getFhzMc(ReturnCodeEnum.SKSSQBF.getIndex()));
                return run;
            }
            if (StringUtils.isBlank(customsApplyReq.getBuyerTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                return run;
            }

            if (StringUtils.isBlank(customsApplyReq.getYxse())) {
                run.setReturnCode(ReturnCodeEnum.DKSEBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.DKSEBNWK.getFhzMc(ReturnCodeEnum.DKSEBNWK.getIndex()));
                return run;
            }

            if (StringUtils.isBlank(customsApplyReq.getRzhUser())) {
                run.setReturnCode(ReturnCodeEnum.RZRBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.RZRBNWK.getFhzMc(ReturnCodeEnum.RZRBNWK.getIndex()));
                return run;
            }
        }
        return run;
    }

    public ReturnStateInfo checkUploadData(List<CustomsApplyReq> authStateList, Integer contentRows,
                                           String buyerTaxNo) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (contentRows == null || authStateList.size() != contentRows) {
            run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
            return run;
        }

        for (CustomsApplyReq customsApplyReq : authStateList) {

            if (StringUtils.isBlank(customsApplyReq.getCustomsNo())) {
                run.setReturnCode("2035");
                run.setReturnMessage("海关缴款书号码不可为空");
                return run;
            }
            if (StringUtils.isBlank(customsApplyReq.getFillInDate())) {
                run.setReturnCode("2036");
                run.setReturnMessage("填发日期不可为空");
                return run;
            }

            if (StringUtils.isBlank(customsApplyReq.getAmount())) {
                run.setReturnCode("2037");
                run.setReturnMessage("税款金额不可为空");
                return run;
            }

            TdxCustomsRecord customsRecord =
                    this.baseMapper.getCustomsRecord(buyerTaxNo, customsApplyReq.getCustomsNo());

            if (customsRecord != null) {
                run.setReturnCode("2038");
                run.setReturnMessage("缴款书已存在,号码：" + customsApplyReq.getCustomsNo());
                return run;
            }
        }
        return run;
    }

    public List<AuthRecord> bulidAuthRecord(List<CustomsApplyReq> list, String batchNo) {
        List<AuthRecord> authRecordList = new ArrayList<>();
        for (CustomsApplyReq customsApplyReq : list) {
            AuthRecord authRecord = new AuthRecord();
            authRecord.setBatchNo(batchNo);
            if (StringUtils.isBlank(customsApplyReq.getApplyRzlx())) {
                authRecord.setRzlx("1");
            } else {
                authRecord.setRzlx(customsApplyReq.getApplyRzlx());
            }
            authRecord.setApplyTaxPeriod(customsApplyReq.getApplyTaxPeriod());
            authRecord.setBuyerTaxNo(customsApplyReq.getBuyerTaxNo());
            authRecord.setYxse(customsApplyReq.getYxse());
            authRecord.setInvoiceType("17");
            authRecord.setCustomsCode(customsApplyReq.getCustomsNo());
            authRecord.setCreateDate(new Date());
            authRecordList.add(authRecord);
        }
        return authRecordList;
    }

    public List<TdxUploadRecord> buliduploadRecord(List<CustomsApplyReq> list, String batchNo) {
        List<TdxUploadRecord> recordList = new ArrayList<>();
        for (CustomsApplyReq customsApplyReq : list) {
            TdxUploadRecord record = new TdxUploadRecord();
            record.setBatchNo(batchNo);
            record.setAmount(customsApplyReq.getAmount());
            record.setCustomsCode(customsApplyReq.getCustomsNo());
            record.setFillInDate(customsApplyReq.getFillInDate());
            record.setCreateDate(new Date());
            recordList.add(record);
        }
        return recordList;
    }

    public CustomsResInfo getCustomsInfo(TdxCustomsRecord customs) {

        CustomsResInfo info = new CustomsResInfo();
        info.setCustomsNo(customs.getCustomsCode());
        info.setFillInDate(new SimpleDateFormat("yyyyMMdd").format(customs.getFillInDate()));
        info.setBuyerTaxNo(customs.getGfTaxNo());
        info.setAmount(customs.getTaxAmount());
        info.setCurrentTaxPeriod(customs.getDqskssq());
        info.setLegalizeEndDate(customs.getGxjzr());
        info.setLegalizeInvoiceDateBegin(customs.getGxfwq());
        info.setLegalizeInvoiceDateEnd(customs.getGxfwz());
        if (customs.getConfirmDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(customs.getConfirmDate()));
        }
        info.setLegalizeState(customs.getRzhYesorno());
        if (customs.getRzhBelongDate() == null) {
            info.setLegalizeBelongDate("");
        } else {
            info.setLegalizeBelongDate(customs.getRzhBelongDate());
        }

        if (customs.getRzlx() == null) {
            info.setRzlx("");
        } else {
            info.setRzlx(customs.getRzlx());
        }

        if (StringUtils.isNotBlank(customs.getGlzt())) {
            info.setGlzt(customs.getGlzt());
        } else {
            info.setGlzt("");
        }
        if (StringUtils.isNotBlank(customs.getXxly())) {
            info.setXxly(customs.getXxly());
        } else {
            info.setXxly("");
        }
        if (StringUtils.isNotBlank(customs.getYxTaxAmount())) {
            info.setYxse(customs.getYxTaxAmount());
        } else {
            info.setYxse("");
        }
        if (StringUtils.isNotBlank(customs.getEntryDiscrepancy())) {
            info.setIsDiscrepancy(customs.getEntryDiscrepancy());
        } else {
            info.setIsDiscrepancy("");
        }
        return info;
    }

    public Integer selectByAllCount(CustomsCollectPo data) {

        QueryWrapper<TdxCustomsRecord> query = new QueryWrapper<>();
        query.eq("gf_tax_no", data.getBuyerTaxNo());
        query.between("create_date", CommonUtils.kprqFormat(data.getAcquisitionDateBegin())
                , CommonUtils.kprqFormat(data.getAcquisitionDateEnd()));
        return Math.toIntExact(this.baseMapper.selectCount(query));
    }

    public List<TdxCustomsRecord> selectCustoms(CustomsCollectPo data, int startRow, int endRow) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("startDate", data.getAcquisitionDateBegin());
        map.put("endDate", data.getAcquisitionDateEnd());
        map.put("start", startRow - 1);
        map.put("num", endRow);
        return super.baseMapper.selectCustoms(map);
    }

    public Integer selectByStateAllCount(String statusChangeDateBegin, String statusChangeDateEnd, String buyerTaxNo) {
        QueryWrapper<TdxCustomsRecord> query = new QueryWrapper<>();
        query.eq("gf_tax_no", buyerTaxNo);
        query.between("update_date", DateUtils.strToDate(statusChangeDateBegin,"yyyyMMddHHmmss"), DateUtils.strToDate(statusChangeDateEnd,"yyyyMMddHHmmss"));

        return Math.toIntExact(this.baseMapper.selectCount(query));
    }

    public List<CustomsResInfo> selectByState(String statusChangeDateBegin, String statusChangeDateEnd,
                                              String buyerTaxNo, Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", buyerTaxNo);
        map.put("startDate", statusChangeDateBegin);
        map.put("endDate", statusChangeDateEnd);
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectByState(map);
    }

    public State getStateInfo(State state) {
        DecimalFormat df = new DecimalFormat("#0.00");
        State info = new State();
        info.setInvoiceCode(state.getInvoiceCode());
        info.setInvoiceNo(state.getInvoiceNo());
        info.setInvoiceStatus(state.getInvoiceStatus());
        if (state.getQsStatus() == null) {
            info.setQsStatus("");
        } else {
            info.setQsStatus(state.getQsStatus());
        }
        if (state.getQsUser() == null) {
            info.setQsUser("");
        } else {
            info.setQsUser(state.getQsUser());
        }
        if (state.getQsDate() == null) {
            info.setQsDate("");
        } else {
            info.setQsDate(state.getQsDate());
        }
        if (state.getLegalizeState() == null) {
            info.setLegalizeState("");
        } else {
            info.setLegalizeState(state.getLegalizeState());
        }
        if (state.getLegalizeDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(state.getLegalizeDate());
        }
        if (state.getLegalizeBelongDate() == null) {
            info.setLegalizeBelongDate("");
        } else {
            info.setLegalizeBelongDate(state.getLegalizeBelongDate());
        }
        if (state.getRzlx() == null) {
            info.setRzlx("");
        } else {
            info.setRzlx(state.getRzlx());
        }
        if (state.getManagementStatus() == null) {
            info.setManagementStatus("");
        } else {
            info.setManagementStatus(state.getManagementStatus());
        }
        if (state.getInformationSources() == null) {
            info.setInformationSources("");
        } else {
            info.setInformationSources(state.getInformationSources());
        }
        if (StringUtils.isBlank(state.getTaxCredit())) {
            info.setTaxCredit("");
        } else {
            info.setTaxCredit(df.format(new BigDecimal(state.getTaxCredit())));
        }
        if (state.getOverdueCheckMark() == null) {
            info.setOverdueCheckMark("");
        } else {
            info.setOverdueCheckMark(state.getOverdueCheckMark());
        }
        if (state.getExceptionType() == null) {
            info.setExceptionType("");
        } else {
            info.setExceptionType(state.getExceptionType());
        }
        return info;
    }

    public ReturnStateInfo getCheck(CustomsCollectPo data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }

        if (CheckUtils.isNullOrEmpty(data.getAcquisitionDateBegin())
                || (!CheckUtils.stringLength(data.getAcquisitionDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getAcquisitionDateEnd())
                || (!CheckUtils.stringLength(data.getAcquisitionDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        return run;
    }

    public ReturnStateInfo getCheckState(StateData data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo()) || !(CheckUtils.stringLength(data.getBuyerTaxNo(), 15)
                || CheckUtils.stringLength(data.getBuyerTaxNo(), 18))) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateBegin())
                || (!CheckUtils.stringLength(data.getStatusChangeDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateEnd())
                || (!CheckUtils.stringLength(data.getStatusChangeDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        return run;
    }


    /**
     * 海关缴款书查询
     *
     * @param globalInfo 请求信息
     *                   请求信息
     * @param map
     * @param request    请求信息
     * @param response   请求信息
     * @param authorize  请求信息
     * @return
     */
    @Override
    public String getSingle(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request, HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        try {
            JSONObject jsonObject = JSONObject.parseObject(map.get("data"));
            String taxNo = jsonObject.getString("buyerTaxNo");
            String customsNo = jsonObject.getString("customsNo");
            if (taxNo == null || "".equals(taxNo.trim())) {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            if( customsNo == null || "".equals(customsNo.trim())){
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JKSHMBNWK.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JKSHMBNWK.getFhzMc(ReturnCodeEnum.JKSHMBNWK.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(taxNo);
            String dbName;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BUSINESS_READ);
            TdxCustomsRecord customsRecord = this.baseMapper.getCustomsRecordByCode(customsNo);
            if (customsRecord != null) {
                TdxCustomsRecordVO vo = getRecord(customsRecord);
                run.setReturnCode("0000");
                run.setReturnMessage("处理成功");
                String globalJson = null;
                String runJson = null;
                String data = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                    data = JSON.toJSONString(vo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData(Base64.encode(data));
                return JSON.toJSONString(interfaceCode);
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.WCXDSJ.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.WCXDSJ.getFhzMc(ReturnCodeEnum.WCXDSJ.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            ReturnStateInfo runInfo = new ReturnStateInfo();
            runInfo.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            runInfo.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(runInfo);
            return JSON.toJSONString(interfaceCode);
        }
    }

    private TdxCustomsRecordVO getRecord(TdxCustomsRecord customsRecord) {
        TdxCustomsRecordVO vo = new TdxCustomsRecordVO();
        vo.setCustomsNo(customsRecord.getCustomsCode() == null ? "" : customsRecord.getCustomsCode());
        vo.setBuyerTaxNo(customsRecord.getGfTaxNo() == null ? "" : customsRecord.getGfTaxNo());
        vo.setFillInDate(customsRecord.getFillInDate() == null ? "" : DateUtil.format(customsRecord.getFillInDate(), "yyyyMMdd"));
        vo.setAmount(customsRecord.getTaxAmount());
        // 是否认证0未认证，1已认证抵扣，2已认证不抵扣
        if (customsRecord.getRzhYesorno() != null && customsRecord.getRzhYesorno().equals("0")) {
            vo.setLegalizeState("0");
        } else if (customsRecord.getRzhYesorno() != null && (customsRecord.getRzhYesorno().equals("1") || customsRecord.getRzhYesorno().equals("2"))) {
            vo.setLegalizeState("1");
        } else {
            vo.setLegalizeState("");
        }
        vo.setLegalizeDate(customsRecord.getRzhDate() == null ? "" : DateUtil.format(customsRecord.getRzhDate(), "yyyyMMdd"));
        vo.setLegalizeBelongDate(customsRecord.getRzhBelongDate() == null ? "" : customsRecord.getRzhBelongDate());
        // 文档 0-未抵扣1-抵扣 2-退税 4-不抵扣
        vo.setXxly(customsRecord.getXxly() == null ? "" : customsRecord.getXxly());
        vo.setYxse(customsRecord.getYxTaxAmount() == null ? "" : customsRecord.getYxTaxAmount());
        vo.setGlzt(customsRecord.getGlzt() == null ? "" : customsRecord.getGlzt());
        vo.setIsDiscrepancy(customsRecord.getEntryDiscrepancy() == null ? "" : customsRecord.getEntryDiscrepancy());
        vo.setRzlx(customsRecord.getRzlx() == null ? "" : customsRecord.getRzlx());
        return vo;
    }
}
