
package com.dxhy.domestic.service.ckzrz.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.RzztEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.domestic.dao.DomesticExportInvoiceDao;
import com.dxhy.api.model.db.TDxDkCountEntity;
import com.dxhy.api.model.invoice.TDxExportInvoice;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.common.utils.ResultData;
import com.dxhy.domestic.model.dto.TdxExportInvoiceModelDTO;
import com.dxhy.domestic.service.ckzrz.DomesticDkCountService;
import com.dxhy.domestic.service.ckzrz.DomesticExportInvoiceCkService;
import com.dxhy.domestic.service.ckzrz.DomesticTaxCurrentService;
import com.dxhy.domestic.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业务单元
 *
 * @author dxhy
 */
@SuppressWarnings("AlibabaMethodTooLong")
@Service
public class DomesticExportInvoiceCkServiceImpl extends ServiceImpl<DomesticExportInvoiceDao, TDxExportInvoice>
    implements DomesticExportInvoiceCkService {

    @Resource
    private DomesticTaxCurrentService domesticTaxCurrentService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DomesticDkCountService domesticDkCountService;
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public String queryVatSgrz(Page page, TdxExportInvoiceModelDTO dto, UserInfo userInfo) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        dto.setParam(page, userInfo);

        //处理号码
        if(StringUtils.isNotBlank(dto.getInvoiceNo())){
            if(dto.getInvoiceNo().length()==8){

            }else {
                dto.setEleInvoiceNo(dto.getInvoiceNo());
                dto.setInvoiceNo("");
            }
        }

        ResultData<Object> resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(dto.getCompany(), dto.getMenuId());
        resultData.putTabulateMenu(tabulateMenu);

        if (StringUtils.isBlank(dto.getGfsh()) && dto.getGfTaxNo().size() <= 0) {
            resultData.setDataList(new ArrayList<>());
            return resultData.toJsonBase();
        }

        Map<String, Object> mapTj = null;

        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (dto.getCurr() == 1) {
            mapTj = this.baseMapper.queryVatSgrzSum(dto);
        }

        Page<Map<String, Object>> result = this.baseMapper.queryVatSgrz(page, dto);

        if (ResultData.isEmpty(result)) {
            // List<DictdetaModel> fpztModels = dictdetaServcice.selectDictdeta("INVOICE_STATUS");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);

                String invoiceStatus = (String)map.get("invoiceStatus");

                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if (map.get("invoiceDate") != null) {
                    map.put("invoiceDate", map.get("invoiceDate"));
                }
                map.put("invoiceStatus", dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceStatus));

                if(ObjectUtil.isNotEmpty(map.get("exportAmount"))){
                    map.put("exportAmount", AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(((BigDecimal)map.get("exportAmount")).toPlainString())));
                }
                if(ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("exportTaxAmount", AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(((BigDecimal)map.get("exportTaxAmount")).toPlainString())));
                }
                if(ObjectUtil.isNotEmpty(map.get("exportYxse"))){
                    map.put("exportYxse", MathUtil.round(((BigDecimal)map.get("exportYxse")).toPlainString()));
                }

                map.put("select", true);
                map.put("upgradeStatus", "1");

                TDxDkCountEntity tDxDkCountEntity;
                TDxTaxCurrentEntity tDxTaxCurrentEntity;
                List<TDxTaxCurrentEntity> TDxTaxCurrentEntities = domesticTaxCurrentService
                    .list(Wrappers.<TDxTaxCurrentEntity>query().lambda().eq(TDxTaxCurrentEntity::getTaxno, map.get("gfTaxNo")));

                if (TDxTaxCurrentEntities == null || TDxTaxCurrentEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }
                tDxTaxCurrentEntity = TDxTaxCurrentEntities.get(0);
                List<TDxDkCountEntity> TDxDkCountEntities = domesticDkCountService
                    .list(Wrappers.<TDxDkCountEntity>query().lambda().eq(TDxDkCountEntity::getTaxno, map.get("gfTaxNo"))
                        .eq(TDxDkCountEntity::getSkssq, tDxTaxCurrentEntity.getCurrentTaxPeriod()));

                if (TDxDkCountEntities == null || TDxDkCountEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }

                tDxDkCountEntity = TDxDkCountEntities.get(0);

                if (!DateUtil.isInTwoDate(tDxTaxCurrentEntity.getSelectStartDate(), tDxTaxCurrentEntity.getSelectEndDate(),
                    (String)map.get("invoiceDate"))) {
                    map.put("select", false);
                    continue;
                }

                if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                    map.put("select", false);
                    continue;
                }

                if (!"0".equals(invoiceStatus)) {
                    map.put("select", false);
                }

            }

        }
        return resultData.getTjData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String approveSg(TdxExportInvoiceModelDTO dto, UserInfo userInfo) {

        Map<String, Object> resultMap = new HashMap<>(16);

        //认证不抵扣，判断不抵扣类型和原因
        if(StringUtils.isNotBlank(dto.getRzlx())&&"2".equals(dto.getRzlx())){
            if(!Arrays.asList("1,2,3,4,5".split(",")).contains(dto.getBdkMessage())){
                resultMap.put("message", "不抵扣类型不正确");
                return Base64.encode(JSONObject.toJSONString(resultMap));
            }
            if("5".equals(dto.getBdkMessage())&& StringUtils.isEmpty(dto.getBdkYy())){
                resultMap.put("message", "不抵扣原因是其他时，需填写原因");
                return Base64.encode(JSONObject.toJSONString(resultMap));
            }
        }

        long total = 0;
        BigDecimal hjje = new BigDecimal(0);
        BigDecimal hjse = new BigDecimal(0);
        BigDecimal hjyxse = new BigDecimal(0);
        String message = "";

        boolean flag = false;
        boolean flag1 = false;
        boolean flag2 = false;
        boolean flag3 = false;

        List<String> sb1List = new ArrayList<>();
        List<String> sb2List = new ArrayList<>();
        List<String> sb3List = new ArrayList<>();

        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        StringBuilder sb3 = new StringBuilder();

        sb.append("以下发票号码的抵扣税额小于等于0或大于税额不可勾选认证： 发票号码\n ");
        sb1.append("以下税号已被锁定不可勾选认证： 税号\n");
        sb2.append("以下税号已申请抵扣统计，请撤销统计后重新操作：税号  \n ");
        sb3.append("以下税号本月发票可认证总税额超限：税号\n");

        // 1.查询数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        List<TDxExportInvoice> records = new ArrayList<>();
        // 2.校验
        List<String> dkList = new ArrayList<>();
        // 抵扣限额合计
        BigDecimal dkTaxAmount = new BigDecimal(0);
        List<InvoiceLog> logList = new ArrayList<>();
        for (String idstr : dto.getIds()) {

            if (idstr == null) {
                continue;
            }

            String[] arr = idstr.split(":");
            Long id = Long.parseLong(arr[0]);
            // 有效税额
            String yxTaxAmount = arr[1];
            if (yxTaxAmount != null) {
                yxTaxAmount = yxTaxAmount.replaceAll(",", "");
                //如果是代扣代缴，金额可能为空，空的话传的是 --
                if("--".equals(yxTaxAmount)){
                    yxTaxAmount = "";
                }
            }

            TDxExportInvoice record = this.baseMapper.selectById(id);
            if (record != null) {

                TDxTaxCurrentEntity tDxTaxCurrentEntity;
                TDxDkCountEntity tDxDkCountEntity;
                List<TDxTaxCurrentEntity> TDxTaxCurrentEntities = domesticTaxCurrentService
                    .list(Wrappers.<TDxTaxCurrentEntity>query().lambda().eq(TDxTaxCurrentEntity::getTaxno, record.getGfTaxNo()));

                tDxTaxCurrentEntity = TDxTaxCurrentEntities.get(0);

                List<TDxDkCountEntity> TDxDkCountEntities = domesticDkCountService
                    .list(Wrappers.<TDxDkCountEntity>query().lambda().eq(TDxDkCountEntity::getTaxno, record.getGfTaxNo())
                        .eq(TDxDkCountEntity::getSkssq, tDxTaxCurrentEntity.getCurrentTaxPeriod()));

                tDxDkCountEntity = TDxDkCountEntities.get(0);
                InvoiceLog invoiceLog = new InvoiceLog();
                // 认证抵扣
                if ("1".equals(dto.getRzlx())) {
                    //如果是代扣代缴，不验证以下信息
                    if(!"4".equals(record.getXxly())){
                        if (Double.parseDouble(yxTaxAmount) <= 0
                                || Double.parseDouble(yxTaxAmount) > new BigDecimal(record.getExportTaxAmount()).doubleValue()) {
                            sb.append(record.getInvoiceNo()).append(" \n ");
                            flag = true;
                            continue;
                        }
                        // 判断抵扣限额
                        if (tDxTaxCurrentEntity.getLimitDkse() != null
                                && tDxTaxCurrentEntity.getLimitDkse().compareTo(BigDecimal.ZERO) != 0) {
                            if (!dkList.contains(record.getGfTaxNo())) {

                                Map<String, Object> paramMap = new HashMap<>(16);
                                paramMap.put("gfsh", record.getGfTaxNo());
                                paramMap.put("skssq", tDxTaxCurrentEntity.getCurrentTaxPeriod());
                                TDxExportInvoice dkInvoice = super.baseMapper.selectDkse(paramMap);

                                if (dkInvoice != null && dkInvoice.getExportYxse() != null) {
                                    dkTaxAmount = dkTaxAmount.add(new BigDecimal(dkInvoice.getExportYxse()));
                                }

                                dkTaxAmount = dkTaxAmount.add(BigDecimal.valueOf(Double.parseDouble(yxTaxAmount)));
                                if (dkTaxAmount.compareTo(tDxTaxCurrentEntity.getLimitDkse()) > 0) {
                                    dkList.add(record.getGfTaxNo());

                                    if (!sb3List.contains(record.getGfTaxNo())) {
                                        sb3.append(record.getGfTaxNo()).append(" \n ");
                                        sb3List.add(record.getGfTaxNo());
                                    }
                                    flag3 = true;
                                    continue;
                                }

                            }
                        }
                    }


                    if ("1".equals(tDxTaxCurrentEntity.getLatchStatus())) {
                        if (!sb1List.contains(record.getGfTaxNo())) {
                            sb1.append(record.getGfTaxNo()).append(" \n ");
                            sb1List.add(record.getGfTaxNo());
                        }
                        flag1 = true;
                        continue;
                    }

                    if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                        if (!sb2List.contains(record.getGfTaxNo())) {
                            sb2.append(record.getGfTaxNo()).append(" \n ");
                            sb2List.add(record.getGfTaxNo());
                        }
                        flag2 = true;
                        continue;
                    }

                    record.setRzlx("1");
                    record.setBdkStatus("1");
                    record.setRzhBelongDate(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setAuthStatus("2");
                    record.setConfirmDate(new Date());
                    record.setConfirmUser(userInfo.getUsername());
                    if(StringUtils.isNotBlank(yxTaxAmount)){
                        record.setExportYxse(yxTaxAmount);
                    }
                    record.setCxrzStatus("0");
                    record.setCxrzDate(new Date());
                    records.add(record);
                    invoiceLog.setInvoiceCode(record.getInvoiceCode());
                    invoiceLog.setInvoiceNo(record.getInvoiceNo());
                    invoiceLog.setType("8");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputName(userInfo.getLoginname());
                    invoiceLog.setInputStatus("14");
                    logList.add(invoiceLog);
                } else if ("2".equals(dto.getRzlx())) {
                    // 认证不抵扣
                    if ("1".equals(tDxTaxCurrentEntity.getLatchStatus())) {
                        if (!sb1List.contains(record.getGfTaxNo())) {
                            sb1.append(record.getGfTaxNo()).append(" \n ");
                            sb1List.add(record.getGfTaxNo());
                        }
                        flag1 = true;
                        continue;
                    }

                    if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                        if (!sb2List.contains(record.getGfTaxNo())) {
                            sb2.append(record.getGfTaxNo()).append(" \n ");
                            sb2List.add(record.getGfTaxNo());
                        }
                        flag2 = true;
                        continue;
                    }

                    record.setRzlx("4");
                    record.setBdkStatus("2");
                    record.setRzhBelongDate(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setAuthStatus("2");
                    record.setConfirmDate(new Date());
                    record.setConfirmUser(userInfo.getUsername());
                    record.setExportYxse(record.getExportTaxAmount());
                    record.setBdkMessage(dto.getBdkMessage());
                    record.setBdkYy(dto.getBdkYy());
                    record.setCxbdkStatus("0");
                    record.setCxbdkDate(new Date());
                    records.add(record);
                    invoiceLog.setInvoiceCode(record.getInvoiceCode());
                    invoiceLog.setInvoiceNo(record.getInvoiceNo());
                    invoiceLog.setType("9");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputName(userInfo.getLoginname());
                    invoiceLog.setInputStatus("10");
                    logList.add(invoiceLog);
                }
            }
        }
        // 3.更新数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_WRITE);
        if (!flag && !flag1 && !flag2 && !flag3) {
            for (TDxExportInvoice record : records) {

                total++;
                if(ObjectUtil.isNotEmpty(record.getExportAmount())){
                    hjje = hjje.add(new BigDecimal(record.getExportAmount()));
                }
                if(ObjectUtil.isNotEmpty(record.getExportTaxAmount())){
                    hjse = hjse.add(new BigDecimal(record.getExportTaxAmount()));
                }
                if(ObjectUtil.isNotEmpty(record.getExportYxse())){
                    hjyxse = hjyxse.add(new BigDecimal(record.getExportYxse()));
                }
                record.setUpdateDate(new Date());
                this.baseMapper.updateById(record);
            }
        }
        if (flag) {
            message = sb.toString();
        }
        if (flag1) {
            message = message + sb1.toString() + "如需勾选认证，请到企业税务信息菜单解除锁定";
        }
        if (flag2) {
            message = message + sb2.toString();
        }
        if (flag3) {
            message = message + sb3.toString();
        }
        resultMap.put("total", AmountFormatUtil.fmtMicrometer(String.valueOf(total)));
        resultMap.put("hjje",
            AmountFormatUtil.fmtMicrometer(hjje.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        resultMap.put("hjse",
            AmountFormatUtil.fmtMicrometer(hjse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        resultMap.put("hjyxse",
            AmountFormatUtil.fmtMicrometer(hjyxse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        resultMap.put("message", message);
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        return Base64.encode(JSONObject.toJSONString(resultMap));
    }

    @Override
    public String queryVatBdk(Page page, TdxExportInvoiceModelDTO dto, UserInfo userInfo) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        dto.setParam(page, userInfo);

        //处理号码
        if(StringUtils.isNotBlank(dto.getInvoiceNo())){
            if(dto.getInvoiceNo().length()==8){

            }else {
                dto.setEleInvoiceNo(dto.getInvoiceNo());
                dto.setInvoiceNo("");
            }
        }

        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(dto.getCompany(), dto.getMenuId());

        ResultData<Object> resultData = new ResultData<>();
        resultData.putTabulateMenu(tabulateMenu);

        if (StringUtils.isBlank(dto.getGfsh()) && dto.getGfTaxNo().size() <= 0) {
            resultData.setDataList(new ArrayList<>());
            return resultData.toJsonBase();
        }

        Map<String, Object> mapTj = null;

        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (dto.getCurr() == 1) {
            mapTj = this.baseMapper.queryVatBdkSum(dto);
        }

        Page<Map> result = this.baseMapper.queryVatBdk(page, dto);

        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);

                String authStatus = (String)map.get("authStatus");
                String cxbdkStatus = (String)map.get("cxbdkStatus");
                String invoiceStatus = (String)map.get("invoiceStatus");
                String bdkStatus = (String)map.get("bdkStatus");
                String bdkMessage = (String)map.get("bdkMessage");

                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if (map.get("invoiceDate") != null) {
                    map.put("invoiceDate", map.get("invoiceDate"));
                }
                // 字典转换
                map.put("invoiceStatus", dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceStatus));
                map.put("authStatus", dictdetaServcice.queryDictName(DictConstant.BDK_AUTH_STATUS, authStatus));
                map.put("cxbdkStatus", dictdetaServcice.queryDictName(DictConstant.BDK_UNDO_STATUS, cxbdkStatus));
                map.put("bdkMessage", dictdetaServcice.queryDictName(DictConstant.bdkMessage, bdkMessage));

                if(ObjectUtil.isNotEmpty(map.get("exportAmount"))){
                    map.put("exportAmount", AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(((BigDecimal)map.get("exportAmount")).toPlainString())));
                }
                if(ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("exportTaxAmount", AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(((BigDecimal)map.get("exportTaxAmount")).toPlainString())));
                }

                if(ObjectUtil.isNotEmpty(map.get("exportYxse"))){
                    map.put("exportYxse", AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(((BigDecimal)map.get("exportYxse")).toPlainString())));
                }

                map.put("select", true);

                TDxDkCountEntity tDxDkCountEntity;
                TDxTaxCurrentEntity tDxTaxCurrentEntity;
                List<TDxTaxCurrentEntity> TDxTaxCurrentEntities = domesticTaxCurrentService
                    .list(Wrappers.<TDxTaxCurrentEntity>query().lambda().eq(TDxTaxCurrentEntity::getTaxno, map.get("gfTaxNo")));

                if (TDxTaxCurrentEntities == null || TDxTaxCurrentEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }
                tDxTaxCurrentEntity = TDxTaxCurrentEntities.get(0);
                List<TDxDkCountEntity> TDxDkCountEntities = domesticDkCountService
                    .list(Wrappers.<TDxDkCountEntity>query().lambda().eq(TDxDkCountEntity::getTaxno, map.get("gfTaxNo"))
                        .eq(TDxDkCountEntity::getSkssq, tDxTaxCurrentEntity.getCurrentTaxPeriod()));

                if (TDxDkCountEntities == null || TDxDkCountEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }

                tDxDkCountEntity = TDxDkCountEntities.get(0);

                // 认证不抵扣
                if ("0".equals(dto.getSfDkStatus())) {
                    if (!"0".equals(authStatus) && !"4".equals(authStatus) && !"5".equals(authStatus)
                        && !"6".equals(authStatus)) {
                        map.put("select", false);
                        continue;
                    }
                } else if ("4".equals(dto.getSfDkStatus())) {
                    // 页面中有撤销不抵扣按钮
                    if (!"0".equals(cxbdkStatus) && !"4".equals(cxbdkStatus) && !"5".equals(cxbdkStatus)) {
                        map.put("select", false);
                        continue;
                    }
                    if (!"2".equals(bdkStatus)) {
                        map.put("select", false);
                        continue;
                    }
                }

                String invoiceDate = (String)map.get("invoiceDate");
                if (!DateUtil.isInTwoDate(tDxTaxCurrentEntity.getSelectStartDate(), tDxTaxCurrentEntity.getSelectEndDate(),
                    invoiceDate)) {
                    map.put("select", false);
                    continue;
                }

                if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                    map.put("select", false);
                    continue;
                }

                if (!"0".equals(invoiceStatus)) {
                    map.put("select", false);
                }

            }

        }
        return resultData.getTjData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String queryVatRzcx(Page page, TdxExportInvoiceModelDTO dto, UserInfo userInfo) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        dto.setParam(page, userInfo);

        //处理号码
        if(StringUtils.isNotBlank(dto.getInvoiceNo())){
            if(dto.getInvoiceNo().length()==8){

            }else {
                dto.setEleInvoiceNo(dto.getInvoiceNo());
                dto.setInvoiceNo("");
            }
        }

        ResultData<Object> resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(dto.getCompany(), dto.getMenuId());
        resultData.putTabulateMenu(tabulateMenu);

        if (StringUtils.isBlank(dto.getGfsh()) && dto.getGfTaxNo().size() <= 0) {
            resultData.setDataList(new ArrayList<>());
            return resultData.toJsonBase();
        }

        Map<String, Object> mapTj = null;

        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (dto.getCurr() == 1) {
            mapTj = this.baseMapper.queryVatRzcxSum(dto);
        }

        Page<Map<String, Object>> result = this.baseMapper.queryVatRzcx(page, dto);

        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);

                String bdkStatus = (String)map.get("bdkStatus");
                String cxrzStatus = (String)map.get("cxrzStatus");
                String rzhYesorno = (String)map.get("rzhYesorno");
                String invoiceStatus = (String)map.get("invoiceStatus");
                String authStatus = (String)map.get("authStatus");

                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if (map.get("invoiceDate") != null) {
                    map.put("invoiceDate", map.get("invoiceDate"));
                }
                if (map.get("rzhDate") != null) {
                    map.put("rzhDate", map.get("rzhDate"));
                }

                // 字典值转换
                map.put("invoiceStatus", dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceStatus));
                map.put("rzhYesorno", dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));
                map.put("authStatus", dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
                map.put("bdkStatus", dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                map.put("cxrzStatus", dictdetaServcice.queryDictName(DictConstant.CXRZ_STATUS, cxrzStatus));

                map.put("bdkStatusBak", bdkStatus);

                map.put("exportAmount", CommonUtil.jecl(map.get("exportAmount")));
                map.put("exportTaxAmount", CommonUtil.jecl(map.get("exportTaxAmount")));
                map.put("exportYxse", CommonUtil.jecl(map.get("exportYxse")));
                map.put("select", true);

                TDxDkCountEntity tDxDkCountEntity;
                TDxTaxCurrentEntity tDxTaxCurrentEntity;
                List<TDxTaxCurrentEntity> TDxTaxCurrentEntities = domesticTaxCurrentService
                    .list(Wrappers.<TDxTaxCurrentEntity>query().lambda().eq(TDxTaxCurrentEntity::getTaxno, map.get("gfTaxNo")));

                if (TDxTaxCurrentEntities == null || TDxTaxCurrentEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }
                tDxTaxCurrentEntity = TDxTaxCurrentEntities.get(0);
                List<TDxDkCountEntity> TDxDkCountEntities = domesticDkCountService
                    .list(Wrappers.<TDxDkCountEntity>query().lambda().eq(TDxDkCountEntity::getTaxno, map.get("gfTaxNo"))
                        .eq(TDxDkCountEntity::getSkssq, tDxTaxCurrentEntity.getCurrentTaxPeriod()));
                if (TDxDkCountEntities == null || TDxDkCountEntities.size() == 0) {
                    map.put("select", false);
                    continue;
                }
                tDxDkCountEntity = TDxDkCountEntities.get(0);
                if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                    map.put("select", false);
                    continue;
                }

                if (!"1".equals(bdkStatus)) {
                    map.put("select", false);
                    continue;
                }
                if (!"1".equals(rzhYesorno)) {
                    map.put("select", false);
                    continue;
                }
                if (!map.get("rzhBelongDate").equals(tDxTaxCurrentEntity.getCurrentTaxPeriod())) {
                    map.put("select", false);
                    continue;
                }
                if (!"0".equals(cxrzStatus) && !"5".equals(cxrzStatus)) {
                    map.put("select", false);
                }
            }

        }
        return resultData.getTjData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String approveCxrz(TdxExportInvoiceModelDTO dto, UserInfo userInfo) throws Exception {

        Map<String, Object> resultMap = new HashMap<>(16);

        long total = 0;
        BigDecimal hjje = new BigDecimal(0);
        BigDecimal hjse = new BigDecimal(0);
        BigDecimal hjyxse = new BigDecimal(0);
        String message = "";

        boolean flag1 = false;
        boolean flag2 = false;
        boolean flag3 = false;

        List<String> sb1List = new ArrayList<>();
        List<String> sb2List = new ArrayList<>();

        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        StringBuilder sb3 = new StringBuilder();

        sb1.append("以下税号已被锁定不可勾选认证： 税号\n");
        sb2.append("以下税号已申请抵扣统计，请撤销统计后重新操作：税号  \n ");
        sb3.append("以下发票的税款所属期不是当前属期：发票\n ");

        // 1.查询数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        List<TDxExportInvoice> records = new ArrayList<>();
        List<InvoiceLog> logList = new ArrayList<>();
        // 2.校验
        for (String idstr : dto.getIds()) {

            Long id = Long.parseLong(idstr);

            TDxExportInvoice record = this.baseMapper.selectById(id);
            if (record != null) {

                TDxTaxCurrentEntity tDxTaxCurrentEntity;
                TDxDkCountEntity tDxDkCountEntity;
                List<TDxTaxCurrentEntity> TDxTaxCurrentEntities = domesticTaxCurrentService
                    .list(Wrappers.<TDxTaxCurrentEntity>query().lambda().eq(TDxTaxCurrentEntity::getTaxno, record.getGfTaxNo()));

                tDxTaxCurrentEntity = TDxTaxCurrentEntities.get(0);

                List<TDxDkCountEntity> TDxDkCountEntities = domesticDkCountService
                    .list(Wrappers.<TDxDkCountEntity>query().lambda().eq(TDxDkCountEntity::getTaxno, record.getGfTaxNo())
                        .eq(TDxDkCountEntity::getSkssq, tDxTaxCurrentEntity.getCurrentTaxPeriod()));

                tDxDkCountEntity = TDxDkCountEntities.get(0);

                if ("1".equals(tDxTaxCurrentEntity.getLatchStatus())) {
                    if (!sb1List.contains(record.getGfTaxNo())) {
                        sb1.append(record.getGfTaxNo()).append(" \n ");
                        sb1List.add(record.getGfTaxNo());
                    }
                    flag1 = true;
                    continue;
                }

                if (!"0".equals(tDxDkCountEntity.getTjStatus()) && !"3".equals(tDxDkCountEntity.getTjStatus())) {
                    if (!sb2List.contains(record.getGfTaxNo())) {
                        sb2.append(record.getGfTaxNo()).append(" \n ");
                        sb2List.add(record.getGfTaxNo());
                    }
                    flag2 = true;
                    continue;
                }

                if (!record.getRzhBelongDate().equals(tDxTaxCurrentEntity.getCurrentTaxPeriod())) {
                    sb3.append(record.getInvoiceNo()).append(" \n ");
                    flag3 = true;
                    continue;
                }
                InvoiceLog invoiceLog = new InvoiceLog();
                // 撤销抵扣
                if ("1".equals(record.getBdkStatus())) {
                    record.setRzlx("5");
                    record.setCxrzCurrentPeriod(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setCxrzStatus("1");
                    record.setCxrzDate(new Date());
                    records.add(record);
                    invoiceLog.setInvoiceCode(record.getInvoiceCode());
                    invoiceLog.setInvoiceNo(record.getInvoiceNo());
                    invoiceLog.setType("8");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputName(userInfo.getLoginname());
                    invoiceLog.setInputStatus("15");
                    logList.add(invoiceLog);
                } else if ("2".equals(record.getBdkStatus())) {
                    // 撤销不抵扣
                    record.setRzlx("6");
                    record.setBdkCurrentPeriod(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setCxbdkStatus("1");
                    record.setCxbdkDate(new Date());
                    records.add(record);
                    invoiceLog.setInvoiceCode(record.getInvoiceCode());
                    invoiceLog.setInvoiceNo(record.getInvoiceNo());
                    invoiceLog.setType("9");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputName(userInfo.getLoginname());
                    invoiceLog.setInputStatus("10");
                    logList.add(invoiceLog);
                }
            }
        }
        // 3.更新数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_WRITE);
        for (TDxExportInvoice record : records) {
            total++;
            if(ObjectUtil.isNotEmpty(record.getExportAmount())){
                hjje = hjje.add(new BigDecimal(record.getExportAmount()));
            }
            if(ObjectUtil.isNotEmpty(record.getExportTaxAmount())){
                hjse = hjse.add(new BigDecimal(record.getExportTaxAmount()));
            }
            if(ObjectUtil.isNotEmpty(record.getExportYxse())){
                hjyxse = hjyxse.add(new BigDecimal(record.getExportYxse()));
            }

            record.setUpdateDate(new Date());
            this.baseMapper.updateById(record);
        }
        if (flag1) {
            message = message + sb1.toString() + "如需勾选认证，请到企业税务信息菜单解除锁定";
        }
        if (flag2) {
            message = message + sb2.toString();
        }
        if (flag3) {
            message = message + sb3.toString();
        }
        resultMap.put("total", AmountFormatUtil.fmtMicrometer(String.valueOf(total)));
        resultMap.put("hjse",
            AmountFormatUtil.fmtMicrometer(hjse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        resultMap.put("message", message);
        resultMap.put("hjje",
            AmountFormatUtil.fmtMicrometer(hjje.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        resultMap.put("hjdk",
            AmountFormatUtil.fmtMicrometer(hjyxse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        return Base64.encode(JSONObject.toJSONString(resultMap));
    }

    private String getRzzt(String rzhYesorno) {
        String rzzt = "";
        if (RzztEnum.WRZ.getRzztDm().equals(rzhYesorno)) {
            rzzt = RzztEnum.WRZ.getRzztMc(RzztEnum.WRZ.getIndex());
        } else if (RzztEnum.YRZ.getRzztDm().equals(rzhYesorno)) {
            rzzt = RzztEnum.YRZ.getRzztMc(RzztEnum.YRZ.getIndex());
        } else if (RzztEnum.YRZBDK.getRzztDm().equals(rzhYesorno)) {
            rzzt = RzztEnum.YRZBDK.getRzztMc(RzztEnum.YRZBDK.getIndex());
        } else if (RzztEnum.TSRZ.getRzztDm().equals(rzhYesorno)) {
            rzzt = RzztEnum.TSRZ.getRzztMc(RzztEnum.TSRZ.getIndex());
        }
        return rzzt;
    }
}
