package com.dxhy.erp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.rz.rzInvoice.page.TdxLqRzInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.Base64FileUtil;
import com.dxhy.erp.dao.*;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.enums.GlobalReturnEnums;
import com.dxhy.erp.service.LqFpRzService;
import com.dxhy.erp.utils.CommonUtils;
import com.dxhy.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * @author Allen
 * @version 1.0.0
 * @ClassName LqFpRzServiceImpl.java
 * @Description 乐企票据入账业务类
 * @createTime 2023年02月22日 16:38:00
 */
@Service
@Slf4j
public class LqFpRzServiceImpl implements LqFpRzService {

    private static final String  LOG_MSG ="（票据入账业务处理类）";

    @Autowired
    private ErpTDxLqRzBatchDao erpTDxLqRzBatchDao;

    @Autowired
    private ErpTDxLqRzCustomDao erpTDxLqRzCustomDao;

    @Autowired
    private ErpTDxLqRzInvoiceDao erpTDxLqRzInvoiceDao;

    @Autowired
    private TdxRecordInvoiceErpDao tdxRecordInvoiceDao;

    @Autowired
    private ErpTdxInvoiceFileDao erpTdxInvoiceFileDao;

    @Autowired
    private ErpTdxCustomsRecordDao erpTdxCustomsRecordDao;

    @Autowired
    private BaseSysEnterpriseConfigErpDao sysEnterpriseConfigErpDao;

    @Autowired
    private FileService fileService;
    /**
     * @param
     * @description 发票入账接口
     * @author Allen
     * @updateTime 2023/2/22 17:09
     */
    @Override
    public String fpRz(GlobalInfo globalInfo , Map<String, String> requestParam) {
        log.info("{} 发票入账处理开始",LOG_MSG);
        try {
            String content = requestParam.get("data");
            log.info("{} 业务报文：{}",LOG_MSG,content);
            InvoiceRzInfo iri = JSON.parseObject(content, InvoiceRzInfo.class);

            //用business数据库
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);

            //入账主体信息校验
            Map<String,String> validMap = validRzBaseInfo(iri);
            if (validMap != null) {
                log.info("{} 入账主体信息校验失败：{}",LOG_MSG,validMap);
                return CommonUtils.packageReturnMsg(globalInfo,null, validMap.get("returnCode") ,validMap.get("returnMsg"));
            }

            /*//验证是否乐企
            DynamicContextHolder.push( DbConstant.BASICS_READ);
            SysEnterpriseConfigEntity enterpriseConfigEntity = sysEnterpriseConfigErpDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, iri.getNsrsbh()));

            //如果不是乐企，不让调
            if(ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"1".equals(enterpriseConfigEntity.getJrfs())&&StringUtils.isNotBlank(enterpriseConfigEntity.getSydwptbm())){
                //是乐企，允许调
            }else{
                //log.info("税号{}不属于乐企，不允许调乐企接口",iri.getNsrsbh());
                //return CommonUtils.packageReturnMsg(globalInfo, null, GlobalReturnEnums.CY_SYDWPTBM_NULL.getCode(), GlobalReturnEnums.CY_SYDWPTBM_NULL.getMsg());
            }*/

            //用business数据库
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);

            //入账明细信息校验
            Map<String,String> validMxMap = validInvoiceRzMxInfo(iri);
            if (validMxMap != null) {
                log.info("{} 入账明细信息校验失败：{}",LOG_MSG,validMxMap);
                return CommonUtils.packageReturnMsg(globalInfo,null, validMxMap.get("returnCode") ,validMxMap.get("returnMsg"));
            }

