package com.dxhy.erp.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigDto;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.db.*;
import com.dxhy.api.model.invoice.invoiceCheck.TdxCheckInvoiceDetail;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
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.erp.dao.BaseSysEnterpriseConfigErpDao;
import com.dxhy.erp.dao.SysEnterpriseConfigErpDao;
import com.dxhy.erp.dao.TdxCheckRecordInvoiceDao;
import com.dxhy.erp.entity.TdxCheckRecordInvoice;
import com.dxhy.erp.entity.TdxCheckVehicleSale;
import com.dxhy.erp.entity.UserdCarEntity;
import com.dxhy.erp.enums.GlobalReturnEnums;
import com.dxhy.erp.model.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.CheckDataService;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.erp.utils.CommonUtils;
import com.dxhy.jxpt.baseService.dao.*;
import com.dxhy.lqchannel.model.LqCheckDataReq;
import com.dxhy.lqchannel.service.LqCheckInvoiceService;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiaohongyang
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("checkDataService")
@Slf4j
public class CheckDataServiceImpl extends MpBaseServiceImpl<TdxCheckRecordInvoiceDao, TdxCheckRecordInvoice>
    implements CheckDataService {

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

    @Autowired
    private LqCheckInvoiceService lqCheckInvoiceService;

    @Autowired
    private TdxRecordInvoiceDao tdxRecordInvoiceDao;

    @Autowired
    private TdxSaleRecordInvoiceDao tdxSaleRecordInvoiceDao;

    @Autowired
    private BaseSysEnterpriseConfigErpDao sysEnterpriseConfigErpDao;

    @Resource
    private TdxTdysMhxcdCoreDao tdxTdysMhxcdCoreDao;
    @Resource
    private TdxTdysMhxcdMxCoreDao tdxTdysMhxcdMxCoreDao;
    @Resource
    private TdxTdysTldzkpCoreDao tdxTdysTldzkpCoreDao;

    @Override
    public String get(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<TdxCheckRecordInvoice> list = null;
        List<TdxCheckInvoiceDetail> detailList;
        List<TdxCheckVehicleSale> vehicleList;
        CollectData data = null;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.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);
            }
            if (StringUtils.isNotBlank(data.getQsDateBegin()) || StringUtils.isNotBlank(data.getQsDateEnd())) {
                data.setQsStatus("1");
            }
            if (StringUtils.isNotBlank(data.getTaxPeriod())) {
                data.setRzhStatus("1");
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrgByCompany(data.getCompany());
            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 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 mxsize = 0;
            int startRow = data.getStartRow();
            String requestRow = data.getRequestRow();

            int endRow = 0;

            if (StringUtils.isNotBlank(requestRow)) {
                if (Integer.parseInt(collectNum) > Integer.parseInt(requestRow)) {

                    endRow = Integer.parseInt(requestRow);
                }
                collectNum = requestRow;

            } else {
                endRow = Integer.parseInt(collectNum);
            }
            // 01回传信息
            List<InvoiceInfo> invoices = new ArrayList<>();
            // 03机动车回传信息
            List<CheckVehicleInfo> vehicleInvoiceInfos = new ArrayList<>();
            // 15二手车回传
            List<UserdCarEntity> userdCar = new ArrayList<>();
            boolean continueQuery = true;
            while (continueQuery && mxsize < Integer.parseInt(collectNum) && invoices.size() < total
                && startRow <= total) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                list = selectCheckInvoice(data, startRow, endRow);
                log.info("-----------获取查验发票完成----------" + globalInfo.getDataExchangeId());
                startRow += list.size();
                for (TdxCheckRecordInvoice info : list) {
                    String uuid = (StringUtils.isBlank(info.getFpdm())?"":info.getFpdm()) + info.getFphm();
                    //机动车
                    if ("03".equals(info.getFpzl())) {
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                        vehicleList = selectVehicle(uuid);
                        if (vehicleList != null && vehicleList.size() > 0) {
                            mxsize += vehicleList.size();
                            for (TdxCheckVehicleSale vehicle : vehicleList) {
                                CheckVehicleInfo vehicleInfo = getVehicleInfo(vehicle, info);
                                vehicleInvoiceInfos.add(vehicleInfo);
                            }
                            if (mxsize > Integer.parseInt(collectNum)) {
                                continueQuery = false;
                                break;
                            }
                        }
                    } else if ("15".equals(info.getFpzl())) {
                        //二手车
                        vehicleList = selectVehicle(uuid);
                        if (vehicleList != null && vehicleList.size() > 0) {
                            mxsize += vehicleList.size();
                            for (TdxCheckVehicleSale vehicle : vehicleList) {
                                UserdCarEntity userdCarEntity = getUserdCarInfo(vehicle, info);
                                userdCar.add(userdCarEntity);
                            }
                            if (mxsize > Integer.parseInt(collectNum)) {
                                continueQuery = false;
                                break;
                            }
                        }
                    } else if ("161".equals(info.getFpzl()))  {
                        //数电票，航空客运
                        // 转换发票实体
                        InvoiceInfo invoiceInfo = this.getInvoiceInfo(info);

                        TdxTdysMhxcdEntity tdxTdysMhxcdEntity = tdxTdysMhxcdCoreDao.selectOne(new LambdaQueryWrapper<TdxTdysMhxcdEntity>().eq(TdxTdysMhxcdEntity::getUuid, uuid));
                        if(ObjectUtil.isNotEmpty(tdxTdysMhxcdEntity)){
                            //设置 空为  字符串""
                            setDefaultNull(tdxTdysMhxcdEntity);
                            tdxTdysMhxcdEntity.setCreateTime(null);
                            tdxTdysMhxcdEntity.setId(null);
                            tdxTdysMhxcdEntity.setUuid(null);
                            invoiceInfo.setMhxcd(tdxTdysMhxcdEntity);
                        }
                        List<TdxTdysMhxcdMxEntity> tdxTdysMhxcdMxEntities = tdxTdysMhxcdMxCoreDao.selectList(new LambdaQueryWrapper<TdxTdysMhxcdMxEntity>().eq(TdxTdysMhxcdMxEntity::getTdysId, uuid));
                        if(!CollectionUtils.isEmpty(tdxTdysMhxcdMxEntities)){
                            for (TdxTdysMhxcdMxEntity tdxTdysMhxcdMxEntity : tdxTdysMhxcdMxEntities) {
                                //设置 空为  字符串""
                                setDefaultNull(tdxTdysMhxcdMxEntity);
                                tdxTdysMhxcdMxEntity.setCreateTime(null);
                                tdxTdysMhxcdMxEntity.setId(null);
                                tdxTdysMhxcdMxEntity.setTdysId(null);
                            }
                            invoiceInfo.setMhxcdMx(tdxTdysMhxcdMxEntities);
                        }
                        invoices.add(invoiceInfo);

                        if (mxsize >= Integer.parseInt(collectNum)) {
                            continueQuery = false;
                            break;
                        }
                    } else if ("283".equals(info.getFpzl()))  {
                        //数电票，铁路
                        // 转换发票实体
                        InvoiceInfo invoiceInfo = this.getInvoiceInfo(info);
                        TdxTdysTldzkpEntity tdxTdysTldzkpEntity = tdxTdysTldzkpCoreDao.selectOne(new LambdaQueryWrapper<TdxTdysTldzkpEntity>().eq(TdxTdysTldzkpEntity::getUuid, uuid));
                        if(ObjectUtil.isNotEmpty(tdxTdysTldzkpEntity)){
                            tdxTdysTldzkpEntity.setCreateTime(null);
                            tdxTdysTldzkpEntity.setId(null);
                            tdxTdysTldzkpEntity.setUuid(null);
                            //设置 空为  字符串""
                            setDefaultNull(tdxTdysTldzkpEntity);
                            invoiceInfo.setTldzkp(tdxTdysTldzkpEntity);
                        }
                        invoices.add(invoiceInfo);

                        if (mxsize >= Integer.parseInt(collectNum)) {
                            continueQuery = false;
                            break;
                        }
                    } else {
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                        detailList = getDetailInfo(uuid);
                        List<InvoiceDetailInfo> listInfo = new ArrayList<>();
                        if (detailList != null && detailList.size() > 0) {
                            mxsize += detailList.size();
                            for (TdxCheckInvoiceDetail detail : detailList) {
                                InvoiceDetailInfo detailInfo = getInvoiceDetailInfo(detail);
                                listInfo.add(detailInfo);
                            }
                        }
                        InvoiceInfo invoiceInfo = getInvoiceInfo(info);
                        invoiceInfo.setDetailList(listInfo);
                        invoices.add(invoiceInfo);
                        if (mxsize >= Integer.parseInt(collectNum)) {
                            continueQuery = false;
                            break;
                        }
                    }
                }
            }
            log.info("===========查验发票实体转换完成============" + globalInfo.getDataExchangeId());
            GatherData gather = new GatherData();
            gather.setStartRow(data.getStartRow());
            gather.setTotalRows(total);
            if ("03".equals(data.getInvoiceType())) {
                gather.setContentRows(vehicleInvoiceInfos.size());
                gather.setInvoices(vehicleInvoiceInfos);
            } else if ("15".equals(data.getInvoiceType())) {
                gather.setContentRows(userdCar.size());
                gather.setInvoices(userdCar);
            } else {
                gather.setContentRows(invoices.size());
                gather.setInvoices(invoices);
            }
            gather.setContentRows(invoices.size() + vehicleInvoiceInfos.size()+userdCar.size());
            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);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;

            runJson = JSON.toJSONString(run);
            globalJson = JSON.toJSONString(globalInfo);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    private void setDefaultNull(Object entity) {
        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            // 设置字段访问权限为可访问
            field.setAccessible(true);
            // 获取字段类型
            Class<?> fieldType = field.getType();
            // 获取字段名
            String fieldName = field.getName();

            // 判断字段类型是否为 String，且为空
            try {
                if (fieldType.equals(String.class) && field.get(entity) == null) {
                    // 如果是空字符串，则设置为 ""
                    field.set(entity, "");
                }
            } catch (IllegalAccessException e) {
                log.info("赋值字段为空字符串异常:{}",e);
            }
        }
    }

    /**
     * 二手车转化数据
     **/
    private UserdCarEntity getUserdCarInfo(TdxCheckVehicleSale vehicle, TdxCheckRecordInvoice veinfo){
        DecimalFormat df = new DecimalFormat("#0.00");
        UserdCarEntity info = new UserdCarEntity();
        if(StringUtils.isBlank(veinfo.getFpdm())){
            info.setInvoiceCode("");
        }else {
            info.setInvoiceCode(veinfo.getFpdm());
        }

        info.setInvoiceNo(veinfo.getFphm());
        if(StringUtils.isBlank(veinfo.getEleInvoiceNo())){
            info.setEleInvoiceNo(veinfo.getEleInvoiceNo());
        }
        /*if ("Y".equals(veinfo.getZfbz())) {

            info.setInvoiceStatus("2");
        } else if ("N".equals(veinfo.getZfbz())) {
            info.setInvoiceStatus("0");
        } else {
            info.setInvoiceStatus(veinfo.getZfbz());
        }*/
        info.setInvoiceStatus(veinfo.getFpzt());
        info.setInvoiceType(veinfo.getFpzl());
        /*if (StringUtils.isBlank(veinfo.getDqskssq())) {
            info.setCurrentTaxPeriod("");
        } else {
            info.setCurrentTaxPeriod(veinfo.getDqskssq());
        }*/
        /*if (StringUtils.isBlank(veinfo.getGxjzr())) {
            info.setLegalizeEndDate("");
        } else {
            info.setLegalizeEndDate(veinfo.getGxjzr());
        }*/
        /*if (StringUtils.isBlank(veinfo.getGxfwq())) {
            info.setLegalizeInvoiceDateBegin("");
        } else {
            info.setLegalizeInvoiceDateBegin(veinfo.getGxfwq());
        }*/
        /*if (StringUtils.isBlank(veinfo.getGxfwz())) {
            info.setLegalizeInvoiceDateEnd("");
        } else {
            info.setLegalizeInvoiceDateEnd(veinfo.getGxfwz());
        }*/
        if (StringUtils.isBlank(veinfo.getFpzt())) {
            info.setInvoiceStatus("");
        } else {
            info.setInvoiceStatus(veinfo.getFpzt());
        }
        info.setInvoiceDate(veinfo.getKprq());
        if (StringUtils.isBlank(vehicle.getBuyerIdNum())) {
            info.setBuyerIdNum("");
        } else {
            info.setBuyerIdNum(vehicle.getBuyerIdNum());
        }
        if (StringUtils.isBlank(vehicle.getSellerUnitCode())) {
            info.setSellerIdNum("");
        }else{
            info.setSellerIdNum(vehicle.getSellerUnitCode());
        }
        info.setBuyerTaxNo(veinfo.getGfsh());
        if (StringUtils.isBlank(veinfo.getGfmc())) {
            info.setBuyerName("");
        } else {
            info.setBuyerName(veinfo.getGfmc());
        }
        if (StringUtils.isBlank(veinfo.getXfmc())) {
            info.setSellerName("");
        } else {
            info.setSellerName(veinfo.getXfmc());
        }
        if (StringUtils.isBlank(veinfo.getXfdzdh())) {
            info.setSellerAddress("");
        } else {
            info.setSellerAddress(veinfo.getXfdzdh());
        }
        if (StringUtils.isBlank(veinfo.getGfdzdh())) {
            info.setBuyerAddress("");
        } else {
            info.setBuyerAddress(veinfo.getGfdzdh());
        }
        if (StringUtils.isBlank(vehicle.getPhone())) {
            info.setSellerPhone("");
        } else {
            info.setSellerPhone(vehicle.getPhone());
        }
        if (StringUtils.isBlank(vehicle.getGfPhone())) {
            info.setBuyerPhone("");
        } else {
            info.setBuyerPhone(vehicle.getGfPhone());
        }
        if (StringUtils.isBlank(veinfo.getBz())) {
            info.setRemark("");
        } else {
            info.setRemark(veinfo.getBz());
        }
        if (StringUtils.isBlank(vehicle.getPlateNo())) {
            info.setPlateNo("");
        } else {
            info.setPlateNo(vehicle.getPlateNo());
        }
        if (StringUtils.isBlank(vehicle.getRegistrationNo())) {
            info.setCertificateNo("");
        } else {
            info.setCertificateNo(vehicle.getRegistrationNo());
        }
        if (StringUtils.isBlank(vehicle.getVehicleType())) {
            info.setVehicleType("");
        } else {
            info.setVehicleType(vehicle.getVehicleType());
        }
        if (StringUtils.isBlank(vehicle.getVehicleNo())) {
            info.setVehicleNo("");
        } else {
            info.setVehicleNo(vehicle.getVehicleNo());
        }
        if (StringUtils.isBlank(vehicle.getFactoryModel())) {
            info.setFactoryModel("");
        } else {
            info.setFactoryModel(vehicle.getFactoryModel());
        }
        if (StringUtils.isBlank(vehicle.getVehicleAdminOffice())) {
            info.setVehicleAdminOffice("");
        } else {
            info.setVehicleAdminOffice(vehicle.getVehicleAdminOffice());
        }
        if (veinfo.getJshj() == null) {
            info.setTotalAmount("");
        } else {
            info.setTotalAmount(df.format(new BigDecimal(veinfo.getJshj())));
        }
        if (StringUtils.isBlank(vehicle.getAuctionUnit())) {
            info.setAuctionUnit("");
        } else {
            info.setAuctionUnit(vehicle.getAuctionUnit());
        }
        if (StringUtils.isBlank(vehicle.getAuctionAddress())) {
            info.setAuctionAddress("");
        } else {
            info.setAuctionAddress(vehicle.getAuctionAddress());
        }
        if (StringUtils.isBlank(vehicle.getAuctionTaxNo())) {
            info.setAuctionTaxno("");
        } else {
            info.setAuctionTaxno(vehicle.getAuctionTaxNo());
        }
        if (StringUtils.isBlank(vehicle.getAuctionBank())) {
            info.setAuctionBank("");
        } else {
            info.setAuctionBank(vehicle.getAuctionBank());
        }
        if (StringUtils.isBlank(vehicle.getAuctionPhone())) {
            info.setAuctionPhone("");
        } else {
            info.setAuctionPhone(vehicle.getAuctionPhone());
        }
        if (StringUtils.isBlank(vehicle.getCarMarket())) {
            info.setCarMarket("");
        } else {
            info.setCarMarket(vehicle.getCarMarket());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketTaxNo())) {
            info.setCarMarketTaxno("");
        } else {
            info.setCarMarketTaxno(vehicle.getCarMarketTaxNo());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketAddress())) {
            info.setCarMarketAddress("");
        } else {
            info.setCarMarketAddress(vehicle.getCarMarketAddress());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketBank())) {
            info.setCarMarketBank("");
        } else {
            info.setCarMarketBank(vehicle.getCarMarketBank());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketPhone())) {
            info.setCarMarketPhone("");
        } else {
            info.setCarMarketPhone(vehicle.getCarMarketPhone());
        }
        if (StringUtils.isBlank(veinfo.getKpr())) {
            info.setInvoicer("");
        } else {
            info.setInvoicer(veinfo.getKpr());
        }
        /*if (StringUtils.isBlank(veinfo.getScanId())) {
            info.setImageUrl("");
        } else {
            String url = this.maekUrl(veinfo.getScanId(), veinfo.getGfTaxNo());
            info.setImageUrl(url);
        }*/
        return info;
    }

    /**
     * @Description 乐企查验接口
     * @Author wangruwei
     * @Date 2023/3/2 13:54
     **/
    @Override
    public String lqGetCheckInvoice(GlobalInfo globalInfo, Map<String, String> requestParam) {
        log.info("乐企查验接口处理开始");
        try {
            String content = requestParam.get("data");
            log.info("业务报文：{}", content);
            LqCheckDataReq checkDataReq = JSON.parseObject(content, LqCheckDataReq.class);
            //乐企查验接口请求信息校验
            Map<String, String> validMap = validCheckBaseInfo(checkDataReq);
            if (validMap != null) {
                log.info("乐企查验接口请求数据校验失败：{}", validMap);
                return CommonUtils.packageReturnMsg(globalInfo, null, validMap.get("returnCode"), validMap.get("returnMsg"));
            }
            log.info("处理请求数据");
            String reqFplxDm = checkDataReq.getFplx();
            boolean detailFlag = detailReqData(globalInfo, checkDataReq);
            if(detailFlag==false){
                return CommonUtils.packageReturnMsg(globalInfo, null, GlobalReturnEnums.CY_SYDWPTBM_NULL.getCode(), GlobalReturnEnums.CY_SYDWPTBM_NULL.getMsg());
            }

            log.info("开始调channel的查验接口，入参:{}",JSONUtil.toJsonStr(checkDataReq));
            Map<String, String> resultMap = lqCheckInvoiceService.checkInvoice(checkDataReq);
            log.info("调channel的查验接口结束,出参:{}",JSONUtil.toJsonStr(resultMap));
            if("00".equals(resultMap.get("returnCode"))){
                log.info("调查验结果成功,更新source_system为 1查验");
                String uuid = (StringUtils.isBlank(checkDataReq.getFpdm())?"":checkDataReq.getFpdm())+checkDataReq.getFphm();
                TdxRecordInvoiceEntity updateRerord = new TdxRecordInvoiceEntity();
                updateRerord.setSourceSystem("1");
                tdxRecordInvoiceDao.update(updateRerord, new LambdaUpdateWrapper<TdxRecordInvoiceEntity>().eq(TdxRecordInvoiceEntity::getUuid, uuid));

                TdxSaleRecordInvoiceEntity updateSaleRerord = new TdxSaleRecordInvoiceEntity();
                updateSaleRerord.setSourceSystem("1");
                tdxSaleRecordInvoiceDao.update(updateSaleRerord, new LambdaUpdateWrapper<TdxSaleRecordInvoiceEntity>().eq(TdxSaleRecordInvoiceEntity::getUuid, uuid));

                Map<String,String> result = new HashMap<>();
                result.put("fplx", reqFplxDm);
                if(StringUtils.isNotBlank(resultMap.get("data"))){
                    result.put("data", Base64.encode(resultMap.get("data")));
                }else{
                    result.put("data", "");
                }
                return CommonUtils.packageReturnMsg(globalInfo, JSONUtil.toJsonStr(result), GlobalReturnEnums.SUCCESS);
            }else{
                log.info("调查验结果失败");
                return CommonUtils.packageReturnMsg(globalInfo,null, resultMap.get("returnCode"),resultMap.get("returnMsg"));
            }
        } catch (Exception e) {
            log.info("乐企查验接口处理异常：{}",e.getMessage());
            log.info("业务处理异常：{}", e);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.FAILED.getCode(),GlobalReturnEnums.CY_INTERFACE_ERR.getMsg());
        }
    }

    private boolean detailReqData(GlobalInfo globalInfo, LqCheckDataReq checkDataReq) {
        boolean detailFlag = true;

        String jxFpzlDm = checkDataReq.getFplx();
        String LqFpzlDm = CommonUtils.conversionInvoiceTypeToLQ(checkDataReq.getFplx());
        log.info("进项转乐企发票类型，传{}转换为{}",checkDataReq.getFplx(),LqFpzlDm);
        checkDataReq.setFplx(LqFpzlDm);
        //乐企判断是否有异常信息
        DynamicContextHolder.push( DbConstant.BASICS_READ);
        SysEnterpriseConfigEntity enterpriseConfigEntity = sysEnterpriseConfigErpDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, checkDataReq.getNsrsbh()));
        //如果不是乐企，不让调
        if(ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"1".equals(enterpriseConfigEntity.getJrfs())&&StringUtils.isNotBlank(enterpriseConfigEntity.getSydwptbm())){
            checkDataReq.setSydwptbm(enterpriseConfigEntity.getSydwptbm());
        }else{
            log.info("税号{}不属于乐企，不允许调乐企查验接口",checkDataReq.getNsrsbh());
            detailFlag = false;
        }
        if(FplxEnum.QDZZP.getFplxDm().equals(jxFpzlDm)||FplxEnum.QDPP.getFplxDm().equals(jxFpzlDm)||
                FplxEnum.TLKP.getFplxDm().equals(jxFpzlDm)||FplxEnum.HKDZFP.getFplxDm().equals(jxFpzlDm)
                ||FplxEnum.SDFP_JDCTYXSFP.getFplxDm().equals(jxFpzlDm)||FplxEnum.ESCDZ.getFplxDm().equals(jxFpzlDm)){
            log.info("全电发票，设置代码为空，号码用代码加号码");
            checkDataReq.setFphm(StringUtils.isBlank(checkDataReq.getFpdm())?"":checkDataReq.getFpdm()+checkDataReq.getFphm());
            checkDataReq.setFpdm("");
        }
        return detailFlag;
    }


    private Map<String, String> validCheckBaseInfo(LqCheckDataReq checkDataReq) {
        if (checkDataReq == null) {
            log.info("查验参数校验失败，参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_PARAM_NULL);
        }
        if(StringUtils.isBlank(checkDataReq.getFplx())){
            log.info("查验发票类型校验失败，参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_FPLX_NULL);
        }

        if( !("01".equals(checkDataReq.getFplx())||
                "02".equals(checkDataReq.getFplx())||
                "03".equals(checkDataReq.getFplx())||
                "04".equals(checkDataReq.getFplx())||
                "08".equals(checkDataReq.getFplx())||
                "10".equals(checkDataReq.getFplx())||
                "11".equals(checkDataReq.getFplx())||
                "14".equals(checkDataReq.getFplx())||
                "15".equals(checkDataReq.getFplx())||
                "31".equals(checkDataReq.getFplx())||
                "32".equals(checkDataReq.getFplx())||
                "185".equals(checkDataReq.getFplx())||
                "186".equals(checkDataReq.getFplx())||
                "161".equals(checkDataReq.getFplx())||
                "283".equals(checkDataReq.getFplx())||
                "383".equals(checkDataReq.getFplx())||
                "184".equals(checkDataReq.getFplx())||
                "187".equals(checkDataReq.getFplx())||
                "188".equals(checkDataReq.getFplx()))){
            log.info("查验发票类型校验失败，发票类型不支持");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_FPLX_NOT_ALLOW);
        }

        if(StringUtils.isBlank(checkDataReq.getFpdm())){
            log.info("查验发票代码校验失败，参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_FPDM_NULL);
        }
        if(StringUtils.isBlank(checkDataReq.getFphm())){
            log.info("查验发票号码校验失败，参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_FPHM_NULL);
        }
        if(StringUtils.isBlank(checkDataReq.getKprq())){
            log.info("查验开票日期校验失败，参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_KPRQ_NULL);
        }
        if(StringUtils.isNotBlank(checkDataReq.getKpje())){
            if(!CheckUtils.checkStrNum(checkDataReq.getKpje())){
                log.info("查验开票金额校验失败，金额格式错误");
                return CommonUtils.packageValidResult(GlobalReturnEnums.CY_JE_FORMATE_ERR);
            }
        }
        if(StringUtils.isBlank(checkDataReq.getNsrsbh())){
            log.info("查验购方纳税人识别号校验失败，查验参数为空");
            return CommonUtils.packageValidResult(GlobalReturnEnums.CY_GF_NSRSBH_NULL);
        }
        return null;
    }

    public InvoiceInfo getInvoiceInfo(TdxCheckRecordInvoice invoice) {
        InvoiceInfo info = new InvoiceInfo();
        info.setCheckUser(invoice.getCheckUser());
        info.setMachineNo(invoice.getJqbh());
        if(StringUtils.isNotBlank(invoice.getFpdm())){
            info.setInvoiceCode(invoice.getFpdm());
        }else {
            info.setInvoiceCode("");
        }
        info.setInvoiceNo(invoice.getFphm());
        info.setEleInvoiceNo(invoice.getEleInvoiceNo());
        info.setInvoiceDate(invoice.getKprq());
        info.setBuyerAccount(invoice.getGfyhzh());
        info.setBuyerAddressPhone(invoice.getGfdzdh());
        info.setBuyerName(invoice.getGfmc());
        info.setBuyerTaxNo(invoice.getGfsh());
        info.setSalerAccount(invoice.getXfyhzh());
        info.setSalerAddressPhone(invoice.getXfdzdh());
        info.setSalerName(invoice.getXfmc());
        info.setSalerTaxNo(invoice.getXfsh());
        info.setInvoiceAmount(invoice.getJe());
        info.setTaxAmount(invoice.getSe());
        info.setTotalAmount(invoice.getJshj());
        info.setRemark(invoice.getBz());
        /*
        * @Description 调开放平台之前的赋值方法
        * @param invoice
        * @Return com.dxhy.erp.model.InvoiceInfo
        * @Author wangruwei
        * @Date 2024/5/24 11:10
        *if ("Y".equals(invoice.getZfbz())) {

            info.setInvoiceStatus("2");
        } else if ("N".equals(invoice.getZfbz())) {
            info.setInvoiceStatus("0");
        } else {
            info.setInvoiceStatus(invoice.getZfbz());
        }*/
        info.setInvoiceStatus(invoice.getFpzt());
        info.setInvoiceType(invoice.getFpzl());

        if (StringUtils.isBlank(invoice.getJym())) {
            info.setCheckCode("");
        } else {
            info.setCheckCode(invoice.getJym());
        }
        if (StringUtils.isBlank(invoice.getTxfbz())) {
            info.setTxfbz("");
        } else {
            info.setTxfbz(invoice.getTxfbz());
        }
        if (StringUtils.isBlank(invoice.getLslbz())) {
            info.setLslbz("");
        } else {
            info.setLslbz(invoice.getLslbz());
        }
        return info;
    }

    public InvoiceDetailInfo getInvoiceDetailInfo(TdxCheckInvoiceDetail detail) {
        InvoiceDetailInfo detailInfo = new InvoiceDetailInfo();
        detailInfo.setDetailNo(detail.getDetailNo() + "");
        detailInfo.setGoodsName(detail.getGoodsName());
        if (StringUtils.isBlank(detail.getModel())) {
            detailInfo.setSpecificationModel("");
        } else {
            detailInfo.setSpecificationModel(detail.getModel());
        }
        if (StringUtils.isBlank(detail.getGoodsNum())) {
            detailInfo.setGoodsNum("");
        } else {
            detailInfo.setGoodsNum(detail.getGoodsNum());
        }
        if (detail.getNum() == null || "".equals(detail.getNum())) {
            detailInfo.setNum("0");
        } else {
            detailInfo.setNum(detail.getNum() + "");
        }
        if (StringUtils.isBlank(detail.getUnit())) {
            detailInfo.setUnit("");
        } else {
            detailInfo.setUnit(detail.getUnit());
        }
        if (detail.getUnitPrice() == null) {
            detailInfo.setUnitPrice("");
        } else {
            detailInfo.setUnitPrice(detail.getUnitPrice());
        }
        if (detail.getDetailAmount() == null) {
            detailInfo.setDetailAmount("");
        } else {
            detailInfo.setDetailAmount(detail.getDetailAmount());
        }
        if (detail.getTaxRate() == null) {
            detailInfo.setTaxRate("");
        } else {
            detailInfo.setTaxRate(detail.getTaxRate());
        }
        if (detail.getTaxAmount() == null) {
            detailInfo.setTaxAmount("");
        } else {
            detailInfo.setTaxAmount(detail.getTaxAmount());
        }
        if (StringUtils.isBlank(detail.getCph())) {
            detailInfo.setCph("");
        } else {
            detailInfo.setCph(detail.getCph());
        }
        if (StringUtils.isBlank(detail.getLx())) {
            detailInfo.setLx("");
        } else {
            detailInfo.setLx(detail.getLx());
        }
        if (StringUtils.isBlank(detail.getTxrqq())) {
            detailInfo.setTxrqq("");
        } else {
            detailInfo.setTxrqq(detail.getTxrqq());
        }
        if (StringUtils.isBlank(detail.getTxrqz())) {
            detailInfo.setTxrqz("");
        } else {
            detailInfo.setTxrqz(detail.getTxrqz());
        }
        return detailInfo;
    }

    public List<TdxCheckInvoiceDetail> getDetailInfo(String uuid) {
        return super.baseMapper.selectDetailInfo(uuid);
    }

    public CheckVehicleInfo getVehicleInfo(TdxCheckVehicleSale vehicleSaleInvoice, TdxCheckRecordInvoice veinfo) {
        DecimalFormat df = new DecimalFormat("#0.00");
        CheckVehicleInfo info = new CheckVehicleInfo();
        info.setMachineNo(veinfo.getJqbh());
        if(StringUtils.isNotBlank(veinfo.getFpdm())){
            info.setInvoiceCode(veinfo.getFpdm());
        }else {
            info.setInvoiceCode("");
        }

        info.setInvoiceNo(veinfo.getFphm());
        info.setInvoiceType(veinfo.getFpzl());
        info.setBuyerName(veinfo.getGfmc());
        info.setBuyerTaxNo(veinfo.getGfsh());
        info.setInvoiceDate(veinfo.getKprq());
        info.setCheckUser(veinfo.getCheckUser());
        info.setTaxAmount(df.format(new BigDecimal(veinfo.getSe())));
        info.setTotalAmount(df.format(new BigDecimal(veinfo.getJshj())));
        info.setSalerName(veinfo.getXfmc());
        info.setSalerTaxNo(veinfo.getXfsh());
        info.setSalerAccount(veinfo.getXfyhzh());
        info.setSalerAddressPhone(veinfo.getXfdzdh());
        info.setRemark(veinfo.getBz());
        info.setInvoiceAmount(df.format(new BigDecimal(veinfo.getJe())));
        if (StringUtils.isBlank(veinfo.getGfyhzh())) {
            info.setBuyerAcount("");
        } else {
            info.setBuyerAcount(veinfo.getGfyhzh());
        }
        if (StringUtils.isBlank(veinfo.getGfdzdh())) {
            info.setBuyerAddressPhone("");
        } else {
            info.setBuyerAddressPhone(veinfo.getGfdzdh());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getBuyerIdNum())) {
            info.setBuyerIdNum("");
        } else {
            info.setBuyerIdNum(vehicleSaleInvoice.getBuyerIdNum());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getVehicleType())) {
            info.setVehicleType("");
        } else {
            info.setVehicleType(vehicleSaleInvoice.getVehicleType());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getFactoryModel())) {
            info.setFactoryModel("");
        } else {
            info.setFactoryModel(vehicleSaleInvoice.getFactoryModel());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getProductPlace())) {
            info.setProductPlace("");
        } else {
            info.setProductPlace(vehicleSaleInvoice.getProductPlace());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getCertificate())) {
            info.setCertificate("");
        } else {
            info.setCertificate(vehicleSaleInvoice.getCertificate());
        }

        if (StringUtils.isBlank(vehicleSaleInvoice.getCertificateImport())) {
            info.setCertificateImport("");
        } else {
            info.setCertificateImport(vehicleSaleInvoice.getCertificateImport());
        }

        if (StringUtils.isBlank(vehicleSaleInvoice.getInspectionNum())) {
            info.setInspectionNum("");
        } else {
            info.setInspectionNum(vehicleSaleInvoice.getInspectionNum());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getEngineNo())) {
            info.setEngineNo("");
        } else {
            info.setEngineNo(vehicleSaleInvoice.getEngineNo());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getVehicleNo())) {
            info.setVehicleNo("");
        } else {
            info.setVehicleNo(vehicleSaleInvoice.getVehicleNo());
        }

        if (StringUtils.isBlank(vehicleSaleInvoice.getPhone())) {
            info.setPhone("");
        } else {
            info.setPhone(vehicleSaleInvoice.getPhone());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getBuyerBank())) {
            info.setBuyerBank("");
        } else {
            info.setBuyerBank(vehicleSaleInvoice.getBuyerBank());
        }

        try {
            info.setTaxRate(Double.valueOf(vehicleSaleInvoice.getTaxRate()).intValue() + "");
        } catch (Exception e) {
            info.setTaxRate("0");
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxBureauCode())) {
            info.setTaxBureauCode("");
        } else {
            info.setTaxBureauCode(vehicleSaleInvoice.getTaxBureauCode());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxBureauName())) {
            info.setTaxBureauName("");
        } else {
            info.setTaxBureauName(vehicleSaleInvoice.getTaxBureauName());
        }

        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxRecords())) {
            info.setTaxRecords("");
        } else {
            info.setTaxRecords(vehicleSaleInvoice.getTaxRecords());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTonnage())) {
            info.setTonnage("");
        } else {
            info.setTonnage(vehicleSaleInvoice.getTonnage());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getLimitPeople())) {
            info.setLimitPeople("");
        } else {
            info.setLimitPeople(vehicleSaleInvoice.getLimitPeople());
        }
        /*if ("Y".equals(veinfo.getZfbz())) {

            info.setInvoiceStatus("2");
        } else if ("N".equals(veinfo.getZfbz())) {
            info.setInvoiceStatus("0");
        } else {
            info.setInvoiceStatus(veinfo.getZfbz());
        }*/
        info.setInvoiceStatus(veinfo.getFpzt());

        return info;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer selectByAllCount(CollectData data) {
        Map<String, Object> map = new HashMap<>(16);
//        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("company", data.getCompany());
        map.put("invoiceType", data.getInvoiceType());
        map.put("createDateBegin", data.getCreateDateBegin());
        map.put("createDateEnd", data.getCreateDateEnd());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());

        return super.baseMapper.selectAllCount(map);
    }

    @Transactional(rollbackFor = Exception.class)
    public List<TdxCheckRecordInvoice> selectCheckInvoice(CollectData data, Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("company", data.getCompany());
        map.put("invoiceType", data.getInvoiceType());
        map.put("createDateBegin", data.getCreateDateBegin());
        map.put("createDateEnd", data.getCreateDateEnd());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectCheckInvoice(map);
    }

    public ReturnStateInfo getCheck(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getCompany())) {
            run.setReturnCode(ReturnCodeEnum.QYBS.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QYBS.getFhzMc(ReturnCodeEnum.QYBS.getIndex()));
        }

        if (CheckUtils.isNullOrEmpty(data.getCreateDateBegin())
            || (!CheckUtils.stringLength(data.getCreateDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getCreateDateEnd())
            || (!CheckUtils.stringLength(data.getCreateDateEnd(), 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 List<TdxCheckVehicleSale> selectVehicle(String uuid) {
        return super.baseMapper.selectVehicle(uuid);
    }
}
