package com.jianshui.income.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.domain.entity.SysUser;
import com.jianshui.common.enums.ErrorCode;
import com.jianshui.common.utils.DateUtils;
import com.jianshui.common.utils.SecurityUtils;
import com.jianshui.common.utils.ValidateUtils;
import com.jianshui.common.utils.uuid.IdUtils;
import com.jianshui.income.constant.elephant.ElephantAuthConstants;
import com.jianshui.income.domain.IncomeInvoiceAuthStatus;
import com.jianshui.income.domain.dto.*;
import com.jianshui.income.domain.dto.elephant.*;
import com.jianshui.income.domain.dto.elephant.GetInvoiceRespCommonDTO;
import com.jianshui.income.domain.entity.*;
import com.jianshui.income.domain.vo.*;
import com.jianshui.income.domain.vo.elephant.*;
import com.jianshui.income.enums.InitActionTypeEnum;
import com.jianshui.income.mapper.*;
import com.jianshui.income.service.IAuthInvoice;
import com.jianshui.system.service.ICompanyservicePropService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.jianshui.income.utils.elephant.ElephantCompanyserviceUtils.request;


/**
 * 大象进项发票认证
 *
 * @author xkng
 * @date 2022/9/9 16:03
 */
@Component(value = "elephant_auth") // 这里是后台字典的服务配置键值 配置的
public class EleAuthInvoiceImpl implements IAuthInvoice {

    private static final Logger log = LoggerFactory.getLogger(EleAuthInvoiceImpl.class);

    @Autowired
    private ICompanyservicePropService propService;

    @Autowired
    private IncomeInvoiceAuthMapper incomeInvoiceAuthMapper;

    @Autowired
    private IncomeInvoiceAuthAuthenticationMapper authenticationMapper;

    @Autowired
    private IncomeInvoiceAuthQueryResultMapper queryResultMapper;

    @Autowired
    private IncomeInvoiceAuthConfirmationResultsMapper confirmationResultsMapper;

    @Autowired
    private IncomeInvoiceAuthCompanyStatisticsMapper companyStatisticsMapper;

    @Autowired
    private IncomeInvoiceAuthEnterpriseArchivesMapper enterpriseArchivesMapper;

    @Autowired
    private IncomeInvoiceAuthAccountMapper accountMapper;

    @Autowired
    private IncomeInvoiceAuthStatusMapper statusMapper;


    //    =================发票采集===========================
    @Autowired
    private IncomeInvoiceAuthCompanyStatisticsMapper incomeInvoiceTwoCompanyStatisticsMapper;

    @Autowired
    private IncomeInvoiceAuthCompanyStatisticsDetailMapper incomeInvoiceCompanyStatisticsDetailMapper;

    @Autowired
    private IncomeInvoiceAuthStatisticsMapper incomeInvoiceTwoStatisticsMapper;

    @Autowired
    private IncomeInvoiceAuthDetailMapper incomeInvoiceAuthDetailMapper;

    @Autowired
    private IncomeInvoiceAuthCarMapper incomeInvoiceAuthCarMapper;