            iri.getInvoiceList().stream().forEach(ii->{
                //查询抵账表
                TDxRecordInvoice fpInfo = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("gf_tax_no", iri.getNsrsbh()).eq("uuid", ii.getFpdm() + ii.getFphm()));
                //查询发票入账表
                TdxLqRzInvoice tri = erpTDxLqRzInvoiceDao.selectOne(new QueryWrapper<TdxLqRzInvoice>().eq("uuid", ii.getFpdm() + ii.getFphm()));
                //插入批次表
                insertRzBatch(iri.getPclsh(),ii.getFpdm() + ii.getFphm(),"0");
                if (tri != null) {
                    if (    tri.getFprzAuthStatus().equals("1")||
                            tri.getFprzAuthStatus().equals("2")||
                            tri.getFprzAuthStatus().equals("5")||
                            tri.getFprzAuthStatus().equals("6")) {
                        //如果是入账中则不处理数据
                            return;
                    }

                    if (    iri.getRzlx().equals("02")||
                            iri.getRzlx().equals("03")||
                            iri.getRzlx().equals("04")||
                            iri.getRzlx().equals("05")) {
                        //接口申请入账处理流程

                        if (tri.getFprzAuthStatus().equals("4")||tri.getFprzAuthStatus().equals("7")) {
                            //如果是入账成功则不处理数据
                            return;
                        }

                        if (tri.getFprzAuthStatus().equals("3")||tri.getFprzAuthStatus().equals("8")) {
                            //未入账  更新入账数据
                            updateRzInvoice(tri,iri);
                        }
                    }

                    if (iri.getRzlx().equals("06")) {
                        //接口申请入账撤销处理流程
                        if (tri.getFprzAuthStatus().equals("3")||tri.getFprzAuthStatus().equals("8")) {
                            //如果是未入账则不处理数据
                            return;
                        }

                        if (tri.getFprzAuthStatus().equals("4")||tri.getFprzAuthStatus().equals("7")) {
                            //已入账  更新入账数据
                            updateRzInvoice(tri,iri);
                        }
                    }

                } else {
                    //插入
                    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.setRzr("接口入账");
                    rzInfo.setCreateTime(new Date());
                    log.info("{} 保存入账表:{}",LOG_MSG,rzInfo);
                    erpTDxLqRzInvoiceDao.insert(rzInfo);
                    //更新抵账表入账状态
                    tdxRecordInvoiceDao.update(null, new LambdaUpdateWrapper<TDxRecordInvoice>()
                            .set(TDxRecordInvoice::getLqRzzt, iri.getRzlx().equals("06") ? "05" : "04")
                            .eq(TDxRecordInvoice::getUuid, (StringUtils.isBlank(ii.getFpdm())?"":ii.getFpdm()) + ii.getFphm()));
                }
            });
            log.info("{} 发票入账处理完成",LOG_MSG);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.SUCCESS);
        } catch (Exception e) {
            log.info("{} 发票入账处理异常：{}",LOG_MSG,e);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.FAILED);
        }
    }

    private void updateRzInvoice(TdxLqRzInvoice tri, InvoiceRzInfo iri) {
        //发票入账更新
        tri.setFprzsq(iri.getRzsq());
        tri.setFprzlx(iri.getRzlx());
        //判断入账类型是否为撤销入账设置入账申请状态
        tri.setFprzAuthStatus(iri.getRzlx().equals("06") ? "5" : "1");
        tri.setFprzsbyy("");
        tri.setFprzsj("");
        tri.setRzr("接口入账");
        tri.setUpdateTime(new Date());
        log.info("{} 更新入账表:{}",LOG_MSG,tri);
        erpTDxLqRzInvoiceDao.updateById(tri);
        //更新抵账表入账状态
        tdxRecordInvoiceDao.update(null, new LambdaUpdateWrapper<TDxRecordInvoice>()
                .set(TDxRecordInvoice::getLqRzzt, iri.getRzlx().equals("06") ? "05" : "04")
                .eq(TDxRecordInvoice::getUuid, tri.getUuid()));
    }

    private Map<String,String> validInvoiceRzMxInfo(InvoiceRzInfo iri) {
        List<InvoiceRzItemInfo> invoiceList = iri.getInvoiceList();
        if (invoiceList == null || invoiceList.size()==0) {
            log.info("{} 入账发票参数校验失败，发票为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_PJXX_NULL);
        }

        if (invoiceList.size() > 100) {
            log.info("{} 入账发票最大支持100条",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_MX_TOO_LONG);
        }

        for (int i = 0;i<invoiceList.size();i++) {
            InvoiceRzItemInfo ii = invoiceList.get(i);
            if (StringUtils.isBlank(ii.getFpdm())) {
                log.info("{} 发票代码不能为空",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.FP_DM_NULL,i+1);
            }
            if (StringUtils.isBlank(ii.getFphm())) {
                log.info("{} 发票号码不能为空",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.FP_HM_NULL,i+1);
            }

            //查询抵账表
            TDxRecordInvoice tdxRecordInvoice = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("gf_tax_no", iri.getNsrsbh()).eq("uuid", ii.getFpdm() + ii.getFphm()));
            if (tdxRecordInvoice == null) {
                log.info("{} 未查询到符合条件的票据",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.NO_CONDITION_PJ,i+1);
            }

            //校验开票日期不能晚于入账属期
            if (CommonUtils.validKprqAndRzsq(tdxRecordInvoice.getInvoiceDate(),iri.getRzsq())) {
                log.info("{} 入账发票开票日期不能晚于入账属期",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.KPRQ_ERROR,i+1);
            }

            //入账撤销不校验发票状态
            if (!"06".equals(iri.getRzlx())) {
                //校验发票状态必须为正常
                if (!tdxRecordInvoice.getInvoiceStatus().equals("0")&&!tdxRecordInvoice.getInvoiceStatus().equals("7")) {
                    log.info("{} 入账发票状态必须为正常或部分冲红",LOG_MSG);
                    return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_FPZT_ERROR,i+1);
                }
            }


            //校验入账发票类型范围
            if (!tdxRecordInvoice.getInvoiceType().equals("01")
                    && !tdxRecordInvoice.getInvoiceType().equals("02")
                    && !tdxRecordInvoice.getInvoiceType().equals("03")
                    && !tdxRecordInvoice.getInvoiceType().equals("04")
                    && !tdxRecordInvoice.getInvoiceType().equals("08")
                    && !tdxRecordInvoice.getInvoiceType().equals("10")
                    && !tdxRecordInvoice.getInvoiceType().equals("11")
                    && !tdxRecordInvoice.getInvoiceType().equals("14")
                    && !tdxRecordInvoice.getInvoiceType().equals("15")
                    && !tdxRecordInvoice.getInvoiceType().equals("31")
                    && !tdxRecordInvoice.getInvoiceType().equals("32")
                    && !tdxRecordInvoice.getInvoiceType().equals("183")
                    && !tdxRecordInvoice.getInvoiceType().equals("184")
                    && !tdxRecordInvoice.getInvoiceType().equals("185")
                    && !tdxRecordInvoice.getInvoiceType().equals("186")
                    && !tdxRecordInvoice.getInvoiceType().equals("187")
                    && !tdxRecordInvoice.getInvoiceType().equals("188")
                    && !tdxRecordInvoice.getInvoiceType().equals("161")
                    && !tdxRecordInvoice.getInvoiceType().equals("283")
                    && !tdxRecordInvoice.getInvoiceType().equals("383")) {
                log.info("{} 入账发票类型必须符合01、02、03、04、08、10、11、14、15、31、32、183、184、185、186、187、188、161、283、383",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.FP_LX_ERROR,i+1);
            }
        }

        return null;
    }

    /**
     *  校验入账发票参数
     * @param iri
     * @return
     */
    private Map<String,String> validRzBaseInfo(RzBaseInfo iri) {
        log.info("{} 入账参数校验。。。",LOG_MSG);
        if (iri == null) {
            log.info("{} 入账参数校验失败，入账参数为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_NULL);
        }

        if (StringUtils.isBlank(iri.getPclsh())) {
            log.info("{} 批次号不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_PCLSH_NULL);
        }

        TdxLqRzBatch trb = erpTDxLqRzBatchDao.selectOne(new QueryWrapper<TdxLqRzBatch>().eq("pclsh", iri.getPclsh()));
        if (trb != null) {
            log.info("{} 入账批次流水号重复",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_PCLSH_CF);
        }

        if (StringUtils.isBlank(iri.getNsrsbh())) {
            log.info("{} 纳税人识别号不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.GHF_NSRSBH_NULL);
        }

        if (StringUtils.isBlank(iri.getRzlx())) {
            log.info("{} 入账类型不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_LX_NULL);
        }

        if (!iri.getRzlx().equals("02")
                && !iri.getRzlx().equals("03")
                && !iri.getRzlx().equals("04")
                && !iri.getRzlx().equals("05")
                && !iri.getRzlx().equals("06")) {
            log.info("{} 入账类型必须符合02、03、04、05、06",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_LX_ERROR);
        }

        if (StringUtils.isBlank(iri.getRzsq())) {
            log.info("{} 入账属期不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_SQ_NULL);
        }

        if (!CommonUtils.validMonth(iri.getRzsq())) {
            log.info("{} 入账属期格式必须满足“YYYYMM”",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_SQ_FORMAT_ERROR);
        }

        if (CommonUtils.validSqForDqy(iri.getRzsq())) {
            log.info("{} 入账属期不能晚于当前自然月",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_SQ_ERROR);
        }

        return null;
    }

    /**
     * @param
     * @description 发票入账结果查询接口
     * @author Allen
     * @updateTime 2023/2/22 17:09
     */
    @Override
    public String fpRzCx(GlobalInfo globalInfo ,Map<String, String> requestParam) {
        log.info("{} 发票入账结果查询处理开始",LOG_MSG);
        try {
            //查询批次数据信息
            return processBatchData(globalInfo ,requestParam,"0");
        } catch (Exception e) {
            log.info("{} 发票入账结果查询处理异常：{}",LOG_MSG,e);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.FAILED);
        }
    }

    /**
     * @param
     * @description 缴款书入账接口
     * @author Allen
     * @updateTime 2023/2/22 17:09
     */
    @Override
    public String jksRz(GlobalInfo globalInfo ,Map<String, String> requestParam) {
        log.info("{} 缴款书入账处理开始",LOG_MSG);
        try {
            String content = requestParam.get("data");
            log.info("{} 业务报文：{}",LOG_MSG,content);
            CustomRzInfo cri = JSON.parseObject(content, CustomRzInfo.class);

            //用business数据库
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            //入账基本信息校验
            Map<String,String> validMap = validRzBaseInfo(cri);
            if (validMap != null) {
                log.info("{} 入账基本信息校验失败：{}",LOG_MSG,validMap);
                return CommonUtils.packageReturnMsg(globalInfo,null, validMap.get("returnCode") ,validMap.get("returnMsg"));
            }

            //验证是否乐企*/
            DynamicContextHolder.push( DbConstant.BASICS_READ);
            SysEnterpriseConfigEntity enterpriseConfigEntity = sysEnterpriseConfigErpDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, cri.getNsrsbh()));
            //如果不是乐企，不让调
            if(ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"1".equals(enterpriseConfigEntity.getJrfs())&&StringUtils.isNotBlank(enterpriseConfigEntity.getSydwptbm())){
                //是乐企，允许调
            }else{
                log.info("税号{}不属于乐企，不允许调乐企查验接口",cri.getNsrsbh());
                return CommonUtils.packageReturnMsg(globalInfo, null, GlobalReturnEnums.CY_SYDWPTBM_NULL.getCode(), GlobalReturnEnums.CY_SYDWPTBM_NULL.getMsg());
            }
            //用business数据库
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);

            //入账明细信息校验
            Map<String,String> validMxMap = validJksRzMxInfo(cri);
            if (validMxMap != null) {
                log.info("{} 入账缴款书明细信息校验失败：{}",LOG_MSG,validMxMap);
                return CommonUtils.packageReturnMsg(globalInfo,null, validMxMap.get("returnCode") ,validMxMap.get("returnMsg"));
            }

            cri.getHgjkshms().stream().forEach(jkshm->{
                //查询发票入账表
                TdxLqRzCustom trc = erpTDxLqRzCustomDao.selectOne(new QueryWrapper<TdxLqRzCustom>().eq("customs_code", jkshm));
                //插入批次表
                insertRzBatch(cri.getPclsh(),jkshm,"1");
                if (trc != null) {
                    if (    trc.getJksrzAuthStatus().equals("1")||
                            trc.getJksrzAuthStatus().equals("2")||
                            trc.getJksrzAuthStatus().equals("5")||
                            trc.getJksrzAuthStatus().equals("6")) {
                        //如果是入账中则不处理数据
                        return;
                    }

                    if (    cri.getRzlx().equals("02")||
                            cri.getRzlx().equals("03")||
                            cri.getRzlx().equals("04")||
                            cri.getRzlx().equals("05")) {
                        //接口申请入账处理流程

                        if (trc.getJksrzAuthStatus().equals("4")||trc.getJksrzAuthStatus().equals("7")) {
                            //如果是入账成功则不处理数据
                            return;
                        }

                        if (trc.getJksrzAuthStatus().equals("3")||trc.getJksrzAuthStatus().equals("8")) {
                            //未入账  更新入账数据
                            updateRzJks(trc,cri);
                        }
                    }

                    if (cri.getRzlx().equals("06")) {
                        //接口申请入账撤销处理流程
                        if (trc.getJksrzAuthStatus().equals("3")||trc.getJksrzAuthStatus().equals("8")) {
                            //如果是未入账则不处理数据
                            return;
                        }

                        if (trc.getJksrzAuthStatus().equals("4")||trc.getJksrzAuthStatus().equals("7")) {
                            //已入账  更新入账数据
                            updateRzJks(trc,cri);
                        }
                    }
                } else {
                    //查询抵账表
                    TdxCustomsRecord tcr = erpTdxCustomsRecordDao.selectOne(new QueryWrapper<TdxCustomsRecord>().eq("customs_code", jkshm));
                    //插入
                    TdxLqRzCustom tlrc = new TdxLqRzCustom();
                    tlrc.setGfTaxNo(cri.getNsrsbh());
                    tlrc.setCustomsCode(tcr.getCustomsCode());
                    tlrc.setFillInDate(tcr.getFillInDate());
                    tlrc.setJksrzsq(cri.getRzsq());
                    //判断入账类型是否为撤销入账 设置入账申请状态
                    tlrc.setJksrzAuthStatus(cri.getRzlx().equals("06") ? "5" : "1");
                    tlrc.setJksrzlx(cri.getRzlx());
                    tlrc.setRzr("接口入账");
                    tlrc.setCreateTime(new Date());
                    log.info("{} 保存缴款书入账表:{}",LOG_MSG,tlrc);
                    erpTDxLqRzCustomDao.insert(tlrc);
                    //更新缴款书抵账表入账状态
                    erpTdxCustomsRecordDao.update(null, new LambdaUpdateWrapper<TdxCustomsRecord>()
                            .set(TdxCustomsRecord::getRzzt, cri.getRzlx().equals("06") ? "05" : "04")
                            .eq(TdxCustomsRecord::getCustomsCode, tcr.getCustomsCode()));
                }
            });
            log.info("{} 缴款书入账处理完成",LOG_MSG);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.SUCCESS);
        } catch (Exception e) {
            log.info("{} 缴款书入账处理异常：{}",LOG_MSG,e);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.FAILED);
        }
    }

    private void updateRzJks(TdxLqRzCustom trc, CustomRzInfo cri) {
        //缴款书入账表有数据则更新
        log.info("{} 更新缴款书入账表",LOG_MSG);
        trc.setJksrzsq(cri.getRzsq());
        trc.setJksrzlx(cri.getRzlx());
        //判断入账类型是否为撤销入账 设置入账申请状态
        trc.setJksrzAuthStatus(cri.getRzlx().equals("06") ? "5" : "1");
        trc.setJksrzsbyy("");
        trc.setJksrzsj("");
        trc.setRzr("接口入账");
        trc.setUpdateTime(new Date());
        log.info("{} 更新缴款书入账表:{}",LOG_MSG,trc);
        erpTDxLqRzCustomDao.updateById(trc);

        //更新缴款书抵账表入账状态
        erpTdxCustomsRecordDao.update(null, new LambdaUpdateWrapper<TdxCustomsRecord>()
                .set(TdxCustomsRecord::getRzzt, cri.getRzlx().equals("06") ? "05" : "04")
                .eq(TdxCustomsRecord::getCustomsCode, trc.getCustomsCode()));
    }

    /**
     * 保存入账批次信息
     * @param pclsh
     * @param uuid
     */
    private void insertRzBatch(String pclsh, String uuid,String lx) {
        TdxLqRzBatch trb = new TdxLqRzBatch();
        //缴款书入账
        trb.setLx(lx);
        trb.setPclsh(pclsh);
        trb.setUuid(uuid);
        trb.setCreateTime(new Date());
        log.info("{} 保存入账批次表:{}",LOG_MSG,trb);
        erpTDxLqRzBatchDao.insert(trb);
    }

    /**
     * 缴款书入账入参校验
     * @param cri
     * @return
     */
    private Map<String,String> validJksRzMxInfo(CustomRzInfo cri) {
        log.info("{} 缴款书入账参数校验。。。",LOG_MSG);
        if (cri.getHgjkshms() == null || cri.getHgjkshms().size()==0) {
            log.info("{} 缴款书入账发票参数校验失败，发票为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_PJXX_NULL);
        }

        if (cri.getHgjkshms().size() > 100) {
            log.info("{} 缴款书入账发票最大支持100条",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_MX_TOO_LONG);
        }
        for (int i = 0;i<cri.getHgjkshms().size();i++) {
            String jkshm = cri.getHgjkshms().get(i);
            if (StringUtils.isBlank(jkshm)) {
                log.info("{} 缴款书号码不能为空",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.RZ_JKSHM_NULL,i+1);
            }

            //查询抵账表
            TdxCustomsRecord tcr = erpTdxCustomsRecordDao.selectOne(new QueryWrapper<TdxCustomsRecord>().eq("customs_code", jkshm).eq("gf_tax_no", cri.getNsrsbh()));
            if (tcr == null) {
                log.info("{} 未查询到符合条件的票据",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.NO_CONDITION_PJ,i+1);
            }

            //校验填发日期不能晚于入账属期
            if (CommonUtils.validKprqAndRzsq(tcr.getFillInDate(),cri.getRzsq())) {
                log.info("{} 入账缴款书填发日期不能晚于入账属期",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.TFRQ_ERROR,i+1);
            }

            //校验缴款书管理状态必须为正常
            if (!tcr.getGlzt().equals("0")) {
                log.info("{} 缴款书管理状态必须为正常",LOG_MSG);
                return CommonUtils.packageValidResult(GlobalReturnEnums.JKSGLZT_ERROR,i+1);
            }
        }
        return null;
    }

    /**
     * @param
     * @description 缴款书入账结果查询接口
     * @author Allen
     * @updateTime 2023/2/22 17:09
     */
    @Override
    public String jksRzCx(GlobalInfo globalInfo ,Map<String, String> requestParam) {
        log.info("{} 缴款书入账结果查询处理开始",LOG_MSG);
        try {
            //查询批次数据信息
            return processBatchData(globalInfo , requestParam,"1");
        } catch (Exception e) {
            log.info("{} 批次结果查询处理异常：{}",LOG_MSG,e);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.FAILED);
        }
    }


    /**
     * 处理批次结果数据
     * @return
     */
    private String processBatchData(GlobalInfo globalInfo ,Map<String, String> requestParam,String lx) {
        log.info("{} 批次类型：{}",LOG_MSG,lx);
        String content = requestParam.get("data");
        log.info("{} 业务报文：{}",LOG_MSG,content);
        String pclsh = JSON.parseObject(content).getString("pclsh");
        //入参校验
        if (StringUtils.isBlank(pclsh)) {
            log.info("{} 请求批次流水号为空",LOG_MSG);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.PARAM_PCLSH_NULL);
        }
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        List<TdxLqRzBatch> batchList = erpTDxLqRzBatchDao.selectList(new QueryWrapper<TdxLqRzBatch>().eq("lx", lx).eq("pclsh", pclsh));
        if (!CollectionUtils.isEmpty(batchList)) {
            log.info("{} 存在批次信息，查询申请结果",LOG_MSG);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("pclsh", pclsh);
            List<Map<String, String>> mxList = new ArrayList<>();
            if (lx.equals("0")) {
                //发票入账结果查询
                dealInvoiceRzInfo(batchList,returnMap,mxList);
            }
            if (lx.equals("1")) {
                //缴款书入账结果查询
                dealJksRzInfo(batchList,returnMap,mxList);
            }
            return CommonUtils.packageReturnMsg(globalInfo,JSON.toJSONString(returnMap), GlobalReturnEnums.SUCCESS);
        } else {
            log.info("{} 未查询到符合条件的批次信息",LOG_MSG);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.HAVE_NO_PCINFO);
        }
    }

    /**
     * 获取xml数据流
     * @param filePath
     * @return
     */
    private String getXmlSjl(String filePath) {
        String localPath = fileService.getLocalPathDefault()+ filePath.substring(filePath.lastIndexOf("/") + 1);
        File localFile = new File(localPath);
        try {
            log.info("{} 获取xml数据流开始,源文件路径：{}，临时文件路径：{}",LOG_MSG,filePath,localPath);
            fileService.downFile(filePath, localPath);
            //return Base64Encoding.encodeToString(FileUtils.readFileToByteArray(localFile));
            return Base64FileUtil.fileToBase64(localFile);
        } catch (Exception e) {
            log.info("{} 获取xml数据流异常：{}",LOG_MSG,e);
            return null;
        }finally {
            if (localFile.exists()) {
                localFile.delete();
            }
        }
    }

    /**
     * 缴款书入账批次处理
     * @param batchList
     * @param
     * @return
     */
    private void dealJksRzInfo(List<TdxLqRzBatch> batchList,Map<String, Object> returnMap, List<Map<String, String>> mxList) {
        log.info("{} 缴款书入账批次处理开始",LOG_MSG);
        batchList.stream().forEach(i->{
            TdxLqRzCustom tlrc = erpTDxLqRzCustomDao.selectOne(new QueryWrapper<TdxLqRzCustom>().eq("customs_code", i.getUuid()));
            Map<String, String> mxMap = new HashMap<>();
            mxMap.put("hgjkshm", tlrc.getCustomsCode());
            mxMap.put("tfrq", CommonUtils.kprqFormat(tlrc.getFillInDate()));
            mxMap.put("rzsq", tlrc.getJksrzsq());
            mxMap.put("rzlx", tlrc.getJksrzlx());
            String rzjg = CommonUtils.parseRzjg(tlrc.getJksrzAuthStatus());
            mxMap.put("rzjg", rzjg);
            mxMap.put("rzsj", tlrc.getJksrzsj());
            mxMap.put("rzsbyy", rzjg.equals("2")||rzjg.equals("5")?tlrc.getJksrzsbyy():"");
            TdxCustomsRecord tcr = erpTdxCustomsRecordDao.selectOne(new QueryWrapper<TdxCustomsRecord>().eq("customs_code", i.getUuid()));
            mxMap.put("rzzt", CommonUtils.parseRzzt(tcr.getRzzt()));
            mxList.add(mxMap);
        });
        returnMap.put("jksmx", mxList);
    }

    /**
     * 发票入账批次处理
     * @param batchList
     */
    private void  dealInvoiceRzInfo(List<TdxLqRzBatch> batchList,Map<String, Object> returnMap, List<Map<String, String>> mxList) {
        log.info("{} 发票入账批次处理开始",LOG_MSG);
        batchList.stream().forEach(i->{
            TdxLqRzInvoice tlri = erpTDxLqRzInvoiceDao.selectOne(new QueryWrapper<TdxLqRzInvoice>().eq("uuid", i.getUuid()));
            Map<String, String> mxMap = new HashMap<>();
            mxMap.put("fpdm", tlri.getInvoiceCode());
            mxMap.put("fphm", tlri.getInvoiceNo());
            mxMap.put("fplx", tlri.getInvoiceType());
            mxMap.put("kprq", CommonUtils.kprqFormat(tlri.getInvoiceDate()));
            mxMap.put("rzsq", tlri.getFprzsq());
            mxMap.put("rzlx", tlri.getFprzlx());
            String rzjg = CommonUtils.parseRzjg(tlri.getFprzAuthStatus());
            mxMap.put("rzjg", rzjg);
            mxMap.put("rzsj", tlri.getFprzsj());
            mxMap.put("rzsbyy", rzjg.equals("2")||rzjg.equals("5")?tlri.getFprzsbyy():"");
            TDxRecordInvoice trd = tdxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("uuid", i.getUuid()));
            mxMap.put("rzzt", CommonUtils.parseRzzt(trd.getLqRzzt()));
            mxList.add(mxMap);
        });
        returnMap.put("fpmx", mxList);
    }

    @Override
    public String sdfpXmlDownload(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request, HttpServletResponse response, Authorize authorize) {
        log.info("{} 数电发票xml文件下载结果查询开始",LOG_MSG);
        String content = requestParam.get("data");
        log.info("{} 业务报文：{}",LOG_MSG,content);
        XmlDownLoadReq xmlDownLoadReq = JSON.parseObject(content, XmlDownLoadReq.class);
        //下载xml请求参数校验
        Map<String,String> validMxMap = validXmlDownloadReq(xmlDownLoadReq);
        if (validMxMap != null) {
            log.info("{} 下载xml请求参数校验失败：{}",LOG_MSG,validMxMap);
            return CommonUtils.packageReturnMsg(globalInfo,null, validMxMap.get("returnCode") ,validMxMap.get("returnMsg"));
        }
        String fpzldm = xmlDownLoadReq.getFpzldm();
        String fpdm = xmlDownLoadReq.getFpdm();
        String fphm = xmlDownLoadReq.getFphm();
        String fileType = xmlDownLoadReq.getFileType();

        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        //抵账库查询，无数据则返回
        TDxRecordInvoice tdxRecordInvoice = tdxRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TDxRecordInvoice>()
                .eq(TDxRecordInvoice::getInvoiceType, fpzldm)
                .eq(TDxRecordInvoice::getInvoiceCode, fpdm)
                .eq(TDxRecordInvoice::getInvoiceNo, fphm)
        );
        if(ObjectUtil.isEmpty(tdxRecordInvoice)){
            log.info("{} 底账中无此发票信息",LOG_MSG);
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.ELEINVOICE_XML_RECORD_NULL);
        }

        Map<String,Object> returnMap = new HashMap();
        returnMap.put("fpdm",fpdm);
        returnMap.put("fphm",fphm);

        //xml下载表，有数据则代表已下载回来
        TDxInvoiceFileEntity tDxInvoiceFile = erpTdxInvoiceFileDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>()
                .eq(TDxInvoiceFileEntity::getUuid, fpdm+fphm)
        );
        if(ObjectUtil.isEmpty(tDxInvoiceFile)){
            returnMap.put("xzjg","0");
        }else{
            String xmlSjl = "";
            boolean haveFile = false;
            //判断是否存在
            if("1".equals(fileType)){
                if(StringUtils.isNotBlank(tDxInvoiceFile.getXmlPath())){
                    xmlSjl = tDxInvoiceFile.getXmlPath();
                    haveFile = true;
                }else{
                    returnMap.put("xzjg","0");
                }
            }else if("2".equals(fileType)){
                if(StringUtils.isNotBlank(tDxInvoiceFile.getPdfPath())){
                    xmlSjl = tDxInvoiceFile.getPdfPath();
                    haveFile = true;
                }else{
                    returnMap.put("xzjg","0");
                }
            }else if("3".equals(fileType)){
                if(StringUtils.isNotBlank(tDxInvoiceFile.getOfdPath())){
                    xmlSjl = tDxInvoiceFile.getOfdPath();
                    haveFile = true;
                }else{
                    returnMap.put("xzjg","0");
                }
            }else{
                log.info("没有此fileType:{}",fileType);
                returnMap.put("xzjg","0");
            }

            if(haveFile){
                returnMap.put("xzjg","1");
                returnMap.put("sjl",getXmlSjl(xmlSjl));
            }
        }
        return CommonUtils.packageReturnMsg(globalInfo,JSON.toJSONString(returnMap), GlobalReturnEnums.SUCCESS);

    }

    private Map<String, String> validXmlDownloadReq(XmlDownLoadReq xmlDownLoadReq) {
//        String gmfsbh = xmlDownLoadReq.getGmfsbh();
//        if(StringUtils.isEmpty(gmfsbh)){
//            log.info("{} 购方税号为空",LOG_MSG);
//            return CommonUtils.packageValidResult(GlobalReturnEnums.ELEINVOICE_XML_GMFSBH_NULL);
//        }
        String fpzldm = xmlDownLoadReq.getFpzldm();
        if(StringUtils.isEmpty(fpzldm)){
            log.info("{} 发票种类代码为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.ELEINVOICE_XML_FPZLDM_NULL);
        }else if(!FplxEnum.QDZZP.getFplxDm().equals(fpzldm)
                &&!FplxEnum.QDPP.getFplxDm().equals(fpzldm)
                &&!FplxEnum.HKDZFP.getFplxDm().equals(fpzldm)
                &&!FplxEnum.TLKP.getFplxDm().equals(fpzldm)){
            log.info("{} 发票种类代码只支持31、32、161、283",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_FPZLDM_ERR);
        }
        String fpdm = xmlDownLoadReq.getFpdm();
        if(StringUtils.isEmpty(fpdm)){
            log.info("{} 发票代码为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.ELEINVOICE_XML_FPDM_NULL);
        }
        String fphm = xmlDownLoadReq.getFphm();
        if(StringUtils.isEmpty(fphm)){
            log.info("{} 发票号码为空",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_FPHM_NULL);
        }

        if(fpdm.length()==10||fpdm.length()==12){

        }else{
            log.info("{} 发票代码长度需为10或12位",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_FPDM_LENGTHERR);
        }
        if(fphm.length()==8||fphm.length()==10){

        }else{
            log.info("{} 发票号码长度需为8或10位",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_FPHM_LENGTHERR);
        }

        String fileType = xmlDownLoadReq.getFileType();
        if(StringUtils.isEmpty(fileType)){
            log.info("{} 下载文件类型为空",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_DOWNLOAD_TYPENULL);
        }
        if(!Arrays.asList("123".split("")).contains(fileType)){
            log.info("{} 下载文件类型不正确",LOG_MSG);
            return CommonUtils.packageValidResult( GlobalReturnEnums.ELEINVOICE_XML_DOWNLOAD_TYPEERR);
        }
        return null;
    }
}
