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

import cn.hutool.core.codec.Base64;
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.service.CustomsLogService;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.domestic.dao.DomesticExportCustomsDao;
import com.dxhy.api.model.db.TDxDkCountEntity;
import com.dxhy.api.model.custom.TDxExportCustoms;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.common.utils.ResultData;
import com.dxhy.domestic.model.dto.TdxExportCustomsModelDTO;
import com.dxhy.domestic.service.ckzrz.DomesticDkCountService;
import com.dxhy.domestic.service.ckzrz.DomesticExportCustomsCkService;
import com.dxhy.domestic.service.ckzrz.DomesticTaxCurrentService;
import com.dxhy.domestic.util.DateUtil;
import com.dxhy.domestic.util.ObjectUtil;
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 DomesticExportCustomsCkServiceImpl extends ServiceImpl<DomesticExportCustomsDao, TDxExportCustoms>
    implements DomesticExportCustomsCkService {

    @Resource
    private DomesticTaxCurrentService domesticTaxCurrentService;

    @Resource
    private DomesticDkCountService domesticDkCountService;

    @Resource
    private CustomsLogService logService;

    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

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

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

        Map<String, Object> mapTj = null;

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

        Page<Map<String, Object>> result = this.baseMapper.querySgByPage(page, dto);
        if (ResultData.isEmpty(result)) {
            // List<DictdetaModel> lyModels = dictdetaServcice.selectDictdeta("jksSources");
            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 dataSources = (String)map.get("dataSources");

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

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("exportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("exportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }
                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("yxExportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("yxExportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).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);
                String fillInDate = (String)map.get("fillInDate");
                if (!DateUtil.isInTwoDate(tDxTaxCurrentEntity.getSelectStartDate(), tDxTaxCurrentEntity.getSelectEndDate(),
                    fillInDate)) {
                    map.put("select", false);
                    continue;
                }

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

                String applyCheck = (String)map.get("applyCheck");
                String checkStatus = (String)map.get("checkStatus");
                // 采集数据
                if ("0".equals(dataSources)) {
                    if (!"0".equals(map.get("glzt"))) {
                        map.put("select", false);
                    }
                } else {// 录入数据
                    if ("0".equals(applyCheck) && "1".equals(checkStatus)) {
                        log.debug("");
                    } else if ("1".equals(applyCheck) && "0".equals(checkStatus)) {
                        log.debug("");
                    } else {
                        map.put("select", false);
                    }
                }

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

    @Override
    public String approveSg(TdxExportCustomsModelDTO 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<TDxExportCustoms> records = new ArrayList<>();
        // 2.校验
        List<String> dkList = new ArrayList<>();
        // 抵扣限额合计
        BigDecimal dkTaxAmount = new BigDecimal(0);
        List<CustomsLog> 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 = "";
                }
            }

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

                TDxTaxCurrentEntity tDxTaxCurrentEntity = null;
                TDxDkCountEntity tDxDkCountEntity = null;
                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(dto.getRzlx())) {
                    //如果是代扣代缴，不验证以下信息
                    if(!"4".equals(record.getXxly())){
                        if (Double.parseDouble(yxTaxAmount) <= 0
                                || Double.parseDouble(yxTaxAmount) > Double.parseDouble(record.getExportTaxAmount())) {
                            sb.append(record.getCustomsCode()).append(" \n ");
                            flag = 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;
                    }

                    // 判断抵扣限额
                    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());
                            TDxExportCustoms dkInvoice = super.baseMapper.selectDkse(paramMap);

                            if (dkInvoice != null && dkInvoice.getYxExportTaxAmount() != null) {
                                dkTaxAmount = dkTaxAmount
                                    .add(BigDecimal.valueOf(Double.parseDouble(dkInvoice.getYxExportTaxAmount())));
                            }
                            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;
                            }

                        }
                    }

                    record.setYxExportTaxAmount(yxTaxAmount);
                    record.setRzlx("1");
                    record.setAuthStatus("2");
                    record.setBdkStatus("1");
                    record.setConfirmDate(DateUtils.getSqlDate());
                    record.setConfirmUser(userInfo.getUsername());
                    record.setRzhBelongDate(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setCxrzStatus("0");
                    record.setCxrzDate(null);
                    record.setRzhType(dto.getRzhType());

                    records.add(record);

                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(record.getCustomsCode());
                    customsLog.setCreateDate(new Date());
                    customsLog.setInputName(userInfo.getLoginname());
                    customsLog.setType("8");
                    customsLog.setInputStatus("14");
                    logList.add(customsLog);
                } 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.setAuthStatus("2");
                    record.setRzhBelongDate(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setConfirmDate(DateUtils.getSqlDate());
                    record.setConfirmUser(userInfo.getUsername());
                    record.setRzhType(dto.getRzhType());
                    record.setCxrzDate(null);
                    record.setCxrzStatus("0");
                    record.setBdkMessage(dto.getBdkMessage());
                    record.setBdkYy(dto.getBdkYy());
                    records.add(record);

                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(record.getCustomsCode());
                    customsLog.setCreateDate(new Date());
                    customsLog.setInputName(userInfo.getLoginname());
                    customsLog.setType("9");
                    customsLog.setInputStatus("7");
                    logList.add(customsLog);
                }

            }
        }
        // 3.更新数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_WRITE);

        if (!flag && !flag1 && !flag2 && !flag3) {
            for (TDxExportCustoms record : records) {

                total++;
                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(record.getExportTaxAmount())){
                    hjse = hjse.add(new BigDecimal(record.getExportTaxAmount()));
                }

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(record.getYxExportTaxAmount())){
                    hjyxse = hjyxse.add(new BigDecimal(record.getYxExportTaxAmount()));
                }
                record.setUpdateDate(new Date());
                this.baseMapper.updateById(record);
            }
        }
        if (logList.size() > 0) {
            logService.toCustomsLog(logList);
        }

        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", total);
        resultMap.put("hjse", hjse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        resultMap.put("hjyxse", hjyxse.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        resultMap.put("message", message);

        return Base64.encode(JSONObject.toJSONString(resultMap));

    }

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

        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 mapTj = null;

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

        Page<Map> result = this.baseMapper.queryBdkByPage(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 dataSources = (String)map.get("dataSources");
                String authStatus = (String)map.get("authStatus");
                String cxbdkStatus = (String)map.get("cxbdkStatus");
                String bdkStatus = (String)map.get("bdkStatus");
                String bdkMessage = (String)map.get("bdkMessage");

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

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("exportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("exportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("yxExportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("yxExportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }

                map.put("select", true);

                TDxDkCountEntity tDxDkCountEntity = null;
                TDxTaxCurrentEntity tDxTaxCurrentEntity = null;
                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;
                    }
                }

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String fillInDate = (String)map.get("fillInDate");
                if (!DateUtil.isInTwoDate(tDxTaxCurrentEntity.getSelectStartDate(), tDxTaxCurrentEntity.getSelectEndDate(),
                    fillInDate)) {
                    map.put("select", false);
                    continue;
                }

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

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

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

        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 mapTj = null;

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

        Page<Map> result = this.baseMapper.queryRzcxByPage(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 cxrzStatus = (String)map.get("cxrzStatus");
                String bdkStatus = (String)map.get("bdkStatus");
                String rzhYesorno = (String)map.get("rzhYesorno");

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

                // 字典值转换
                String dataSources = (String)map.get("dataSources");
                map.put("dataSources", dictdetaServcice.queryDictName(DictConstant.JKSCJFS, dataSources));
                String glzt = (String)map.get("glzt");
                map.put("glzt", dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                map.put("rzhYesorno", dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));
                String authStatus = (String)map.get("authStatus");
                map.put("authStatus", dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
                map.put("cxrzStatus", dictdetaServcice.queryDictName(DictConstant.CXRZ_STATUS, cxrzStatus));;
                map.put("bdkStatus", dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                map.put("bdkStatusBak", bdkStatus);
                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("exportTaxAmount"))){
                    map.put("exportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("exportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("yxExportTaxAmount"))){
                    map.put("yxExportTaxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("yxExportTaxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }

                map.put("select", true);

                if (!"1".equals(rzhYesorno)) {
                    map.put("select", false);
                    continue;
                }

                TDxDkCountEntity tDxDkCountEntity = null;
                TDxTaxCurrentEntity tDxTaxCurrentEntity = null;
                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 (map.get("rzhBelongDate") != null
                    && !map.get("rzhBelongDate").equals(tDxTaxCurrentEntity.getCurrentTaxPeriod())) {
                    map.put("select", false);
                    continue;
                }

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

                if (!"0".equals(cxrzStatus) && !"5".equals(cxrzStatus)) {
                    map.put("select", false);
                }
            }
        }
        return resultData.getTjBdData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String approveCxrz(TdxExportCustomsModelDTO dto, UserInfo userInfo) {

        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<TDxExportCustoms> records = new ArrayList<>();
        // 2.校验
        List<String> dkList = new ArrayList<>();
        List<CustomsLog> logList = new ArrayList<>();
        for (String idstr : dto.getIds()) {

            Long id = Long.parseLong(idstr);

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

                TDxTaxCurrentEntity tDxTaxCurrentEntity = null;
                TDxDkCountEntity tDxDkCountEntity = null;
                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 ("1".equals(record.getBdkStatus())) {
                    record.setRzlx("5");
                    record.setCxrzCurrentPeriod(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setCxrzDate(new Date());
                    record.setCxrzStatus("1");
                    records.add(record);

                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(record.getCustomsCode());
                    customsLog.setCreateDate(new Date());
                    customsLog.setType("8");
                    customsLog.setInputName(userInfo.getLoginname());
                    customsLog.setInputStatus("15");
                    logList.add(customsLog);

                } else if ("2".equals(record.getBdkStatus())) {
                    // 撤销不抵扣
                    record.setBdkCurrentPeriod(tDxTaxCurrentEntity.getCurrentTaxPeriod());
                    record.setRzlx("6");
                    record.setCxbdkDate(new Date());
                    record.setCxbdkStatus("1");
                    records.add(record);

                    CustomsLog customsLog = new CustomsLog();
                    customsLog.setCustomsCode(record.getCustomsCode());
                    customsLog.setCreateDate(new Date());
                    customsLog.setType("9");
                    customsLog.setInputName(userInfo.getLoginname());
                    customsLog.setInputStatus("10");
                    logList.add(customsLog);
                }
            }
        }
        // 3.更新数据
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_WRITE);
        for (TDxExportCustoms record : records) {

            total++;
            if(cn.hutool.core.util.ObjectUtil.isNotEmpty(record.getExportTaxAmount())){
                hjse = hjse.add(new BigDecimal(record.getExportTaxAmount()));
            }

            if(cn.hutool.core.util.ObjectUtil.isNotEmpty(record.getYxExportTaxAmount())){
                hjyxse = hjyxse.add(new BigDecimal(record.getYxExportTaxAmount()));
            }
            record.setUpdateDate(new Date());
            this.baseMapper.updateById(record);
        }

        if (logList.size() > 0) {
            logService.toCustomsLog(logList);
        }

        if (flag1) {
            message = message + sb1.toString() + "如需勾选认证，请到企业税务信息菜单解除锁定";
        }
        if (flag2) {
            message = message + sb2.toString();
        }

        if (flag3) {
            message = message + sb3.toString();
        }

        resultMap.put("total", total);
        resultMap.put("hjse", hjse);
        resultMap.put("message", message);
        resultMap.put("hjje", hjje);
        resultMap.put("hjdk", hjyxse);
        return Base64.encode(JSONObject.toJSONString(resultMap));
    }
}
