package com.dxhy.jxpt.baseService.rzInvoice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.db.TdxRecordInvoiceEntity;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.rz.rzInvoice.RzInvoicePageReq;
import com.dxhy.api.model.rz.rzInvoice.RzInvoicePageReqItem;
import com.dxhy.api.model.rz.rzInvoice.TDxRecordInvoicePreRzVo;
import com.dxhy.api.model.rz.rzInvoice.drrq.RzReqItem;
import com.dxhy.api.model.rz.rzInvoice.page.InvoiceRzInfo;
import com.dxhy.api.model.rz.rzInvoice.page.TdxLqRzInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.dao.TdxRecordInvoiceDao;
import com.dxhy.jxpt.baseService.rzInvoice.dao.RzRecordInvoiceDao;
import com.dxhy.jxpt.baseService.rzInvoice.dao.TDxLqRzInvoiceDao;
import com.dxhy.jxpt.baseService.rzInvoice.service.RzInvoiceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
* @Description 大企业发票入账业务
* @Author wangruwei
* @Date 2023/9/21 16:20
**/
@Service("baseServicerzInvoiceService")
@Slf4j
public class RzInvoiceServiceImpl extends MpBaseServiceImpl<RzRecordInvoiceDao, TDxRecordInvoice> implements RzInvoiceService {

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private TDxLqRzInvoiceDao tDxLqRzInvoiceDao;

    @Resource
    private RzRecordInvoiceDao rzRecordInvoiceDao;

    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Resource
    private TdxRecordInvoiceDao tdxRecordInvoiceDao;