    /**
     * 状态采集
     *
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/14 20:03
     */
    @Override
    public AjaxResult statusAcquisition(@Valid IncomeStatusCollectionDTO incomeStatusCollectionDTO, Companyservice companyservice, List<IncomeInvoiceAuth> allIncomeInvoiceList, List<IncomeInvoiceAuthStatus> allIncomeInvoiceTwoStatusList) throws Exception {

        //数据格式转化
        StatusCollectionDTO statusCollectionDTO = BeanUtil.copyProperties(incomeStatusCollectionDTO, StatusCollectionDTO.class);
        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.STATUS_ACQUISTION, statusCollectionDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【状态采集】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        try {
            if (resp.getString("ZTDM").equals("0000")) {
                log.info("\"【进项服务类】【大象】【状态采集】请求成功。\"");
                GetInvoiceRespCommonDTO getInvoiceRespCommonDTO = resp.toJavaObject(GetInvoiceRespCommonDTO.class);
                // 请求结果-获取发票状态结果
                List<IncomeInvoiceAuthStatus> incomeInvoiceTwoStatusList = getInvoiceRespCommonDTO.getFPZHXX();

                // 数据库查询-所有发票信息记录
                if (CollectionUtils.isEmpty(allIncomeInvoiceList)) {
                    allIncomeInvoiceList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(new IncomeInvoiceAuth());

                }
                if (CollectionUtils.isEmpty(allIncomeInvoiceTwoStatusList)) {
                    allIncomeInvoiceTwoStatusList = statusMapper.selectIncomeInvoiceAuthStatusList(new IncomeInvoiceAuthStatus());
                }
                // 数据库查询-所有发票状态记录
                if (!CollectionUtils.isEmpty(incomeInvoiceTwoStatusList)) {
                    // 遍历发票状态记录
                    for (IncomeInvoiceAuthStatus invoiceTwoStatus : incomeInvoiceTwoStatusList) {
                        // 从所有发票中找到那张状态修改的发票
                        Optional<IncomeInvoiceAuth> incomeInvoiceOpt = allIncomeInvoiceList.stream().filter(item -> {
                            if (invoiceTwoStatus.getFphm().equals(item.getFphm()) && invoiceTwoStatus.getFpdm().equals(item.getFpdm())) {
                                return true;
                            } else {
                                return false;
                            }
                        }).findFirst();
                        // 判断这个状态之前有没有处理过
                        Optional<IncomeInvoiceAuthStatus> incomeInvoiceStatusOpt = allIncomeInvoiceTwoStatusList.stream().filter(item -> {
                            if (item.equals(invoiceTwoStatus)) {
                                return true;
                            } else {
                                return false;
                            }
                        }).findFirst();
                        // 只有 这张发票我们系统里有 同时这条状态记录之前没处理过 才会对状态记录进行处理
                        if (incomeInvoiceOpt.isPresent() && !incomeInvoiceStatusOpt.isPresent()) {
                            // 处理发票的状态
                            IncomeInvoiceAuth incomeInvoice = incomeInvoiceOpt.get();
                            incomeInvoice.setFpzt(invoiceTwoStatus.getFpzt());
                            if (invoiceTwoStatus.getRzzt() != null) {
                                incomeInvoice.setRzzt(invoiceTwoStatus.getRzzt());
                                incomeInvoice.setRzstatus("0");
                                if ("1".equals(invoiceTwoStatus.getRzzt())) {
                                    incomeInvoice.setRzstatus("2");
                                }
                            }
                            if (invoiceTwoStatus.getRzrq() != null) {
                                incomeInvoice.setRzrq(invoiceTwoStatus.getRzrq());
                            }
                            incomeInvoice.setRzsq(invoiceTwoStatus.getRzsq());
                            incomeInvoice.setYxse(invoiceTwoStatus.getYxse());
                            incomeInvoice.setYqkgxbz(invoiceTwoStatus.getYqkgxbz());
                            incomeInvoice.setGlzt(invoiceTwoStatus.getGlzt());
                            incomeInvoice.setRzlx(invoiceTwoStatus.getRzlx());
                            incomeInvoice.setDkse(invoiceTwoStatus.getDkse());
                            incomeInvoice.setBdkyy(invoiceTwoStatus.getBdkyy());
                            incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(incomeInvoice);
                            // 新增一条发票状态
                            invoiceTwoStatus.setId(UUID.randomUUID().toString().replace("-", ""));
                            invoiceTwoStatus.setInvoiceId(incomeInvoice.getId());
                            invoiceTwoStatus.setCreateTime(new Date());
                            statusMapper.insertIncomeInvoiceAuthStatus(invoiceTwoStatus);
                        }
                    }
                }
                // 获取总行数 本次查询行数 和开始行数
                int zhs = resp.getIntValue("ZHS");
                int bcqqfhhs = resp.getIntValue("BCQQFHHS");
                int kshs = resp.getIntValue("KSHS");
                // 如果 当前已递归的行数 < 总行数 则再递归
                if ((kshs + bcqqfhhs - 1) < zhs) {
                    incomeStatusCollectionDTO.setKSHS(String.valueOf((bcqqfhhs + kshs)));
                    this.statusAcquisition(incomeStatusCollectionDTO, companyservice, allIncomeInvoiceList, allIncomeInvoiceTwoStatusList);
                }
            }
        } catch (Exception e) {
            log.error("【进项服务类】【大象】【状态采集】数据解析出现异常。错误信息:{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("状态采集完成");
    }


    /**
     * 申请认证
     *
     * @param incomeApplyLegalizePrimaryDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 11:29
     */
    @Override
    public AjaxResult applyLegalize(IncomeApplyLegalizePrimaryDTO incomeApplyLegalizePrimaryDTO, Companyservice companyservice) throws Exception {


        // 申请认证接口  1校验 2表数据存储  3发起认证
        ApplyLegalizePrimaryDTO applyLegalizePrimaryDTO = BeanUtil.copyProperties(incomeApplyLegalizePrimaryDTO, ApplyLegalizePrimaryDTO.class);
        applyLegalizePrimaryDTO.setFPZHXX(BeanUtil.copyToList(incomeApplyLegalizePrimaryDTO.getFPZHXX(), ApplyLegalizeChildDTO.class));

        // 1.数据校验
        if (BeanUtil.isEmpty(applyLegalizePrimaryDTO) || CollectionUtils.isEmpty(applyLegalizePrimaryDTO.getFPZHXX())) {
            return AjaxResult.error(ErrorCode.PARAM_MISS_ERROR);
        }
        List<ApplyLegalizeChildDTO> applyLegalizeChildDTO = applyLegalizePrimaryDTO.getFPZHXX();
        ValidateUtils.validate(applyLegalizePrimaryDTO);
        ValidateUtils.validate(applyLegalizeChildDTO);

        // 2.数据存储
        String id = "";
        String pch = IdUtils.simpleUUID();
        // 调用后更新结果
        String ids = "";
        pch = incomeApplyLegalizePrimaryDTO.getPCH();
        for (ApplyLegalizeChildDTO legalizeChildDTO : applyLegalizeChildDTO) {

            IncomeInvoiceAuth invoiceAuth = new IncomeInvoiceAuth();
            invoiceAuth.setFphm(legalizeChildDTO.getFPHM());
            invoiceAuth.setFpdm(legalizeChildDTO.getFPDM());
            List<IncomeInvoiceAuth> incomeInvoiceTwoList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceAuth);
            if (CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                continue;
            }

            // 查询认证状态
            IncomeInvoiceAuthAuthentication authenticationQuery = new IncomeInvoiceAuthAuthentication();
            authenticationQuery.setFpdm(legalizeChildDTO.getFPDM());
            authenticationQuery.setFphm(legalizeChildDTO.getFPHM());
            List<IncomeInvoiceAuthAuthentication> authenticationList = authenticationMapper.selectIncomeInvoiceAuthAuthenticationList(authenticationQuery);

            IncomeInvoiceAuthAuthentication authentication = new IncomeInvoiceAuthAuthentication();
            if (CollectionUtils.isEmpty(authenticationList)) {
                id = IdUtils.simpleUUID();
                authentication = BeanUtil.copyProperties(legalizeChildDTO, IncomeInvoiceAuthAuthentication.class);
                authentication.setPch(pch);
                authentication.setId(id);
                authentication.setInvoiceId(incomeInvoiceTwoList.get(0).getId());
                authentication.setGmfsbh(applyLegalizePrimaryDTO.getGMFSBH());
                authentication.setCreateTime(new Date());
                authenticationMapper.insertIncomeInvoiceAuthAuthentication(authentication);
            } else {
                authentication = authenticationList.get(0);
                id = authentication.getId();
                authentication.setInvoiceId(incomeInvoiceTwoList.get(0).getId());
                authentication.setGmfsbh(applyLegalizePrimaryDTO.getGMFSBH());
                authentication.setUpdateTime(new Date());
                authenticationMapper.updateIncomeInvoiceAuthAuthentication(authentication);
            }
            //累加多条id
            ids = ids + "," + id;

        }
        applyLegalizePrimaryDTO.setPCH(pch);
        // 设置总行数
        applyLegalizePrimaryDTO.setFHHS(applyLegalizeChildDTO.size());

        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.APPLY_LEGALIZE, applyLegalizePrimaryDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【申请认证】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        //返回解析
        ApplyLegalizeVO applyLegalizeVO = BeanUtil.copyProperties(resp, ApplyLegalizeVO.class);
        IncomeApplyLegalizeVO incomeApplyLegalizeVO = BeanUtil.copyProperties(applyLegalizeVO, IncomeApplyLegalizeVO.class);

        if ("0000".equals(incomeApplyLegalizeVO.getZTDM())) {
            String[] idTemp = ids.split(",");
            String invoiceIds = "";

            String pchTask = "";
            String gmfsbhTask = "";
            String identityTask = "";
            String taxnoTask = "";

            for (String idt : idTemp) {
                //更新返回信息
                IncomeInvoiceAuthAuthentication authenticationResult = new IncomeInvoiceAuthAuthentication();
                authenticationResult.setId(idt);
                authenticationResult.setZtdm(incomeApplyLegalizeVO.getZTDM());
                authenticationResult.setZtxx(incomeApplyLegalizeVO.getZTXX());
                authenticationMapper.updateIncomeInvoiceAuthAuthentication(authenticationResult);

                IncomeInvoiceAuthAuthentication authentication = authenticationMapper.selectIncomeInvoiceAuthAuthenticationById(idt);
                if (BeanUtil.isNotEmpty(authentication)) {
                    //发起成功的情况更新
                    String invoiceId = authentication.getInvoiceId() != null ? authentication.getInvoiceId() : "";
                    IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                    invoiceTwo.setId(invoiceId);
                    invoiceTwo.setRzstatus("1");
                    incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(invoiceTwo);

                    IncomeInvoiceAuth invoiceAuth = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthById(invoiceId);

                    pchTask = authentication.getPch();
                    gmfsbhTask = authentication.getGmfsbh();
                    identityTask = String.valueOf(invoiceAuth.getIdentity());
                    taxnoTask = invoiceAuth.getTaxno();

                    invoiceIds = invoiceIds + "," + invoiceId;
                }
                incomeApplyLegalizeVO.setId(invoiceIds);
            }

            //更新定时任务表
            IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
            queryResult.setId(IdUtils.simpleUUID());
            queryResult.setPch(pchTask);
            queryResult.setInitationType(InitActionTypeEnum.APPLY_LEGALIZE.getCode());
            queryResult.setInitationTime(new Date());
            queryResult.setInitationStatus("0");
            queryResult.setGmfsbh(gmfsbhTask);
            queryResult.setIdentity(identityTask);
            queryResult.setTaxno(taxnoTask);
            queryResult.setInitationNum(0L);
            queryResult.setCreateTime(new Date());
            queryResult.setUpdateTime(new Date());
            queryResultMapper.insertIncomeInvoiceAuthQueryResult(queryResult);

        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }

        return AjaxResult.success(incomeApplyLegalizeVO);
    }

    /**
     * 发票认证查询接口
     *
     * @param incomeApplyLegalizeResultDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author k
     * @date 2022/9/17 11:47
     */
    @Override
    public AjaxResult applyLegalizeResult(IncomeApplyLegalizeResultDTO incomeApplyLegalizeResultDTO, Companyservice companyservice) throws Exception {

        ApplyLegalizeResultDTO applyLegalizeResultDTO = BeanUtil.copyProperties(incomeApplyLegalizeResultDTO, ApplyLegalizeResultDTO.class);

       // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.APPLY_LEGALIZE_RESULT, applyLegalizeResultDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【发票认证查询】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        //返回解析
        ApplyLegalizeResultVO applyLegalizeResultVO = BeanUtil.copyProperties(resp, ApplyLegalizeResultVO.class);
        IncomeApplyLegalizeResultVO incomeApplyLegalizeResultVO = BeanUtil.copyProperties(applyLegalizeResultVO, IncomeApplyLegalizeResultVO.class);
        incomeApplyLegalizeResultVO.setFPZHXX(BeanUtil.copyToList(applyLegalizeResultVO.getFPZHXX(), ApplyLegalizeResultChildVO.class));

        String pch = incomeApplyLegalizeResultDTO.getPCH();

        String ztdm = incomeApplyLegalizeResultVO.getZTDM() != null ? incomeApplyLegalizeResultVO.getZTDM() : "";
        String pczt = incomeApplyLegalizeResultVO.getPCZT() != null ? incomeApplyLegalizeResultVO.getPCZT() : "";
        String invoiceId = "";
        // 返回状态-大象请求状态
        if ("0000".equals(ztdm)) {
            if("Y".equals(pczt)){
                List<ApplyLegalizeResultChildVO> FPZHXX = incomeApplyLegalizeResultVO.getFPZHXX();
                for (ApplyLegalizeResultChildVO fpzhxx : FPZHXX) {

                    //查询数据
                    IncomeInvoiceAuthAuthentication authenticationQuery = new IncomeInvoiceAuthAuthentication();
                    authenticationQuery.setPch(pch);
                    authenticationQuery.setFphm(fpzhxx.getFPHM());
                    authenticationQuery.setFpdm(fpzhxx.getFPDM());
                    List<IncomeInvoiceAuthAuthentication> authenticationList = authenticationMapper.selectIncomeInvoiceAuthAuthenticationList(authenticationQuery);
                    if (CollectionUtils.isEmpty(authenticationList)) {
                        continue;
                    }
                    //更新认证结果
                    IncomeInvoiceAuth authentication;
                    authentication = BeanUtil.copyProperties(fpzhxx, IncomeInvoiceAuth.class);
                    authentication.setId(authenticationList.get(0).getId());
                    authentication.setPch(pch);
                    authentication.setZtdm(incomeApplyLegalizeResultVO.getZTDM());
                    authentication.setZtxx(incomeApplyLegalizeResultVO.getZTXX());
                    authentication.setPczt(incomeApplyLegalizeResultVO.getPCZT());
                    authentication.setUpdateTime(new Date());
                    incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(authentication);

                    //大象是如果失败原因存在就是认证失败
                    String rzzt = fpzhxx.getRZZT() != null ? fpzhxx.getRZZT() : "";
                    String sbyy = fpzhxx.getSBYY() != null ? fpzhxx.getSBYY() : "";
                    String rzlx = fpzhxx.getRZLX() != null ? fpzhxx.getRZLX() : "";

                    if ("0".equals(rzzt)) {
                        rzzt = "0";
                        if (StrUtil.isNotEmpty(sbyy)) {
                            rzzt = "3";
                        }
                    }
                    if ("1".equals(rzzt)) {
                        rzzt = "2";
                    }

                    //更新认证状态
                    invoiceId = authentication.getInvoiceId() != null ? authentication.getInvoiceId() : "";
                    IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                    invoiceTwo.setId(authenticationList.get(0).getInvoiceId());
                    invoiceTwo.setRzzt(fpzhxx.getRZZT() != null ? fpzhxx.getRZZT() : "");
                    invoiceTwo.setRzsq(fpzhxx.getRZSQ() != null ? fpzhxx.getRZSQ() : "");
                    invoiceTwo.setRzrq(fpzhxx.getRZRQ() != null ? fpzhxx.getRZRQ() : "");
                    invoiceTwo.setRzstatus(rzzt);
                    incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(invoiceTwo);
                }
                //更新定时任务表
                IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
                queryResult.setPch(pch);
                List<IncomeInvoiceAuthQueryResult> incomeTwoQueryResults = queryResultMapper.selectIncomeInvoiceAuthQueryResultList(queryResult);
                if (!CollectionUtils.isEmpty(incomeTwoQueryResults)) {
                    queryResult = incomeTwoQueryResults.get(0);
                    queryResult.setInitationType(InitActionTypeEnum.APPLY_LEGALIZE.getCode());
                    queryResult.setInitationTime(new Date());
                    queryResult.setInitationStatus("1");
                    queryResult.setGmfsbh(companyservice.getSellertax());
                    queryResult.setIdentity(String.valueOf(companyservice.getCompanyid()));
                    queryResult.setTaxno(companyservice.getSellertax());
                    queryResult.setInitationNum(0L);
                    queryResult.setUpdateTime(new Date());
                    queryResultMapper.updateIncomeInvoiceAuthQueryResult(queryResult);
                }
            }else if("N".equals(pczt)){
                return AjaxResult.success(incomeApplyLegalizeResultVO);
            }else{
                return AjaxResult.error("系统错误！！！");
            }
        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }
        return AjaxResult.success(incomeApplyLegalizeResultVO);
    }

    /**
     * 申请确认
     *
     * @param incomeApplyConfirmDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 12:03
     */
    @Override
    public AjaxResult applyConfirm(IncomeApplyConfirmDTO incomeApplyConfirmDTO, Companyservice companyservice) throws Exception {

//        SysUser sysUser = SecurityUtils.getLoginUser().getUser(); // 获取当前用户

        ApplyConfirmDTO applyConfirmDTO = BeanUtil.copyProperties(incomeApplyConfirmDTO, ApplyConfirmDTO.class); // 参数转换 方法参数转大象接口需要的参数
        ValidateUtils.validate(applyConfirmDTO); // 大象接口参数校验

        // 参数校验加到接口调用前面
        if (StrUtil.isEmpty(applyConfirmDTO.getRZSKSSQ()) || StrUtil.isEmpty(applyConfirmDTO.getGMFSBH())) {
            log.error("【进项服务类】【大象】【申请确认】无税款所属期及购方税号，请确认。");
            return AjaxResult.error("无税款所属期及购方税号，请确认");
        }

        JSONObject resp = null; // 定义返回值
        try {
            resp = request(ElephantAuthConstants.APPLY_CONFIRM, applyConfirmDTO, companyservice); // 调用接口获取结果
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【申请确认】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        // 校验返回值是不是为空
        if (resp == null) {
            log.error("【进项服务类】【大象】【申请确认】API请求异常，无返回值。");
            return AjaxResult.error("无返回值信息");
        }
        //返回解析
        String id = "";
        String pch = applyConfirmDTO.getPCH(); // 获取参数中的批次号
        String ssq = applyConfirmDTO.getRZSKSSQ(); // 获取参数中的税款所属期
        String gmfsbh = applyConfirmDTO.getGMFSBH(); // 获取参数中的购方税号
        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : ""; // 获取结果中的状态代码
        if (("0000").equals(ztdm)) { // 如果返回为0000说明请求成功
            IncomeInvoiceAuthConfirmationResults confirmationResults = new IncomeInvoiceAuthConfirmationResults(); // 定义查询确认结果参数
            confirmationResults.setGmfsbh(gmfsbh); // 通过购方税号和税款所属期查询确认结果是否存在
            confirmationResults.setTjyf(ssq);
            List<IncomeInvoiceAuthConfirmationResults> confirmationResultsList = confirmationResultsMapper.selectIncomeInvoiceAuthConfirmationResultsList(confirmationResults);

            // 判断是否已申请确认 没有的话新增一条确认结果记录
            if (!CollectionUtils.isEmpty(confirmationResultsList)) {
                confirmationResultsMapper.deleteIncomeInvoiceAuthConfirmationResultsById(confirmationResultsList.get(0).getId());
            }

            IncomeInvoiceAuthConfirmationResults results = new IncomeInvoiceAuthConfirmationResults();
            id = IdUtils.simpleUUID();
            results.setPch(pch);
            results.setGmfsbh(applyConfirmDTO.getGMFSBH());
            results.setId(id);
//            results.setCreateBy(String.valueOf(sysUser.getUserId()));
            results.setCreateTime(new Date());
            results.setTjbz(applyConfirmDTO.getQRBZ());
            results.setQrbz(applyConfirmDTO.getQRBZ());
            results.setSqskssq(ssq);
            results.setTjyf(ssq);
            confirmationResultsMapper.insertIncomeInvoiceAuthConfirmationResults(results);

            String invoiceId = "";

            // 更新统计主表(income_invoice_company_statistics)统计控制(tjkz)字段，为了做按钮功能限制
            IncomeInvoiceAuthCompanyStatistics queryParamEntity = new IncomeInvoiceAuthCompanyStatistics();  // 定义统计主表的参数
            queryParamEntity.setGmdsbh(gmfsbh); // 通过购方税号的税款所属期查询统计主表信息
            queryParamEntity.setSkssq(ssq);
            List<IncomeInvoiceAuthCompanyStatistics> statisticsMainList = incomeInvoiceTwoCompanyStatisticsMapper.selectIncomeInvoiceAuthCompanyStatisticsList(queryParamEntity);
            if (CollectionUtils.isEmpty(statisticsMainList)) {
                log.error("【进项服务类】【大象】【申请确认】未获取统计信息，请确认。");
                return AjaxResult.error("未获取统计信息，请确认");
            }
            IncomeInvoiceAuthCompanyStatistics updateStatisticsMain = statisticsMainList.get(0);
            updateStatisticsMain.setTjkz("07"); // 修改统计主表的统计控制字段为确认中
            updateStatisticsMain.setQrsbyy("");
            incomeInvoiceTwoCompanyStatisticsMapper.updateIncomeInvoiceAuthCompanyStatistics(updateStatisticsMain);

            // 更新发票信息表
            IncomeInvoiceAuth invoiceQueryParam = new IncomeInvoiceAuth();
            invoiceQueryParam.setRzsq(ssq);
            invoiceQueryParam.setGmfsbh(gmfsbh);
            List<IncomeInvoiceAuth> queryInvoiceList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceQueryParam);
            for (int i = 0; i < queryInvoiceList.size(); i++) {
                IncomeInvoiceAuth currentInvoice = queryInvoiceList.get(i);
                currentInvoice.setQrstatus("1");
                incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(currentInvoice);
            }

            //插入定时任务表
            IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
            queryResult.setId(IdUtils.simpleUUID());
            queryResult.setPch(pch);
            queryResult.setInitationType(InitActionTypeEnum.APPLY_CONFIRM.getCode());
            queryResult.setInitationTime(new Date());
            queryResult.setInitationStatus("0");
            queryResult.setGmfsbh(gmfsbh);
            queryResult.setIdentity(String.valueOf(companyservice.getCompanyid()));
            queryResult.setTaxno(companyservice.getSellertax());
            queryResult.setInitationNum(0L);
            queryResult.setCreateTime(new Date());
            queryResultMapper.insertIncomeInvoiceAuthQueryResult(queryResult);

        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }

        ApplyConfirmVO applyConfirmVO = BeanUtil.copyProperties(resp, ApplyConfirmVO.class);
        IncomeApplyConfirmVO incomeApplyCountResultVO = BeanUtil.copyProperties(applyConfirmVO, IncomeApplyConfirmVO.class);

        return AjaxResult.success(incomeApplyCountResultVO);
    }

    /**
     * 获取确认结果
     *
     * @param incomeApplyConfirmDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 12:16
     */
    @Override
    public AjaxResult applyConfirmResult(IncomeApplyConfirmResultDTO incomeApplyConfirmDTO, Companyservice companyservice) throws Exception {


        ApplyConfirmResultDTO applyConfirmResultDTO = BeanUtil.copyProperties(incomeApplyConfirmDTO, ApplyConfirmResultDTO.class);
        ValidateUtils.validate(applyConfirmResultDTO);

        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.APPLY_CONFIRM_RESULY, applyConfirmResultDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【获取确认结果】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        //返回解析
        ApplyConfirmResultVO applyConfirmResultVO = BeanUtil.copyProperties(resp, ApplyConfirmResultVO.class);
        IncomeApplyConfirmResultVO incomeApplyConfirmResultVO = BeanUtil.copyProperties(applyConfirmResultVO, IncomeApplyConfirmResultVO.class);

        String pch = applyConfirmResultDTO.getPCH();
        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : "";
        // 结果状态 Y当前批次已出结果 N当前批次无结果
        String pczt = resp.getString("PCZT") != null ? resp.getString("PCZT") : "";
        String clzt = resp.getString("CLZT") != null ? resp.getString("CLZT") : "";
        if (("0000").equals(ztdm) && "Y".equals(pczt) && ("0".equals(clzt) || "3".equals(clzt) || "4".equals(clzt))) {
            IncomeInvoiceAuthConfirmationResults results = new IncomeInvoiceAuthConfirmationResults(); // 查询确认结果表
            // 根据批次号查询确认结果信息
            results.setPch(pch);
            // 统计确认标识 0:申请确认 1:撤销确认
            String tjbz = incomeApplyConfirmResultVO.getTJBZ() != null ? incomeApplyConfirmResultVO.getTJBZ() : "";
            // 确认标志 （结果状态为 Y 时有值）0 成功 1 失败
            String qrbz = incomeApplyConfirmResultVO.getQRBZ() != null ? incomeApplyConfirmResultVO.getQRBZ() : "";
            // 获取确认结果列表
            List<IncomeInvoiceAuthConfirmationResults> confirmationResultsList = confirmationResultsMapper.selectIncomeInvoiceAuthConfirmationResultsList(results);
            // 如果确认结果列表现在不为空
            if (!CollectionUtils.isEmpty(confirmationResultsList)) {
                results = BeanUtil.copyProperties(incomeApplyConfirmResultVO, IncomeInvoiceAuthConfirmationResults.class);
                results.setId(confirmationResultsList.get(0).getId());
                results.setUpdateTime(new Date());
                confirmationResultsMapper.updateIncomeInvoiceAuthConfirmationResults(results);

                String ssq = confirmationResultsList.get(0).getTjyf() != null ? confirmationResultsList.get(0).getTjyf() : "";
                if (StrUtil.isNotEmpty(ssq) && StrUtil.isNotEmpty(incomeApplyConfirmDTO.getGMFSBH())) {

                    //更新统计信息表
                    IncomeInvoiceAuthCompanyStatistics incomeInvoiceTwoCompanyStatistics = new IncomeInvoiceAuthCompanyStatistics();
                    incomeInvoiceTwoCompanyStatistics.setGmdsbh(incomeApplyConfirmDTO.getGMFSBH());
                    incomeInvoiceTwoCompanyStatistics.setSkssq(ssq);
                    List<IncomeInvoiceAuthCompanyStatistics> list = incomeInvoiceTwoCompanyStatisticsMapper.selectIncomeInvoiceAuthCompanyStatisticsList(incomeInvoiceTwoCompanyStatistics);
                    if (CollectionUtils.isEmpty(list)) {
                        log.error("【进项服务类】【大象】【获取确认结果】解析异常，无统计主表信息，请联系管理员处理");
                        return AjaxResult.error("【进项服务类】【大象】【获取确认结果】解析异常，无统计主表信息，请联系管理员处理");
                    }

                    String qrState = "0";
                    IncomeInvoiceAuthCompanyStatistics statisticsMain = list.get(0);
                    switch (clzt) {
                        // 待确认
                        case "0":
                            qrState = "0";
                            statisticsMain.setTjkz("00");
                            break;
                        // 确认失败
                        case "3":
                            if ("0".equals(tjbz)) {
                                qrState = "3";
                                statisticsMain.setTjkz("05");
                            } else {
                                qrState = "2";
                                statisticsMain.setTjkz("03");
                            }
                            break;
                        // 确认成功
                        case "4":
                            if ("0".equals(tjbz)) {
                                qrState = "2";
                                statisticsMain.setTjkz("03");
                            } else {
                                qrState = "0";
                                statisticsMain.setTjkz("00");
                            }
                            break;
                    }
                    statisticsMain.setQrsj(incomeApplyConfirmResultVO.getQRSJ());
                    statisticsMain.setQrsbyy(incomeApplyConfirmResultVO.getSBYY());
                    incomeInvoiceTwoCompanyStatisticsMapper.updateIncomeInvoiceAuthCompanyStatistics(statisticsMain);

                    // 更新发票信息表
                    IncomeInvoiceAuth invoiceQueryParam = new IncomeInvoiceAuth();
                    invoiceQueryParam.setRzsq(ssq);
                    invoiceQueryParam.setGmfsbh(incomeApplyConfirmDTO.getGMFSBH());
                    List<IncomeInvoiceAuth> queryInvoiceList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceQueryParam);
                    for (int i = 0; i < queryInvoiceList.size(); i++) {
                        IncomeInvoiceAuth currentInvoice = queryInvoiceList.get(i);
                        currentInvoice.setQrstatus(qrState);
                        incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(currentInvoice);
                    }

                    //更新定时任务表
                    IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
                    queryResult.setPch(pch);
                    List<IncomeInvoiceAuthQueryResult> incomeTwoQueryResults = queryResultMapper.selectIncomeInvoiceAuthQueryResultList(queryResult);
                    if (!CollectionUtils.isEmpty(incomeTwoQueryResults)) {
                        queryResult = incomeTwoQueryResults.get(0);
                        queryResult.setInitationType(InitActionTypeEnum.APPLY_CONFIRM.getCode());
                        queryResult.setInitationTime(new Date());
                        queryResult.setInitationStatus("1");
                        queryResult.setInitationNum(0L);
                        queryResult.setUpdateTime(new Date());
                        queryResultMapper.updateIncomeInvoiceAuthQueryResult(queryResult);
                    }
                }
            }
        }else {
            return AjaxResult.success(incomeApplyConfirmResultVO);
        }
        return AjaxResult.success(incomeApplyConfirmResultVO);
    }

    /**
     * 获取企业档案
     *
     * @param incomeGetCompanyInfoDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 12:22
     */
    @Override
    public AjaxResult getCompanyInfo(IncomeGetCompanyInfoDTO incomeGetCompanyInfoDTO, Companyservice companyservice) throws Exception {

        GetCompanyInfoDTO getCompanyInfoDTO = BeanUtil.copyProperties(incomeGetCompanyInfoDTO, GetCompanyInfoDTO.class);
        ValidateUtils.validate(getCompanyInfoDTO);

        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.GET_COMPANY_INFO, getCompanyInfoDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【获取企业档案】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : "";
        String ztxx = resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "";
        if(!"0000".equals(ztdm)){
            log.info("【进项服务类】【大象】【获取企业档案】API请求返回错误，ZTDM={}，ZTXX={}",ztdm,ztxx);
            return AjaxResult.error(200000,"进项错误！");
        }

        GetCompanyInfoVO getCompanyInfoVO = BeanUtil.copyProperties(resp, GetCompanyInfoVO.class);

        IncomeInvoiceAuthEnterpriseArchives enterpriseArchives = BeanUtil.copyProperties(getCompanyInfoVO, IncomeInvoiceAuthEnterpriseArchives.class);
        enterpriseArchives.setSbh(incomeGetCompanyInfoDTO.getSBH());
        IncomeInvoiceAuthEnterpriseArchives enterpriseArchivesQuery = new IncomeInvoiceAuthEnterpriseArchives();
        enterpriseArchivesQuery.setSbh(incomeGetCompanyInfoDTO.getSBH());
        enterpriseArchivesQuery.setGmfsbh(incomeGetCompanyInfoDTO.getSBH());
        List<IncomeInvoiceAuthEnterpriseArchives> enterpriseArchivesList = enterpriseArchivesMapper.selectIncomeInvoiceAuthEnterpriseArchivesList(enterpriseArchivesQuery);

        if (CollectionUtils.isEmpty(enterpriseArchivesList)) {
            enterpriseArchives.setId(IdUtils.simpleUUID());
            enterpriseArchives.setCreateTime(new Date());
            enterpriseArchivesMapper.insertIncomeInvoiceAuthEnterpriseArchives(enterpriseArchives);
        } else {
            IncomeInvoiceAuthEnterpriseArchives enterpriseArchivesResult = enterpriseArchivesList.get(0);
            enterpriseArchives.setId(enterpriseArchivesResult.getId());
            enterpriseArchives.setUpdateTime(new Date());
            enterpriseArchivesMapper.updateIncomeInvoiceAuthEnterpriseArchives(enterpriseArchives);
        }

        IncomeGetCompanyInfoVO incomeGetCompanyInfoVO = BeanUtil.copyProperties(getCompanyInfoVO, IncomeGetCompanyInfoVO.class);
        return AjaxResult.success(incomeGetCompanyInfoVO);
    }