    @Override
    public Object preRzInvoiceList(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            //json = tabulateRedisService.getTabulateMenu(company, menuId);

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjje = "0.00";
                String hjse = "0.00";
                List<TDxRecordInvoicePreRzVo> hjList = super.baseMapper.selectPreRzInvoiceHj(pramsMap);
                TDxRecordInvoicePreRzVo hjxx = hjList.get(0);
                hjsl = hjxx.getId();
                if (!"0".equals(hjsl)) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount()));
                }
                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjse", hjse);
            }

            PageHelper.startPage(curr, size);
            List<TDxRecordInvoicePreRzVo> pageList = super.baseMapper.selectPreRzInvoiceList(pramsMap);
            PageInfo<TDxRecordInvoicePreRzVo> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoicePreRzVo> resultList = pageInfo.getList();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + start));

                    if (!"01".equals(resultList.get(i).getInvoiceType())
                            && !"03".equals(resultList.get(i).getInvoiceType())
                            && !"08".equals(resultList.get(i).getInvoiceType())
                            && !"14".equals(resultList.get(i).getInvoiceType())
                            && !"31".equals(resultList.get(i).getInvoiceType())) {
                        resultList.get(i).setDkTaxAmount(null);
                    } else {
                        if (StringUtils.isNotBlank(resultList.get(i).getDkTaxAmount())) {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkTaxAmount())));
                        } else {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                        }
                    }

                    if(StringUtils.isNotEmpty(resultList.get(i).getInvoiceAmount())){
                        resultList.get(i).setInvoiceAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                    }

                    pageList.get(i)
                            .setSelect(true);
                    if(StringUtils.isNotEmpty(resultList.get(i).getTaxAmount())){
                        resultList.get(i)
                                .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getTotalAmount())){
                        resultList.get(i).setTotalAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTotalAmount())));
                    }


                    String glzt = resultList.get(i).getGlzt();
                    resultList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    String settlementStatus = resultList.get(i).getSettlementStatus();
                    resultList.get(i).setSettlementStatus(
                            dictdetaServcice.queryDictName(DictConstant.SETTLEMENT_STATUS, settlementStatus));
                    String invoiceStatus = resultList.get(i).getInvoiceStatus();
                    resultList.get(i)
                            .setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceStatus));
                    String rzzt = resultList.get(i).getRzzt();
                    resultList.get(i).setRzzt(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzzt));
                    String rzclzt = resultList.get(i).getRzclzt();
                    resultList.get(i).setRzclzt(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, rzclzt));
                    String qszt = resultList.get(i).getQszt();
                    resultList.get(i).setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qszt));
                    String qsfs = resultList.get(i).getQsfs();
                    resultList.get(i).setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsfs));
                    String bdkStatus = resultList.get(i).getBdkStatus();
                    resultList.get(i).setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                    String inAccountStatus = resultList.get(i).getInAccountStatus();
                    resultList.get(i)
                            .setInAccountStatus(dictdetaServcice.queryDictName(DictConstant.DK_STATUS, inAccountStatus));
                }
            }

            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", resultList);

        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }
    /**
     * @Description 入账结果查询
     * @Author wangruwei
     * @Date 2023/9/21 16:48
     **/
    @Override
    public Object rzInvoiceResultList(Map<String, Object> pramsMap, int curr, int size) {
        //用关联去处理 t_dx_lq_rz_invoice 和 底账表
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            //json = tabulateRedisService.getTabulateMenu(company, menuId);

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjje = "0.00";
                String hjse = "0.00";
                List<TDxRecordInvoicePreRzVo> hjList = super.baseMapper.selectRzInvoiceResultHj(pramsMap);
                TDxRecordInvoicePreRzVo hjxx = hjList.get(0);
                hjsl = hjxx.getId();
                if (!"0".equals(hjsl)) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount()));
                }
                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjse", hjse);
            }


            PageHelper.startPage(curr, size);
            List<TDxRecordInvoicePreRzVo> pageList = super.baseMapper.selectRzInvoiceResultList(pramsMap);
            PageInfo<TDxRecordInvoicePreRzVo> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoicePreRzVo> resultList = pageInfo.getList();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + start));

                    if (!"01".equals(resultList.get(i).getInvoiceType())
                            && !"03".equals(resultList.get(i).getInvoiceType())
                            && !"08".equals(resultList.get(i).getInvoiceType())
                            && !"14".equals(resultList.get(i).getInvoiceType())
                            && !"31".equals(resultList.get(i).getInvoiceType())) {
                        resultList.get(i).setDkTaxAmount(null);
                    } else {
                        if (StringUtils.isNotBlank(resultList.get(i).getDkTaxAmount())) {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkTaxAmount())));
                        } else {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                        }
                    }

                    //可勾选进行撤销的数据  4入账成功  7撤销失败
                    if("4".equals(resultList.get(i).getFprzAuthStatus())||"7".equals(resultList.get(i).getFprzAuthStatus())){
                        resultList.get(i).setSelect(true);
                    }else{
                        resultList.get(i).setSelect(false);
                    }

                    if(StringUtils.isNotEmpty(resultList.get(i).getInvoiceAmount())){
                        resultList.get(i).setInvoiceAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getTaxAmount())){
                        resultList.get(i)
                                .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getTotalAmount())){
                        resultList.get(i).setTotalAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTotalAmount())));
                    }

                    String glzt = resultList.get(i).getGlzt();
                    resultList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    String settlementStatus = resultList.get(i).getSettlementStatus();
                    resultList.get(i).setSettlementStatus(
                            dictdetaServcice.queryDictName(DictConstant.SETTLEMENT_STATUS, settlementStatus));
                    String invoiceStatus = resultList.get(i).getInvoiceStatus();
                    resultList.get(i)
                            .setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceStatus));
                    String rzzt = resultList.get(i).getRzzt();
                    resultList.get(i).setRzzt(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzzt));
                    String rzclzt = resultList.get(i).getRzclzt();
                    resultList.get(i).setRzclzt(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, rzclzt));
                    String qszt = resultList.get(i).getQszt();
                    resultList.get(i).setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qszt));
                    String qsfs = resultList.get(i).getQsfs();
                    resultList.get(i).setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsfs));
                    String bdkStatus = resultList.get(i).getBdkStatus();
                    resultList.get(i).setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                    String inAccountStatus = resultList.get(i).getInAccountStatus();
                    resultList.get(i)
                            .setInAccountStatus(dictdetaServcice.queryDictName(DictConstant.DK_STATUS, inAccountStatus));

                    String lqHzsdbs = resultList.get(i).getLqHzsdbs();
                    resultList.get(i)
                            .setLqHzsdbs(dictdetaServcice.queryDictName(DictConstant.HZSDZT, lqHzsdbs));
                    String fprzauthStatus = resultList.get(i).getFprzAuthStatus();
                    resultList.get(i)
                            .setFprzAuthStatus(dictdetaServcice.queryDictName(DictConstant.INACCOUNT_GLZT, fprzauthStatus));

                    //入账状态
                    //入账申请状态：1申请入账，2发送入账请求，3入账失败，4入账成功，5申请撤销，6发送撤销申请，7撤销失败，8撤销成功
                    //4 5 6 7 属于入账成功
                    //1 2 3 8 属于入账失败
                    if("4".equals(fprzauthStatus)||"5".equals(fprzauthStatus)||"6".equals(fprzauthStatus)||"7".equals(fprzauthStatus)){
                        resultList.get(i)
                                .setLqRzzt("已入账");
                    }else{
                        resultList.get(i)
                                .setLqRzzt("未入账");
                    }

                    //入账用途
                    String fprzlx = resultList.get(i).getFprzlx();
                    resultList.get(i)
                            .setFprzlx(dictdetaServcice.queryDictName(DictConstant.INACCOUNT_YT_RZPAGE, fprzlx));

                }
            }

            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", resultList);

        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    /**
     * 入账/撤销入账  申请
     **/
    @Override
    public boolean rzInvoiceReq(RzInvoicePageReq req, String userName) {
        try {
            List<RzInvoicePageReqItem> invoiceList = req.getInvoiceList();
            //按税号分组
            Map<String, List<RzInvoicePageReqItem>> groupBySh = invoiceList.stream().collect(Collectors.groupingBy(RzInvoicePageReqItem::getGfTaxNo));

            Set<String> gfList = invoiceList.stream().map(RzInvoicePageReqItem::getGfTaxNo).collect(Collectors.toSet());

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<SysEnterpriseConfigEntity> qyDtoList = sysEnterpriseConfigDao.selectList(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().in(SysEnterpriseConfigEntity::getNsrsbh, gfList));
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            Set<String> shSet = new HashSet<>();
            //把对号对应的企业类型查到
            groupBySh.keySet().forEach(key -> {
                shSet.add(key);
                String tdlx = qyDtoList.stream().filter(e->e.getNsrsbh().equals(key)).findFirst().get().getJrfs();

                InvoiceRzInfo iri = new InvoiceRzInfo();
                //把税号这些放进去
                iri.setNsrsbh(key);
                iri.setPclsh(UUID.randomUUID().toString().replace("-", ""));
                iri.setRzlx(req.getRzlx());
                iri.setRzsq(req.getRzsq());
                List<RzInvoicePageReqItem> rzInvoicePageReqItems = groupBySh.get(key);

                rzInvoicePageReqItems.stream().forEach(ii->{
                    String uuid = getInvoiceUuid(ii.getInvoiceCode(),ii.getInvoiceNo());
                    //查询发票入账表
                    TdxLqRzInvoice tri = tDxLqRzInvoiceDao.selectOne(new QueryWrapper<TdxLqRzInvoice>().eq("uuid",uuid ));
                    if (tri != null) {
                        //发票入账表有数据则更新
                        tri.setFprzsq(iri.getRzsq());
                        tri.setFprzlx(iri.getRzlx());
                        //判断入账类型是否为撤销入账设置入账申请状态
                        String fprzAuthStatus = iri.getRzlx().equals("06") ? "5" : "1";
                        tri.setFprzAuthStatus(fprzAuthStatus);
                        tri.setFprzsbyy("");
                        tri.setFprzsj("");
                        tri.setUpdateTime(new Date());
                        tri.setTdlx(tdlx);
                        tri.setRzr(userName);
                        log.info("{} 更新入账表:{}",tri);
                        tDxLqRzInvoiceDao.updateById(tri);
                    } else {
                        //查询抵账表
                        TDxRecordInvoice fpInfo = rzRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("gf_tax_no", iri.getNsrsbh()).eq("uuid", uuid));
                        //插入
                        TdxLqRzInvoice rzInfo = new TdxLqRzInvoice();
                        rzInfo.setNsrsbh(iri.getNsrsbh());
                        rzInfo.setInvoiceType(fpInfo.getInvoiceType());
                        rzInfo.setInvoiceCode(fpInfo.getInvoiceCode());
                        rzInfo.setInvoiceNo(fpInfo.getInvoiceNo());
                        rzInfo.setEleInvoiceNo(fpInfo.getEleInvoiceNo());
                        rzInfo.setUuid(fpInfo.getUuid());
                        rzInfo.setInvoiceDate(fpInfo.getInvoiceDate());
                        rzInfo.setFprzsq(iri.getRzsq());
                        rzInfo.setFprzAuthStatus(iri.getRzlx().equals("06") ? "5" : "1");
                        rzInfo.setFprzlx(iri.getRzlx());
                        rzInfo.setTdlx(tdlx);
                        rzInfo.setRzr(userName);
                        rzInfo.setCreateTime(new Date());
                        log.info("保存入账表:{}", JSON.toJSONString(rzInfo));
                        tDxLqRzInvoiceDao.insert(rzInfo);
                    }

                    //更新底账表
                    //入账
                    TDxRecordInvoice updateRecord = new TDxRecordInvoice();
                    if(!"06".equals(iri.getRzlx())){
                        updateRecord.setLqRzzt("04");
                    }else{
                        //入账撤销
                        updateRecord.setLqRzzt("05");
                    }
                    rzRecordInvoiceDao.update(updateRecord,new QueryWrapper<TDxRecordInvoice>().eq("uuid", uuid));
                });

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

    /**
     * @Description 导入入账
     * @param reqList
     * @param gfshList
     * @param userName
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/6/4 19:53
     **/
    @Override
    public ResponseEntity<R> importRzInvoice(List<RzReqItem> reqList, List<String> gfshList, String userName) {
        List<String> errorMsgList = checkDrParam(reqList,gfshList);
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            log.info("参数校验未通过");
            return ResponseEntity.ok(R.error(9998, "参数校验未通过").put("data", errorMsgList));
        }
        reqList.stream().forEach(param->{
            try {
                String fpdm = param.getInvoiceCode();
                String fphm = param.getInvoiceNo();
                String rzType = param.getRzType();
                String rzsq = param.getRzsq();
                String sdhm = null;
                if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                    //判断为数电号码
                    sdhm = fphm;
                }
                TdxRecordInvoiceEntity invoice = null;
                if (StringUtils.isNotBlank(sdhm)) {
                    invoice = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TdxRecordInvoiceEntity>().eq("ele_invoice_no", sdhm));
                } else {
                    invoice = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TdxRecordInvoiceEntity>().eq("invoice_code", fpdm).eq("invoice_no",fphm));
                }

                //调入账申请方法
                RzInvoicePageReq req = new RzInvoicePageReq();
                String rzlx = "";
                if("入账（企业所得税前扣除）".equals(rzType)){
                    rzlx = "02";
                }else if("入账（企业所得税不扣除）".equals(rzType)){
                    rzlx = "03";
                }else{
                    log.error("导入没有此入账类型");
                }
                req.setRzlx(rzlx);
                req.setRzsq(rzsq.replace("-", ""));
                RzInvoicePageReqItem item = new RzInvoicePageReqItem();
                item.setGfTaxNo(invoice.getGfTaxNo());
                item.setInvoiceCode(fpdm);
                item.setInvoiceNo(fphm);
                req.setInvoiceList(Arrays.asList(item));
                //调方法
                rzInvoiceReq(req, userName);
            } catch (Exception e) {
                log.info("业务处理异常：{}", e);
                return;
            }
        });
        log.info("导入入账完成");
        return ResponseEntity.ok(R.ok().put("data", reqList.size()));
    }


    private List<String> checkDrParam(List<RzReqItem> reqList, List<String> gfshList) {
        int index = 0;
        List<String> errorMsgList = new ArrayList<>();
        List<String> uuidList = new ArrayList<>();
        for (RzReqItem param : reqList) {
            String error = null;
            index ++;
            String fpdm = param.getInvoiceCode();
            String fphm = param.getInvoiceNo();
            String uuid = StringUtils.defaultString(fpdm) + StringUtils.defaultString(fphm);
            String rzType = param.getRzType();
            String rzsq = param.getRzsq();
            String sdhm = null;

            if (StringUtils.isBlank(fphm)) {
                error = "第"+index+ "条数据：入账发票号码不能为空";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            if (StringUtils.isBlank(rzType)) {
                error = "第"+index+ "条数据：入账类型不能为空";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            if (StringUtils.isBlank(rzsq)) {
                error = "第"+index+ "条数据：入账属期不能为空";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            if (uuidList.contains(uuid)) {
                error = "第"+index+ "条数据：数据重复，发票代码："+fpdm+"发票号码："+fphm;
                log.info(error);
                errorMsgList.add(error);
                continue;
            } else {
                uuidList.add(uuid);
            }

            if (StringUtils.isNotBlank(fpdm)) {
                if (fpdm.length() != 10 && fpdm.length() != 12) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码长度应为10或者12";
                    log.info(error);
                    errorMsgList.add(error);
                    continue;
                }
                if (!CommonUtil.checkStrNum(fpdm)) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码必须为数字";
                    log.info(error);
                    errorMsgList.add(error);
                    continue;
                }
                if (StringUtils.isBlank(fphm) || fphm.length() != 8) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票号码长度必须为8";
                    log.info(error);
                    errorMsgList.add(error);
                    continue;
                }
            }else{
                if (StringUtils.isBlank(fphm) || fphm.length() != 20) {
                    error = "第"+index+ "条数据：发票代码为空时，发票号码长度必须为20";
                    log.info(error);
                    errorMsgList.add(error);
                    continue;
                }
            }

            if (!CommonUtil.checkStrNum(fphm)) {
                error = "第"+index+ "条数据：发票号码必须为数字";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                //判断为数电号码
                sdhm = fphm;
            }

            TdxRecordInvoiceEntity invoice = null;
            if (StringUtils.isNotBlank(sdhm)) {
                invoice = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TdxRecordInvoiceEntity>().eq("ele_invoice_no", sdhm));
            } else {
                invoice = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TdxRecordInvoiceEntity>().eq("invoice_code", fpdm).eq("invoice_no",fphm));
            }

            if (invoice == null) {
                error = "第"+index+ "条数据：底账库不存在该发票";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            SysEnterpriseConfigEntity enterpriseConfig = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", invoice.getGfTaxNo()));
            if (enterpriseConfig == null) {
                error = "第"+index+ "条数据：未查询到该购方税号："+invoice.getGfTaxNo()+"的配置信息";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //验证税号是否在当前用户
            if(!gfshList.contains(invoice.getGfTaxNo())){
                error = "第"+index+ "条数据：购方税号不属于当前登录人权限";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //3.2.6校验发票入账状态，如果是入账中（除未入账、入账失败）则返回错误XXX行发票已在入账中请重复入账
            if(!"01".equals(invoice.getLqRzzt())&&!"03".equals(invoice.getLqRzzt())){
                error = "第"+index+ "条数据：发票已在入账中请勿重复入账";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //校验发票状态是否正常，如果发票状态异常则提醒XXX发票状态异常不允许入账
            if(("0".equals(invoice.getInvoiceStatus())||"7".equals(invoice.getInvoiceStatus()))&&"N".equals(invoice.getLqHzsdbs())){

            }else{
                error = "第"+index+ "条数据：发票状态异常不允许入账";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }
            /*if(!"0".equals(invoice.getInvoiceStatus())||!"N".equals(invoice.getLqHzsdbs())){
                error = "第"+index+ "条数据：发票状态异常不允许入账";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }*/

            if(!"入账（企业所得税前扣除）".equals(rzType)&&!"入账（企业所得税不扣除）".equals(rzType)){
                error = "第"+index+ "条数据：入账类型错误";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //入账属期为年月格式，否则返回XXXX行入账属期错误；
            if(!DateUtils.checkStrFormat(rzsq, "yyyy-MM")){
                error = "第"+index+ "条数据：入账属期错误,需为yyyy-MM,例如：2023-05";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //校验入账属期是否小于等于当前月，如果不满足则返回错误XXX行入账属期大于当前月不允许入账
            if(Integer.parseInt(rzsq.replace("-", ""))>Integer.parseInt(DateUtils.getNowMonthStr().replace("-", ""))){
                error = "第"+index+ "条数据：入账属期大于当前月不允许入账";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

            //校验入账属期与发票发票日期，如果发票日期对应月份大于入账属期，则返回错误
            if(Integer.parseInt(rzsq.replace("-", ""))<Integer.parseInt(DateUtils.dateToStr(invoice.getInvoiceDate(), "yyyy-MM").replace("-", ""))){
                error = "第"+index+ "条数据：开票日期大于入账属期不允许入账";
                log.info(error);
                errorMsgList.add(error);
                continue;
            }

        }
        uuidList.clear();
        return errorMsgList;
    }

}