    /**
     * 重置密码
     *
     * @param incomeResetPasswordDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 12:26
     */
    @Override
    public AjaxResult resetPassword(IncomeResetPasswordDTO incomeResetPasswordDTO, Companyservice companyservice) throws Exception {

        //SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        //数据格式转化
        ResetPasswordDTO resetPasswordDTO = new ResetPasswordDTO();
        resetPasswordDTO.setSBH(incomeResetPasswordDTO.getSBH());
//        BeanUtil.copyProperties(incomeResetPasswordDTO, resetPasswordDTO);
        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.RESET_PASSWORD, resetPasswordDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【重置密码】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        // TODO-xkng: 2022/9/17 未测 待处理
        SetPasswordVO setPasswordVO = BeanUtil.copyProperties(resp, SetPasswordVO.class);
        IncomeInvoiceAuthAccount account = new IncomeInvoiceAuthAccount();
        account.setSbh(resetPasswordDTO.getSBH());
        List<IncomeInvoiceAuthAccount> accountList = accountMapper.selectIncomeInvoiceAuthAccountList(account);
        account.setStatus(setPasswordVO.getCLZT());
        // TODO: 2022/6/6 看下默认是多少
        account.setYwmm("密码重置");
        account.setNewywmm("密码重置");
        if (CollectionUtils.isEmpty(accountList)) {
            account.setId(IdUtils.simpleUUID());
            account.setCreateTime(new Date());
            accountMapper.insertIncomeInvoiceAuthAccount(account);
        } else {
            account.setUpdateTime(new Date());
            accountMapper.updateIncomeInvoiceAuthAccount(account);
        }
        IncomeSetPasswordVO incomeSetPasswordVO = BeanUtil.copyProperties(setPasswordVO, IncomeSetPasswordVO.class);
        return AjaxResult.success(incomeSetPasswordVO);

    }

    /**
     * 设置密码
     *
     * @param incomeSetPasswordDTO
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author xkng
     * @date 2022/9/17 12:32
     */
    @Override
    public AjaxResult setPassword(IncomeSetPasswordDTO incomeSetPasswordDTO, Companyservice companyservice) throws Exception {

        //数据格式转化
        SetPasswordDTO setPasswordDTO = BeanUtil.copyProperties(incomeSetPasswordDTO, SetPasswordDTO.class);
        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.SET_PASSWORD, setPasswordDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【设置密码】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        SetPasswordVO setPasswordVO = BeanUtil.copyProperties(resp, SetPasswordVO.class);

        if ("9999".equals(setPasswordVO.getZTDM())) {
            return AjaxResult.error("请求失败");
        }
        // TODO: 2022/6/2 返回结果处理：处理失败？ xkng
        IncomeInvoiceAuthAccount account = new IncomeInvoiceAuthAccount();
        account.setSbh(incomeSetPasswordDTO.getSBH());
        List<IncomeInvoiceAuthAccount> accountList = accountMapper.selectIncomeInvoiceAuthAccountList(account);

        if (CollectionUtils.isEmpty(accountList)) {
            account.setId(IdUtils.simpleUUID());
            account.setCreateTime(new Date());
            account.setStatus(setPasswordVO.getCLZT());
            account.setYwmm(incomeSetPasswordDTO.getYWMM());
            account.setNewywmm(incomeSetPasswordDTO.getNEWYWMM());
            accountMapper.insertIncomeInvoiceAuthAccount(account);
        } else {
            account = accountList.get(0);
            account.setUpdateTime(new Date());
            account.setStatus(setPasswordVO.getCLZT());
            account.setYwmm(incomeSetPasswordDTO.getYWMM());
            account.setNewywmm(incomeSetPasswordDTO.getNEWYWMM());
            accountMapper.updateIncomeInvoiceAuthAccount(account);
        }
        IncomeSetPasswordVO incomeSetPasswordVO = BeanUtil.copyProperties(setPasswordVO, IncomeSetPasswordVO.class);
        return AjaxResult.success(incomeSetPasswordVO);
    }


//    =============================发票采集-ql==========================================
    // TODO: 2022/9/22

    /**
     * 全票面采集
     *
     * @param incomeGetInvoiceDTO
     * @return
     */
    @Override
    public AjaxResult getInvoice(IncomeGetInvoiceDTO incomeGetInvoiceDTO, Companyservice companyservice)
            throws Exception {
        // 校验数据
        ValidateUtils.validate(incomeGetInvoiceDTO);

        // 拼装数据
        GetInvoiceDTO getInvoiceDTO = new GetInvoiceDTO();

        BeanUtils.copyProperties(incomeGetInvoiceDTO, getInvoiceDTO);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        getInvoiceDTO.setCJKSRQ(sdf.format(incomeGetInvoiceDTO.getCJKSRQ()));
        getInvoiceDTO.setCJJSRQ(sdf.format(incomeGetInvoiceDTO.getCJJSRQ()));

        //替换结束时间，不然当天没法采集
        String jssj = getInvoiceDTO.getCJJSRQ().replace("000000", "235959");
        getInvoiceDTO.setCJJSRQ(jssj);

        getInvoiceDTO.setZTBZ("1");

        Long identity = companyservice.getCompanyid();
        String textno = companyservice.getSellertax();
//        // 处理发票类型
//        String invoieLine = coverInvoiceLineToElephant(getInvoiceDTO.getFPLXDM());
//        if (StringUtils.isEmpty(invoieLine)) {
//            return AjaxResult.error(ErrorCode.ERROR_INVOICE_LINE);
//        }
//        getInvoiceDTO.setFPLXDM(invoieLine);

        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.getInvoice, getInvoiceDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            // 大象请求异常
            log.error("【进项服务类】【大象】【全票面采集】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        //处理发票类型和状态代码为null的情况
        String fplxdm = resp.getString("FPLXDM") == null ? "" : resp.getString("FPLXDM");
        String ztdm = resp.getString("ZTDM") == null ? "" : resp.getString("ZTDM");
        resp.put("ZTDM", ztdm);
        if (!fplxdm.equals("03")) {
            // 解码处理dto存数据库
            GetInvoiceRespCommonDTO getInvoiceRespCommonDTO = resp.toJavaObject(GetInvoiceRespCommonDTO.class);

            if (getInvoiceRespCommonDTO.getZTDM().equals("0000")) {
                List<IncomeInvoiceAuth> incomeInvoiceTwoList = getInvoiceRespCommonDTO.getFPZHXX();
                // List<GetInvoiceResultDTO> getInvoiceResultDTOS = getInvoiceRespCommonDTO.getFPZHXX();
                if (!CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                    for (IncomeInvoiceAuth incomeInvoiceTwo : incomeInvoiceTwoList) {
                        IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                        invoiceTwo.setFpdm(incomeInvoiceTwo.getFpdm());
                        invoiceTwo.setFphm(incomeInvoiceTwo.getFphm());
                        invoiceTwo.setOrganizeid(String.valueOf(identity));
                        List<IncomeInvoiceAuth> list = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceTwo);
                        if (!CollectionUtils.isEmpty(list)) {
                            incomeInvoiceTwo.setId(list.get(0).getId());
                            incomeInvoiceTwo.setUpdateTime(new Date());
                            incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(incomeInvoiceTwo);
                        } else {
                            //插入拉取发票
                            String uuid = IdUtils.simpleUUID();
                            incomeInvoiceTwo.setId(uuid);
                            incomeInvoiceTwo.setPch(incomeGetInvoiceDTO.getPCH());
                            incomeInvoiceTwo.setIdentity(identity);
                            incomeInvoiceTwo.setTaxno(textno);
                            incomeInvoiceTwo.setCreateTime(new Date());
                            incomeInvoiceTwo.setUpdateTime(new Date());
                            incomeInvoiceTwo.setOrganizeid(String.valueOf(identity));
                            incomeInvoiceAuthMapper.insertIncomeInvoiceAuth(incomeInvoiceTwo);
                            List<IncomeInvoiceAuthDetail> incomeInvoiceTwoDetailList = incomeInvoiceTwo.getMxxx();
                            for (IncomeInvoiceAuthDetail mxxx : incomeInvoiceTwoDetailList) {
                                String uuidDetail = IdUtils.simpleUUID();
                                mxxx.setId(uuidDetail);
                                mxxx.setInvoiceId(uuid);
                                incomeInvoiceAuthDetailMapper.insertIncomeInvoiceAuthDetail(mxxx);
                            }

                        }
                    }

                }
            }
        } else {
            // 解码处理dto存数据库
            GetInvoiceRespCommonCarDTO getInvoiceRespCommonCarDTO = resp.toJavaObject(GetInvoiceRespCommonCarDTO.class);
            if (getInvoiceRespCommonCarDTO.getZTDM().equals("0000")) {
                List<GetInvoiceRespAuthCarDTO> incomeInvoiceTwoList = getInvoiceRespCommonCarDTO.getFPZHXX();
                if (!CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                    for (GetInvoiceRespAuthCarDTO incomeInvoiceTwo : incomeInvoiceTwoList) {
                        IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                        invoiceTwo.setFpdm(incomeInvoiceTwo.getFpdm());
                        invoiceTwo.setFphm(incomeInvoiceTwo.getFphm());
                        invoiceTwo.setOrganizeid(String.valueOf(identity));
                        List<IncomeInvoiceAuth> list = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceTwo);
                        if (!CollectionUtils.isEmpty(list)) {
                            // 如果存在income invoice auth
                            incomeInvoiceTwo.setId(list.get(0).getId());
                            IncomeInvoiceAuth invoiceTwo_ath = new IncomeInvoiceAuth();
                            BeanUtils.copyProperties(incomeInvoiceTwo, invoiceTwo_ath);
                            incomeInvoiceTwo.setUpdateTime(new Date());
                            incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(invoiceTwo_ath);
                            // 获取下机动车发票
                            IncomeInvoiceAuthCar carQuery = new IncomeInvoiceAuthCar();
                            carQuery.setInvoiceId(list.get(0).getId());
                            List<IncomeInvoiceAuthCar> incomeInvoiceAuthCars = incomeInvoiceAuthCarMapper.selectIncomeInvoiceAuthCarList(carQuery);
                            if (!CollectionUtils.isEmpty(incomeInvoiceAuthCars)) {
                                // 如果不为空
                                IncomeInvoiceAuthCar updateData = new IncomeInvoiceAuthCar();
                                String id = updateData.getId();
                                String invoiceId = updateData.getInvoiceId();
                                BeanUtils.copyProperties(incomeInvoiceTwo, updateData);
                                updateData.setId(id);
                                updateData.setInvoiceId(invoiceId);
                                incomeInvoiceAuthCarMapper.updateIncomeInvoiceAuthCar(updateData);
                            } else {
                                //
                                IncomeInvoiceAuthCar updateData = new IncomeInvoiceAuthCar();
                                BeanUtils.copyProperties(incomeInvoiceTwo, updateData);
                                updateData.setInvoiceId(list.get(0).getId());
                                String uuid = IdUtils.simpleUUID();
                                updateData.setId(uuid);
                                incomeInvoiceAuthCarMapper.updateIncomeInvoiceAuthCar(updateData);
                            }

                        } else {
                            String uuid = IdUtils.simpleUUID();
                            String uuidCar = IdUtils.simpleUUID();
                            IncomeInvoiceAuth incomeInvoice = new IncomeInvoiceAuth();
                            IncomeInvoiceAuthCar incomeInvoiceAuthCar = new IncomeInvoiceAuthCar();
                            BeanUtils.copyProperties(incomeInvoiceTwo, incomeInvoice);
                            incomeInvoice.setId(uuid);
                            incomeInvoice.setPch(incomeGetInvoiceDTO.getPCH());
                            incomeInvoice.setIdentity(identity);
                            incomeInvoice.setTaxno(textno);
                            incomeInvoice.setCreateTime(new Date());
                            incomeInvoice.setUpdateTime(new Date());
                            incomeInvoiceAuthMapper.insertIncomeInvoiceAuth(incomeInvoice);

                            incomeInvoiceAuthCar.setId(uuidCar);
                            incomeInvoiceAuthCar.setInvoiceId(uuid);
                            incomeInvoiceAuthCarMapper.insertIncomeInvoiceAuthCar(incomeInvoiceAuthCar);

                        }
                    }

                }
            }
        }
        // tianenhui add by 2022年6月11日  采集记录添加---------srart
        // CollectRecord collectRecord = new CollectRecord();
        // collectRecord.setGmfsbh(incomeGetInvoiceDTO.getGMFSBH());
        // collectRecord.setFplxdm(incomeGetInvoiceDTO.getFPLXDM());
        // collectRecord.setPch(incomeGetInvoiceDTO.getPCH());
        // collectRecord.setCjksrq(TimeUtil.dateFormat(incomeGetInvoiceDTO.getCJKSRQ(), "yyyyMMddHHmmss"));//采集开始时间
        // collectRecord.setCjjsrq(TimeUtil.dateFormat(incomeGetInvoiceDTO.getCJJSRQ(), "yyyyMMddHHmmss"));//采集结束时间
        // collectRecord.setCjlx(incomeGetInvoiceDTO.getCjlx());//采集类型
        // collectRecord.setCreatetime(TimeUtil.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));//创建时间
        // collectRecord.setZhs((long) (resp.getString("ZHS") == null ? 0 : Long.parseLong(resp.getString("ZHS"))));//结果总行数
        // collectRecord.setDqskssq(resp.getString("DQSKSSQ") == null ? "" : resp.getString("DQSKSSQ"));//税款所属期
        // collectRecordMapper.insertCollectRecord(collectRecord);
        // log.info("采集结果数=" + collectRecord.getZhs());
        // tianenhui add by 2022年6月11日  采集记录添加---------end

        // TODO 处理resp转vo

        return AjaxResult.success(resp);
    }


    /**
     * 主信息采集
     *
     * @param incomeMasterInformationDTO
     * @param companyservice
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public AjaxResult masterInformation(@Valid IncomeMasterInformationDTO incomeMasterInformationDTO, Companyservice companyservice) throws Exception {
        //数据格式转化
        MasterInformationDTO masterInformationDTO = new MasterInformationDTO();
        BeanUtil.copyProperties(incomeMasterInformationDTO, masterInformationDTO);
        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.Master_INFORMATION, masterInformationDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【主信息采集】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        //返回解析
        if (resp.getString("ZTDM").equals("0000")) {
            GetInvoiceRespCommonDTO getInvoiceRespCommonDTO = resp.toJavaObject(GetInvoiceRespCommonDTO.class);
            if (CollectionUtils.isEmpty(getInvoiceRespCommonDTO.getFPZHXX())) {
                return AjaxResult.error();
            }
            List<IncomeInvoiceAuth> incomeInvoiceTwoLists = getInvoiceRespCommonDTO.getFPZHXX();
            for (IncomeInvoiceAuth incomeInvoiceTwo : incomeInvoiceTwoLists) {
                IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                invoiceTwo.setIdentity(companyservice.getCompanyid());
                invoiceTwo.setFpdm(incomeInvoiceTwo.getFpdm());
                invoiceTwo.setFphm(incomeInvoiceTwo.getFphm());
                invoiceTwo.setDqskssq(incomeInvoiceTwo.getDqskssq());
                invoiceTwo.setGxjzr(incomeInvoiceTwo.getGxjzr());
                invoiceTwo.setGxrqq(incomeInvoiceTwo.getGxrqq());
                invoiceTwo.setGxrqz(incomeInvoiceTwo.getGxrqz());
                invoiceTwo.setFplxdm(incomeInvoiceTwo.getFplxdm());
                invoiceTwo.setGmfsbh(incomeInvoiceTwo.getGmfsbh());
                invoiceTwo.setXhfmc(incomeInvoiceTwo.getXhfmc());
                invoiceTwo.setXhfsbh(incomeInvoiceTwo.getXhfsbh());
                invoiceTwo.setKprq(incomeInvoiceTwo.getKprq());
                invoiceTwo.setHjje(incomeInvoiceTwo.getHjje());
                invoiceTwo.setSe(incomeInvoiceTwo.getSe());
                invoiceTwo.setFpzt(incomeInvoiceTwo.getFpzt());
                invoiceTwo.setRzzt(incomeInvoiceTwo.getRzzt());
                invoiceTwo.setRzrq(incomeInvoiceTwo.getRzrq());
                invoiceTwo.setRzsq(incomeInvoiceTwo.getRzsq());
                invoiceTwo.setSfdbts(incomeInvoiceTwo.getSfdbts());
                invoiceTwo.setRzlx(incomeInvoiceTwo.getRzlx());
                invoiceTwo.setJym(incomeInvoiceTwo.getJym());
                invoiceTwo.setXxly(incomeInvoiceTwo.getXxly());
                invoiceTwo.setYxse(incomeInvoiceTwo.getYxse());
                invoiceTwo.setYqkgxbz(incomeInvoiceTwo.getYqkgxbz());
                invoiceTwo.setGlzt(incomeInvoiceTwo.getGlzt());
                invoiceTwo.setFply(incomeInvoiceTwo.getFply());
                invoiceTwo.setDkse(incomeInvoiceTwo.getDkse());
                invoiceTwo.setBdkyy(incomeInvoiceTwo.getBdkyy());
                List<IncomeInvoiceAuth> list = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceTwo);
                if (!CollectionUtils.isEmpty(list)) {
                    incomeInvoiceTwo.setId(list.get(0).getId());
                    incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(incomeInvoiceTwo);
                } else {
                    String uuid = IdUtils.fastUUID();
                    invoiceTwo.setId(uuid);
                    invoiceTwo.setPch(incomeMasterInformationDTO.getPCH());
                    incomeInvoiceAuthMapper.insertIncomeInvoiceAuth(invoiceTwo);
                }
            }

            // TODO 为什么下面还要再插入一遍？
            // List<IncomeInvoiceTwo> incomeInvoiceTwoList = getInvoiceRespCommonDTO.getFPZHXX();
            // for (IncomeInvoiceTwo invoiceTwo : incomeInvoiceTwoList) {
            //     // String uuid = UuidUtils.getUUID();
            //     String uuid = IdUtils.fastUUID≤();
            //     invoiceTwo.setId(uuid);
            //     invoiceTwo.setPch(incomeMasterInformationDTO.getPCH());
            //     incomeInvoiceTwoMapper.insertIncomeInvoiceTwo(invoiceTwo);
            // }
        } else {
            // 唉，只处理成功的不处理失败的情况
            return AjaxResult.error(resp.getInteger("ZTDM"), resp.getString("ZTXX"));
        }

        // 我佛了，这两句加上是干啥的
        // MaterInformationVO materInformationVO = new MaterInformationVO();
        // IncomeMaterInformationVO incomeMaterInformationVO = BeanUtil.copyProperties(materInformationVO, IncomeMaterInformationVO.class);
        return AjaxResult.success(resp);
    }

    /**
     * 获取统计信息
     *
     * @param incomeCountInfoDTO
     * @return com.hx.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/5/27 11:41
     */
    @Override
    public AjaxResult getCountInfo(IncomeCountInfoDTO incomeCountInfoDTO, Companyservice companyservice) throws Exception {

        CountInfoDTO countInfoDTO = BeanUtil.copyProperties(incomeCountInfoDTO, CountInfoDTO.class);

        ValidateUtils.validate(countInfoDTO);

        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.COUNT_INFO, countInfoDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【获取统计信息】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        //返回解析
        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : "";

        if (ztdm.equals("0000")) {
            //税款所属期
            String skssq = incomeCountInfoDTO.getRZSKSSQ();
            IncomeInvoiceAuthCompanyStatistics incomeInvoiceTwoCompanyStatistics = BeanUtil.copyProperties(resp, IncomeInvoiceAuthCompanyStatistics.class);
            CountInfoVO countInfoVO = BeanUtil.copyProperties(resp, CountInfoVO.class);
            IncomeCountInfoVO incomecountInfoVO = BeanUtil.copyProperties(countInfoVO, IncomeCountInfoVO.class);
            String uuid = "";
            //查询是否已存在
            IncomeInvoiceAuthCompanyStatistics statistics = new IncomeInvoiceAuthCompanyStatistics();
            statistics.setGmdsbh(incomeInvoiceTwoCompanyStatistics.getGmdsbh());
            statistics.setSkssq(skssq);
            List<IncomeInvoiceAuthCompanyStatistics> twoStatisticsList = incomeInvoiceTwoCompanyStatisticsMapper.selectIncomeInvoiceAuthCompanyStatisticsList(statistics);
            //统计结果存在
            if (!CollectionUtils.isEmpty(twoStatisticsList)) {
                incomeInvoiceTwoCompanyStatistics.setSkssq(skssq);
                incomeInvoiceTwoCompanyStatistics.setId(twoStatisticsList.get(0).getId());
                uuid = twoStatisticsList.get(0).getId();
                incomeInvoiceTwoCompanyStatisticsMapper.updateIncomeInvoiceAuthCompanyStatistics(incomeInvoiceTwoCompanyStatistics);
                //删除从表数据
                IncomeInvoiceAuthCompanyStatisticsDetail incomeInvoiceCompanyStatisticsDetail = new IncomeInvoiceAuthCompanyStatisticsDetail();
                incomeInvoiceCompanyStatisticsDetail.setStatisticsId(uuid);
                List<IncomeInvoiceAuthCompanyStatisticsDetail> statisticsDetails = incomeInvoiceCompanyStatisticsDetailMapper.selectIncomeInvoiceAuthCompanyStatisticsDetailList(incomeInvoiceCompanyStatisticsDetail);
                if (!CollectionUtils.isEmpty(statisticsDetails)) {
                    for (IncomeInvoiceAuthCompanyStatisticsDetail statisticsDetail : statisticsDetails) {
                        incomeInvoiceCompanyStatisticsDetailMapper.deleteIncomeInvoiceAuthCompanyStatisticsDetailById(statisticsDetail.getId());
                    }
                }
            } else {
                uuid = IdUtils.fastUUID();
                incomeInvoiceTwoCompanyStatistics.setId(uuid);
                incomeInvoiceTwoCompanyStatistics.setSkssq(skssq);
                incomeInvoiceTwoCompanyStatistics.setCreateTime(DateUtils.getNowDate());
                incomeInvoiceTwoCompanyStatistics.setTjzt(countInfoVO.getTJZT());
                incomeInvoiceTwoCompanyStatistics.setTjkz(countInfoVO.getTJKZ());
                incomeInvoiceTwoCompanyStatisticsMapper.insertIncomeInvoiceAuthCompanyStatistics(incomeInvoiceTwoCompanyStatistics);
            }

            //存明细到统计明细表
            String tjjg = incomeInvoiceTwoCompanyStatistics.getTjjg();
            if (!StringUtils.isEmpty(tjjg)) {
                String[] tjjgs = tjjg.split(";");
                for (String s : tjjgs) {
                    String[] detail = s.split("=");
                    IncomeInvoiceAuthCompanyStatisticsDetail incomeInvoiceCompanyStatisticsDetail = new IncomeInvoiceAuthCompanyStatisticsDetail();
                    String id = IdUtils.fastUUID();
                    incomeInvoiceCompanyStatisticsDetail.setId(id);
                    incomeInvoiceCompanyStatisticsDetail.setStatisticsId(uuid);
                    incomeInvoiceCompanyStatisticsDetail.setSkssq(skssq);
                    incomeInvoiceCompanyStatisticsDetail.setGmdsbh(incomeInvoiceTwoCompanyStatistics.getGmdsbh());
                    incomeInvoiceCompanyStatisticsDetail.setFplxdm(detail[0]);
                    incomeInvoiceCompanyStatisticsDetail.setDkfpfs(detail[1]);
                    incomeInvoiceCompanyStatisticsDetail.setDkzje(detail[2]);
                    incomeInvoiceCompanyStatisticsDetail.setDkzyxse(detail[3]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkfpfs(detail[4]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkzje(detail[5]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkzyxse(detail[6]);
                    incomeInvoiceCompanyStatisticsDetail.setCreateTime(DateUtils.getNowDate());
                    incomeInvoiceCompanyStatisticsDetailMapper.insertIncomeInvoiceAuthCompanyStatisticsDetail(incomeInvoiceCompanyStatisticsDetail);
                }
            }

            String tjzt = incomeInvoiceTwoCompanyStatistics.getTjzt() != null ? incomeInvoiceTwoCompanyStatistics.getTjzt() : "";
            //更新统计状态到主表
            if (StrUtil.isNotEmpty(incomeInvoiceTwoCompanyStatistics.getGmdsbh()) && StrUtil.isNotEmpty(skssq)) {
                IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
                invoiceTwo.setDqskssq(skssq);
                invoiceTwo.setGmfsbh(incomeInvoiceTwoCompanyStatistics.getGmdsbh());
                List<IncomeInvoiceAuth> incomeInvoiceTwoList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceTwo);
                if (!CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                    for (IncomeInvoiceAuth incomeInvoiceTwo : incomeInvoiceTwoList) {
                        if ("21".equals(tjzt)) {
                            incomeInvoiceTwo.setTjstatus("1");
                        } else if ("22".equals(tjzt) || "20".equals(tjzt)) {
                            incomeInvoiceTwo.setTjstatus("2");
                        } else {
                            continue;
                        }
                        incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(invoiceTwo);
                    }
                }
            }

            return AjaxResult.success(incomecountInfoVO);
        } else if ("".equals(ztdm)) {
            return AjaxResult.success("调用接口成功，但未获取到信息");
        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }
    }


    /**
     * 申请统计
     *
     * @param incomeCountInfoDTO
     * @return com.hx.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/5/27 15:28
     */
    @Override
    public AjaxResult applyCount(IncomeApplyCountDTO incomeCountInfoDTO, Companyservice companyservice) throws Exception {

        ApplyCountDTO applyCountDTO = BeanUtil.copyProperties(incomeCountInfoDTO, ApplyCountDTO.class);

        ValidateUtils.validate(applyCountDTO);

        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.APPLY_COUNTY, applyCountDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【申请统计】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : "";

        if (ztdm.equals("0000")) {
            String pch = applyCountDTO.getPCH();
            String gmfsbh = applyCountDTO.getGMFSBH();
            //税期
            String ssq = applyCountDTO.getRZSKSSQ();


            IncomeInvoiceAuthStatistics incomeInvoiceTwoStatistics = new IncomeInvoiceAuthStatistics();
            incomeInvoiceTwoStatistics.setPch(pch);
            incomeInvoiceTwoStatistics.setGmfsbh(gmfsbh);
            incomeInvoiceTwoStatistics.setTjbz(applyCountDTO.getTJBZ());
            String uuid = IdUtils.fastUUID();
            incomeInvoiceTwoStatistics.setId(uuid);
            incomeInvoiceTwoStatistics.setSqskssq(ssq);
            incomeInvoiceTwoStatisticsMapper.insertIncomeInvoiceAuthStatistics(incomeInvoiceTwoStatistics);

            //更新统计状态 更新当前所操作税期的
            IncomeInvoiceAuth invoiceTwo = new IncomeInvoiceAuth();
            invoiceTwo.setGmfsbh(gmfsbh);

            Long identity = 0L;
            String taxno = "";
            String invoiceId = "";


            // 更新统计主表(income_invoice_company_statistics)统计控制(tjkz)字段，为了做按钮功能限制
            IncomeInvoiceAuthCompanyStatistics queryParamEntity = new IncomeInvoiceAuthCompanyStatistics();
            queryParamEntity.setGmdsbh(incomeCountInfoDTO.getGMFSBH());
            queryParamEntity.setSkssq(incomeCountInfoDTO.getRZSKSSQ());
            List<IncomeInvoiceAuthCompanyStatistics> statisticsMainList = incomeInvoiceTwoCompanyStatisticsMapper.selectIncomeInvoiceAuthCompanyStatisticsList(queryParamEntity);
            if (CollectionUtils.isEmpty(statisticsMainList)) {
                return AjaxResult.error("未获取统计信息，请确认");
            }
            IncomeInvoiceAuthCompanyStatistics updateStatisticsMain = statisticsMainList.get(0);
            updateStatisticsMain.setTjkz("06");
            incomeInvoiceTwoCompanyStatisticsMapper.updateIncomeInvoiceAuthCompanyStatistics(updateStatisticsMain);


            List<IncomeInvoiceAuth> incomeInvoiceTwoList = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(invoiceTwo);
            if (!CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                for (IncomeInvoiceAuth incomeInvoiceTwo : incomeInvoiceTwoList) {
                    incomeInvoiceTwo.setTjstatus("1");
                    incomeInvoiceTwo.setDqskssq(ssq);
                    incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(incomeInvoiceTwo);
                    invoiceId = incomeInvoiceTwo.getId();
                    identity = incomeInvoiceTwo.getIdentity();
                    taxno = incomeInvoiceTwo.getTaxno();
                }
            }

            //插入定时任务表
            IncomeInvoiceAuth incomeInvoiceTwo = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthById(invoiceId);
            if (BeanUtil.isNotEmpty(incomeInvoiceTwo)) {
                //更新定时任务表
                IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
                queryResult.setId(IdUtils.simpleUUID());
                queryResult.setPch(pch);
                queryResult.setInitationType(InitActionTypeEnum.APPLY_COUNT.getCode());
                queryResult.setInitationTime(new Date());
                queryResult.setInitationStatus("0");
                queryResult.setGmfsbh(gmfsbh);
                queryResult.setIdentity(String.valueOf(incomeInvoiceTwo.getIdentity()));
                queryResult.setTaxno(incomeInvoiceTwo.getTaxno());
                queryResult.setInitationNum(0L);
                queryResult.setCreateTime(new Date());
                queryResultMapper.insertIncomeInvoiceAuthQueryResult(queryResult);
            }

        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }
        //返回解析
        ApplyCountVO applyCountVO = BeanUtil.copyProperties(resp, ApplyCountVO.class);
        IncomeApplyCountVO incomecountInfoVO = BeanUtil.copyProperties(applyCountVO, IncomeApplyCountVO.class);
        return AjaxResult.success(incomecountInfoVO);
    }


    /**
     * 获取统计结果
     *
     * @param incomeCountInfoDTO
     * @return com.hx.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/5/30 8:55
     */
    @Override
    public AjaxResult applyCountResult(IncomeApplyCountResultDTO incomeCountInfoDTO, Companyservice companyservice) throws Exception {

        ApplyCountResultDTO applyCountResultDTO = BeanUtil.copyProperties(incomeCountInfoDTO, ApplyCountResultDTO.class);

        ValidateUtils.validate(applyCountResultDTO);

        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.APPLY_COUNTY_RESULT, applyCountResultDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【获取统计结果】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }

        String ztdm = resp.getString("ZTDM") != null ? resp.getString("ZTDM") : "";
        String pczt = resp.getString("PCZT") != null ? resp.getString("PCZT") : "";

        // 获取处理状态 0 待统计 1 已申请统计中 2 等待获取统计结果 3 申请统计失败 4 申请统计成功
        String clzt = resp.getString("CLZT") == null ? "" : resp.getString("CLZT");
        if (("0000").equals(ztdm) && "Y".equals(pczt) && ("0".equals(clzt) || "3".equals(clzt) || "4".equals(clzt))) {
            String pch = resp.getString("PCH") == null ? "" : resp.getString("PCH");
            if (StringUtils.isEmpty(pch)) {
                log.error("【进项服务类】【大象】【获取统计结果】解析异常，无批次号信息，请联系管理员处理");
                return AjaxResult.error("【进项服务类】【大象】【获取统计结果】解析异常，无批次号信息，请联系管理员处理");
            }
            // 购方税号
            String gmfsbh = resp.getString("GMFSBH") == null ? "" : resp.getString("GMFSBH");
            // 统计月份(税款所属期)
            String tjyf = resp.getString("TJYF") == null ? "" : resp.getString("TJYF");
            if (StringUtils.isEmpty(gmfsbh) || StringUtils.isEmpty(tjyf)) {
                log.error("【进项服务类】【大象】【获取统计结果】解析异常，统计结果中未获取购方税号或税款所属期，请联系管理员处理");
                return AjaxResult.error("【进项服务类】【大象】【获取统计结果】解析异常，统计结果中未获取购方税号或税款所属期，请联系管理员处理");
            }

            // 1 处理统计主表信息
            IncomeInvoiceAuthCompanyStatistics statisticsMainQueryParam = new IncomeInvoiceAuthCompanyStatistics();
            statisticsMainQueryParam.setGmdsbh(gmfsbh);
            statisticsMainQueryParam.setSkssq(tjyf);
            List<IncomeInvoiceAuthCompanyStatistics> statisticsMainList = incomeInvoiceTwoCompanyStatisticsMapper.selectIncomeInvoiceAuthCompanyStatisticsList(statisticsMainQueryParam);
            if (CollectionUtils.isEmpty(statisticsMainList)) {
                log.error("【进项服务类】【大象】【获取统计结果】解析异常，无统计主表信息，请联系管理员处理");
                return AjaxResult.error("【进项服务类】【大象】【获取统计结果】解析异常，无统计主表信息，请联系管理员处理");
            }
            IncomeInvoiceAuthCompanyStatistics statisticsMain = statisticsMainList.get(0);
            String tjbz = resp.getString("TJBZ") == null ? "" : resp.getString("TJBZ");
            // 1.1 根据统计处理状态和申请统计标志修改统计控制
            switch (clzt) {
                case "0":
                    statisticsMain.setTjzt("23");
                    statisticsMain.setTjkz("01");
                    break;
                case "3":
                    if ("0".equals(tjbz)) {
                        statisticsMain.setTjzt("23");
                        statisticsMain.setTjkz("04");
                    } else {
                        statisticsMain.setTjzt("20");
                        statisticsMain.setTjkz("00");
                    }
                    break;
                case "4":
                    if ("0".equals(tjbz)) {
                        statisticsMain.setTjzt("20");
                        statisticsMain.setTjkz("00");
                    } else {
                        statisticsMain.setTjzt("23");
                        statisticsMain.setTjkz("01");
                    }
                    break;
            }
            // 1.2 修改税款所属期（统计月份）
            statisticsMain.setSkssq(tjyf);
            statisticsMain.setSqskssq(tjyf);
            // 1.3 赋值统计日期
            statisticsMain.setTjrq(resp.getString("TJRQ"));
            // 1.4 统计结果信息
            String tjjg = resp.getString("TJJG") == null ? "" : resp.getString("TJJG");
            statisticsMain.setTjjg(tjjg);
            // 1.5 统计失败原因
            statisticsMain.setTjsbyy(resp.getString("SBYY"));
            // 1.6 修改主表数据
            incomeInvoiceTwoCompanyStatisticsMapper.updateIncomeInvoiceAuthCompanyStatistics(statisticsMain);

            // 2、处理统计明细信息
            // 2.1 删除明细表原有数据
            IncomeInvoiceAuthCompanyStatisticsDetail invoiceCompanyStatisticsDetail = new IncomeInvoiceAuthCompanyStatisticsDetail();
            invoiceCompanyStatisticsDetail.setStatisticsId(statisticsMain.getId());
            List<IncomeInvoiceAuthCompanyStatisticsDetail> statisticsDetailList = incomeInvoiceCompanyStatisticsDetailMapper.selectIncomeInvoiceAuthCompanyStatisticsDetailList(invoiceCompanyStatisticsDetail);
            if (!CollectionUtils.isEmpty(statisticsDetailList)) {
                List<String> deleteIdList = statisticsDetailList.stream().map(IncomeInvoiceAuthCompanyStatisticsDetail::getId).collect(Collectors.toList());
                String[] deleteIds = deleteIdList.toArray(new String[0]);
                incomeInvoiceCompanyStatisticsDetailMapper.deleteIncomeInvoiceAuthCompanyStatisticsDetailByIds(deleteIds);
            }
            // 2.2 如果存在明细数据 遍历新增明细表
            if (!StringUtils.isEmpty(tjjg)) {
                String[] tjjgs = tjjg.split(";");
                for (String s : tjjgs) {
                    String[] detail = s.split("=");
                    IncomeInvoiceAuthCompanyStatisticsDetail incomeInvoiceCompanyStatisticsDetail = new IncomeInvoiceAuthCompanyStatisticsDetail();
                    String id = UUID.randomUUID().toString().replace("-", "");
                    incomeInvoiceCompanyStatisticsDetail.setId(id);
                    incomeInvoiceCompanyStatisticsDetail.setStatisticsId(statisticsMain.getId());
                    incomeInvoiceCompanyStatisticsDetail.setSkssq(statisticsMain.getSkssq());
                    incomeInvoiceCompanyStatisticsDetail.setGmdsbh(statisticsMain.getGmdsbh());
                    incomeInvoiceCompanyStatisticsDetail.setFplxdm(detail[0]);
                    incomeInvoiceCompanyStatisticsDetail.setDkfpfs(detail[1]);
                    incomeInvoiceCompanyStatisticsDetail.setDkzje(detail[2]);
                    incomeInvoiceCompanyStatisticsDetail.setDkzyxse(detail[3]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkfpfs(detail[4]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkzje(detail[5]);
                    incomeInvoiceCompanyStatisticsDetail.setBdkzyxse(detail[6]);
                    incomeInvoiceCompanyStatisticsDetail.setCreateTime(DateUtils.getNowDate());
                    incomeInvoiceCompanyStatisticsDetailMapper.insertIncomeInvoiceAuthCompanyStatisticsDetail(incomeInvoiceCompanyStatisticsDetail);
                }
            }

            // 3、更新定时任务表
            IncomeInvoiceAuthQueryResult queryResult = new IncomeInvoiceAuthQueryResult();
            queryResult.setPch(pch);
            List<IncomeInvoiceAuthQueryResult> incomeTwoQueryResults = queryResultMapper.selectIncomeInvoiceAuthQueryResultList(queryResult);
            if (CollectionUtils.isEmpty(incomeTwoQueryResults)) {
                log.error("【进项服务类】【大象】【获取统计结果】解析异常，无统计请求调用信息，请联系管理员处理");
                return AjaxResult.error("【进项服务类】【大象】【获取统计结果】解析异常，无统计请求调用信息，请联系管理员处理");
            }
            queryResult = incomeTwoQueryResults.get(0);
            queryResult.setInitationType(InitActionTypeEnum.APPLY_COUNT.getCode());
            queryResult.setInitationTime(new Date());
            queryResult.setInitationStatus("1");
            queryResult.setInitationNum(0L);
            queryResult.setUpdateTime(new Date());
            queryResultMapper.updateIncomeInvoiceAuthQueryResult(queryResult);

        } else {
            return AjaxResult.error(resp.getString("ZTXX") != null ? resp.getString("ZTXX") : "");
        }

        //返回解析
        ApplyCountResultVO applyCountResultVO = BeanUtil.copyProperties(resp, ApplyCountResultVO.class);
        IncomeApplyCountResultVO incomeApplyCountResultVO = BeanUtil.copyProperties(applyCountResultVO, IncomeApplyCountResultVO.class);

        return AjaxResult.success(incomeApplyCountResultVO);
    }


    /**
     * @return com.hx.income.domain.entity.IncomeInvoiceTwoCompanyStatistics
     * @Author W
     * @Description 统计结果返回转化
     * @Date 2022-06-15
     * @Param [incomeInvoiceTwoStatistics]
     **/
    private IncomeInvoiceAuthCompanyStatistics conversion(IncomeInvoiceAuthStatistics incomeInvoiceTwoStatistics) {
        IncomeInvoiceAuthCompanyStatistics incomeInvoiceTwoCompanyStatistics = new IncomeInvoiceAuthCompanyStatistics();
        //获取当前数款所属期
        IncomeInvoiceAuthEnterpriseArchives enterpriseArchives = new IncomeInvoiceAuthEnterpriseArchives();
        enterpriseArchives.setGmfsbh(incomeInvoiceTwoStatistics.getGmfsbh());
        List<IncomeInvoiceAuthEnterpriseArchives> enterpriseArchivesList = enterpriseArchivesMapper.selectIncomeInvoiceAuthEnterpriseArchivesList(enterpriseArchives);
        if (CollectionUtils.isEmpty(enterpriseArchivesList)) {
            return null;
        }
        String skssq = enterpriseArchivesList.get(0).getDqskssq();
        //转化赋值
        incomeInvoiceTwoCompanyStatistics.setGmdsbh(incomeInvoiceTwoStatistics.getGmfsbh());
        //为N
        if (incomeInvoiceTwoStatistics.getClzt().equals("N")) {
            incomeInvoiceTwoCompanyStatistics.setSkssq(skssq);
            // TODO: 这个字段是不是新加的
//            incomeInvoiceTwoCompanyStatistics.setTjsbyy(incomeInvoiceTwoStatistics.getSbyy());
            return incomeInvoiceTwoCompanyStatistics;
        } else if (incomeInvoiceTwoStatistics.getClzt().equals("Y")) {
            incomeInvoiceTwoCompanyStatistics.setSqskssq(incomeInvoiceTwoStatistics.getTjyf());
            //转化时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String tjrq = "";
            try {
                Date date = sdf.parse(incomeInvoiceTwoStatistics.getTjrq());
                tjrq = sdf.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            incomeInvoiceTwoCompanyStatistics.setTjrq(tjrq);
            incomeInvoiceTwoCompanyStatistics.setTjjg(incomeInvoiceTwoStatistics.getTjjg());
            return incomeInvoiceTwoCompanyStatistics;
        } else {
            return null;
        }
    }

    /**
     * @return com.hx.common.core.domain.AjaxResult
     * @Author W
     * @Description 状态采集
     * @Date 2022-05-30
     * @Param [incomeStatusAcquisitionDTO]
     **/
    @Override
    public AjaxResult statusAcquisition(@Valid IncomeStatusAcquisitionDTO incomeStatusAcquisitionDTO, Companyservice companyservice) throws Exception {
        //数据格式转化
        StatusAcquistionDTO statusAcquistionDTO = new StatusAcquistionDTO();
        BeanUtil.copyProperties(incomeStatusAcquisitionDTO, statusAcquistionDTO);
        // 发送请求给大象
        JSONObject resp = null;
        try {
            resp = request(ElephantAuthConstants.STATUS_ACQUISTION, statusAcquistionDTO, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【进项服务类】【大象】【状态采集】API请求异常，大象外部报文返回code非0000。错误信息:{}", e.getMessage());
            if(e.getMessage().indexOf("secret") != -1){
                return AjaxResult.error(ErrorCode.INCOME_KEY_ERROR);
            }
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        if (resp.getString("ZTDM").equals("0000")) {
            GetInvoiceRespCommonDTO getInvoiceRespCommonDTO = resp.toJavaObject(GetInvoiceRespCommonDTO.class);
            List<IncomeInvoiceAuth> incomeInvoiceTwoList = getInvoiceRespCommonDTO.getFPZHXX();
            if (!CollectionUtils.isEmpty(incomeInvoiceTwoList)) {
                for (IncomeInvoiceAuth invoiceTwo : incomeInvoiceTwoList) {
                    IncomeInvoiceAuth incomeInvoiceTwo = new IncomeInvoiceAuth();
                    incomeInvoiceTwo.setFphm(invoiceTwo.getFphm());
                    incomeInvoiceTwo.setFpdm(invoiceTwo.getFpdm());
                    List<IncomeInvoiceAuth> list = incomeInvoiceAuthMapper.selectIncomeInvoiceAuthList(incomeInvoiceTwo);
                    if (!CollectionUtils.isEmpty(list)) {
                        IncomeInvoiceAuth income = list.get(0);
                        BeanUtils.copyProperties(invoiceTwo, income);
                        incomeInvoiceAuthMapper.updateIncomeInvoiceAuth(income);
                    }
                }
            }
        }
        //返回解析
        StatusAcquisitionVO statusAcquisitionVO = new StatusAcquisitionVO();
        IncomeStatusAcquisitionVO incomeStatusAcquisitionVO = BeanUtil.copyProperties(statusAcquisitionVO, IncomeStatusAcquisitionVO.class);
        return AjaxResult.success(resp);
    }


}
