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

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.api.model.db.TdxDkTsCountDetailEntity;
import com.dxhy.api.model.db.TdxDkTsCountEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.DataSourceEnum;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.QSignStatusEnum;
import com.dxhy.common.enums.QsTypeEnum;
import com.dxhy.common.service.CustomsLogService;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.common.utils.ResultData;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.core.job.service.ApplyService;
import com.dxhy.domestic.constants.DicProp;
import com.dxhy.domestic.dao.DomesticCustomsRecordDao;
import com.dxhy.domestic.dao.DomesticTdxTaxCurrentDao;
import com.dxhy.domestic.model.vo.BaseCustomsRefundImportVO;
import com.dxhy.domestic.service.customsrefund.DomesticCustomsRefundService;
import com.dxhy.domestic.util.ObjectUtil;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDao;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDetailDao;
import com.dxhy.vo.custom.BaseCustomsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("domesticCustomsRefundService")
@Slf4j
public class DomesticCustomsRefundServiceImpl extends MpBaseServiceImpl<DomesticCustomsRecordDao, TdxCustomsRecord>
    implements DomesticCustomsRefundService {

    /**
     * 判断小数点后2位的数字的正则表达式
     */
    private static final Pattern PATTERN_AMOUNT = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
    @Resource
    private CustomsLogService logService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Resource
    private DomesticTdxTaxCurrentDao domesticTdxTaxCurrentDao;

    @Resource
    private TdxDkTsCountDao tdxDkTsCountDao;
    @Resource
    private TdxDkTsCountDetailDao tdxDkTsCountDetailDao;

    @Resource
    private ApplyService applyService;

    @Override
    public String queryManualConfirmList(Page page, BaseCustomsVO entity) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(entity.getUserInfo().getDbName(), "business") + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        ResultData<Object> resultData = new ResultData<>();

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

        resultData.putTabulateMenu(tabulateMenu);

        List<String> buyerTaxNoList = new ArrayList<>();
        if (StringUtils.isEmpty(entity.getGfsh())) {
            buyerTaxNoList = entity.getUserInfo().getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());
            entity.setGfTaxNo(buyerTaxNoList);
        }
        if (StringUtils.isBlank(entity.getGfsh()) && buyerTaxNoList.size() <= 0) {
            resultData.setDataList(new ArrayList<>());
            return resultData.toJsonBase();
        }

        Page<Map> result = this.baseMapper.queryManualConfirmList(page, entity);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            double amountTotal = 0.0;
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map map = result.getRecords().get(i);
                String dataSources = (String)map.get("dataSources");
                map.put("id", String.valueOf(map.get("id")));
                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));

                // 字典转换
                map.put("dataSources", dictdetaServcice.queryDictName(DictConstant.JKSCJFS, dataSources));
                String qsStatus = (String)map.get("qsStatus");
                map.put("qsStatus", dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
                String qsType = (String)map.get("qsType");
                map.put("qsType", dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));

                if (map.get("fillInDate") != null) {
//                    map.put("fillInDate", sdf.format(map.get("fillInDate")));
                    map.put("fillInDate",map.get("fillInDate") );
                }
                if (map.get("qsDate") != null) {
//                    map.put("qsDate", sdf.format(map.get("qsDate")));
                    map.put("qsDate", map.get("qsDate"));
                }

                map.put("select", true);
                map.put("upgradeStatus", "1");
                String taxAmount = (String)map.get("taxAmount");
                amountTotal += Double.parseDouble(StringUtils.isEmpty(taxAmount) ? "0" : taxAmount);
                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("taxAmount"))){
                    map.put("taxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("taxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }
                if (!"0".equals(map.get("glzt"))) {
                    map.put("select", false);
                    continue;
                }

                String applyCheck = (String)map.get("applyCheck");
                String checkStatus = (String)map.get("checkStatus");
                String auditStatus = (String)map.get("auditStatus");

                // 采集数据
                if ("0".equals(dataSources)) {
                    if (!"0".equals(map.get("entryDiscrepancy"))) {
                        map.put("select", false);
                    }
                } else {// 录入数据
                    map.put("select", false);
                    if ("0".equals(applyCheck) && "1".equals(auditStatus)) {
                        log.debug("");
                    } else if ("1".equals(applyCheck) && "0".equals(checkStatus)) {
                        log.debug("");
                    } else {
                        map.put("select", false);
                    }
                }
            }
            Map<String, Object> mapTj = null;
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (entity.getCurr() == 1) {
                mapTj = this.baseMapper.queryManualConfirmSum(entity);
            }
            resultData.getTjBdData(mapTj);
        }

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

    @Override
    public String manualConfirm(BaseCustomsVO reqVO, 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 flag = false;
        StringBuilder sb = new StringBuilder();
        sb.append("以下缴款书号码的税款金额小于等于0不可勾选认证： 缴款书号码\n ");

        // 1.查询数据
        DynamicContextHolder.push(org.apache.commons.lang3.StringUtils.defaultString(userInfo.getDbName(), "business")
            + DbConstant.BUSINESS_READ);
        List<TdxCustomsRecord> records = new ArrayList<>();
        List<CustomsLog> logList = new ArrayList<>();
        for (String idstr : reqVO.getIds()) {

            if (idstr == null) {
                continue;
            }

            TdxCustomsRecord record = this.baseMapper.selectById(idstr);
            if (record != null) {
                //如果是代扣代缴，不验证以下信息
                if(!"4".equals(record.getXxly())){
                    if (Double.parseDouble(record.getTaxAmount()) <= 0) {
                        sb.append(record.getCustomsCode()).append(" \n ");
                        flag = true;
                        continue;
                    }
                }

                record.setBdkStatus("3");
                record.setRzlx("2");
                record.setRzhBelongDate(new SimpleDateFormat("yyyyMM").format(new Date()));
                record.setAuthStatus("2");
                record.setConfirmDate(DateUtils.getSqlDate());
                record.setConfirmUser(userInfo.getUsername());
                record.setCxrzStatus("0");
                record.setCxrzDate(null);
                records.add(record);
            }
        }
        // 3.更新数据
        DynamicContextHolder.push(org.apache.commons.lang3.StringUtils.defaultString(userInfo.getDbName(), "business")
            + DbConstant.BUSINESS_WRITE);

        if (!flag) {
            for (TdxCustomsRecord record : records) {
                total++;
                if(StringUtils.isNotEmpty(record.getTaxAmount())){
                    hjse = hjse.add(new BigDecimal(record.getTaxAmount()));
                }

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

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

        if (flag) {
            message = sb.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 importConfirmList(BaseCustomsVO reqVO) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(reqVO.getUserInfo().getDbName(), "business") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        // JSONObject json = super.setTitleList(DicProp.CUSTOMS_REFUND_IMPORT_CONFIRM_LIST_TITLE,
        // DicProp.CUSTOMS_REFUND_IMPORT_CONFIRM_LIST_PROP);
        List<String> taxnoList = UserInfoUtil.getGfshAll(reqVO.getUserInfo().getOrg());

        JSONObject json = tabulateRedisService.getTabulateMenu(reqVO.getUserInfo().getCompany(), reqVO.getMenuId());

        // 总数量
        int allNumber = 0;
        // 异常数量
        int errorNumber = 0;

        List<Object> returnList = new ArrayList<>();
        // 解析json
        JSONArray dateArray = JSONArray.parseArray(reqVO.getDataList());

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < dateArray.size(); i++) {
            JSONObject jsonObject = dateArray.getJSONObject(i);
            String taxno = jsonObject.getString("gfTaxNo");
            String customsCode = jsonObject.getString("customsCode");
            String fillInDate = jsonObject.getString("fillInDate");
            String taxAmount = jsonObject.getString("taxAmount");
            BaseCustomsRefundImportVO importVO = new BaseCustomsRefundImportVO(customsCode, fillInDate, taxAmount);
            importVO.setXh(String.valueOf(i + 1));

            if (StringHelper.isBlank(taxno)) {
                importVO.setErrorMassage("缴款书单位税号不能为空");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            }

            if (StringHelper.isBlank(customsCode) || ObjectUtil.isExistLowwer(customsCode)) {
                importVO.setErrorMassage("缴款书号码不能为空或格式错误");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            }

            if (StringHelper.isBlank(fillInDate)) {
                importVO.setErrorMassage("填发日期不能为空");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                sdf.parse(fillInDate);
            } catch (Exception e1) {
                importVO.setErrorMassage("填发日期格式错误");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            }

            if (StringHelper.isBlank(taxAmount)) {
                importVO.setErrorMassage("税款金额不能为空");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            } else {
                Matcher match = PATTERN_AMOUNT.matcher(taxAmount);
                if (!match.matches()) {
                    importVO.setErrorMassage("税款金额格式错误");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                taxAmount = MathUtil.round(taxAmount);
                importVO.setTaxAmount(AmountFormatUtil.fmtMicrometer(taxAmount));
            }
            if (uuidList.contains(customsCode)) {
                importVO.setErrorMassage("重复缴款书");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
                continue;
            } else {
                uuidList.add(customsCode);
            }

            QueryWrapper<TdxCustomsRecord> queryRecord = new QueryWrapper<>();
            queryRecord.eq("customs_code", customsCode);
            TdxCustomsRecord customRecord = this.baseMapper.selectOne(queryRecord);

            if (customRecord != null) {
                if (taxnoList.size() == 0 || !taxnoList.contains(customRecord.getGfTaxNo())) {
                    importVO.setErrorMassage("无该缴款书购方税号权限");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                TDxTaxCurrentEntity tdxTaxCurrentEntity = domesticTdxTaxCurrentDao.selectOne(
                        new QueryWrapper<TDxTaxCurrentEntity>().eq("taxno", customRecord.getGfTaxNo()));
                if (tdxTaxCurrentEntity == null) {
                    importVO.setErrorMassage("无该缴款书税号属期信息");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                // 补充列表所需信息
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                importVO.setId(customRecord.getId());
                importVO.setGfName(customRecord.getGfName());
                importVO.setDataSources(DataSourceEnum.getVal(ObjectUtil.fixNull(customRecord.getDataSources())));
                importVO.setBelongDate(tdxTaxCurrentEntity.getCurrentTaxPeriod());
                importVO.setQsStatus(QSignStatusEnum.getVal(ObjectUtil.fixNull(customRecord.getQsStatus())));
                if (customRecord.getFillInDate() != null) {
                    importVO.setQsDate(sdf.format(customRecord.getFillInDate()));
                }
                importVO.setQsType(QsTypeEnum.getVal(ObjectUtil.fixNull(customRecord.getQsType())));
                importVO.setQsUser(customRecord.getQsUser());

                String baseFillInDate = sdf2.format(customRecord.getFillInDate());
                if (!fillInDate.equals(baseFillInDate)) {
                    importVO.setErrorMassage("填发日期与底账数据不一致");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }

                if (!"0".equals(customRecord.getExportMark())) {
                    importVO.setErrorMassage("该缴款书已出口转内销");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                if (!"0".equals(customRecord.getGlzt())) {
                    importVO.setErrorMassage("管理状态异常");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                if ("0".equals(customRecord.getDataSources())) {

                    if (!"0".equals(customRecord.getEntryDiscrepancy())) {
                        importVO.setErrorMassage("管理状态异常");
                        importVO.setSelectFlag(false);
                        returnList.add(importVO);
                        errorNumber++;
                        continue;
                    }
                } else {// 录入数据
                    if ("0".equals(customRecord.getApplyCheck()) && !"1".equals(customRecord.getAuditStatus())) {

                        importVO.setErrorMassage("该缴款书稽核结果不相符");
                        importVO.setSelectFlag(false);
                        returnList.add(importVO);
                        errorNumber++;
                        continue;
                    } else if ("1".equals(customRecord.getApplyCheck()) && !"0".equals(customRecord.getCheckStatus())) {

                        importVO.setErrorMassage("该缴款书核对结果不允许抵扣、退税");
                        importVO.setSelectFlag(false);
                        returnList.add(importVO);
                        errorNumber++;
                        continue;
                    }
                }
                if ("1".equals(customRecord.getRzhYesorno())) {
                    importVO.setErrorMassage("该缴款书已认证抵扣");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                if ("3".equals(customRecord.getRzhYesorno())) {
                    importVO.setErrorMassage("该缴款书已退税认证");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                if ("1".equals(customRecord.getAuthStatus())) {
                    importVO.setErrorMassage("该缴款书已勾选未确认");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                } else if ("2".equals(customRecord.getAuthStatus())) {
                    importVO.setErrorMassage("该缴款书已确认");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                } else if ("3".equals(customRecord.getAuthStatus())) {
                    importVO.setErrorMassage("该缴款书已发送认证");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                } else if ("4".equals(customRecord.getAuthStatus())) {
                    importVO.setErrorMassage("该缴款书已认证抵扣");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }

                if ("2".equals(customRecord.getBdkStatus())) {
                    importVO.setErrorMassage("该缴款书已认证不抵扣");
                    importVO.setSelectFlag(false);
                    returnList.add(importVO);
                    errorNumber++;
                    continue;
                }
                returnList.add(importVO);
                allNumber++;
            } else {
                importVO.setErrorMassage("无底账信息");
                importVO.setSelectFlag(false);
                returnList.add(importVO);
                errorNumber++;
            }
        }
        json.put("allNumber", allNumber);
        json.put("errorNumber", errorNumber);
        json.put("datalist", returnList);
        json.put("total", dateArray.size());
        return super.responseResult(json);
    }

    @Override
    public String queryConfirmList(Page page, BaseCustomsVO entity) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(entity.getUserInfo().getDbName(), "business") + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        double amountTotal = 0.0;
        ResultData resultData = new ResultData();

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

        resultData.putTabulateMenu(tabulateMenu);

        List<String> buyerTaxNoList = new ArrayList<>();
        if (StringUtils.isEmpty(entity.getGfsh())) {
            buyerTaxNoList = entity.getUserInfo().getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());
            entity.setGfTaxNo(buyerTaxNoList);
        }

        Page<Map> result = this.baseMapper.queryCustomsRefundConfirmList(page, entity);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map map = result.getRecords().get(i);
                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));

                // 字典值转换
                String dataSources = (String)map.get("dataSources");
                map.put("dataSources", dictdetaServcice.queryDictName(DictConstant.JKSCJFS, dataSources));
                String qsStatus = (String)map.get("qsStatus");
                map.put("qsStatus", dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
                String qsType = (String)map.get("qsType");
                map.put("qsType", dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
                String glzt = (String)map.get("glzt");
                map.put("glzt", dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                String rzhYesorno = (String)map.get("rzhYesorno");
                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));
                String rzlx = (String)map.get("rzlx");
                map.put("rzlx", dictdetaServcice.queryDictName(DictConstant.INVOICE_RZLX, rzlx));

                if (map.get("fillInDate") != null) {
                    map.put("fillInDate", map.get("fillInDate"));
                }
                if (map.get("qsDate") != null) {
                    map.put("qsDate", map.get("qsDate"));
                }

                if (map.get("rzhDate") != null) {
                    map.put("rzhDate", map.get("rzhDate"));
                }

                String taxAmount = (String)map.get("taxAmount");
                amountTotal += Double.parseDouble(StringUtils.isEmpty(taxAmount) ? "0" : taxAmount);

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

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

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

    @Override
    public String queryRefundCountList(Page page, BaseCustomsVO entity) throws Exception {
        DynamicContextHolder
            .push(StringUtils.defaultString(entity.getUserInfo().getDbName(), "business") + DbConstant.BUSINESS_READ);
        if ("99".equals(entity.getGfsh())) {
            entity.setGfsh(null);
            entity.setGfTaxNo(UserInfoUtil.getGfshAll(entity.getUserInfo().getOrg()));
        }
        entity.setPage(page);

        ResultData resultData = new ResultData();

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

        resultData.putTabulateMenu(tabulateMenu);

        List<String> buyerTaxNoList = new ArrayList<>();
        if (StringUtils.isEmpty(entity.getGfsh())) {
            buyerTaxNoList = entity.getUserInfo().getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());
            entity.setGfTaxNo(buyerTaxNoList);
        }

        Page<Map> result = this.baseMapper.queryRefundCountPage(page, entity);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map map = result.getRecords().get(i);
                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                map.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(map.get("taxAmount").toString())));

                LambdaQueryWrapper<SysEnterpriseConfigEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysEnterpriseConfigEntity::getNsrsbh, map.get("gfTaxNo"));
                SysEnterpriseConfigEntity enterpriseConfigEntity = sysEnterpriseConfigDao.selectOne(lambdaQueryWrapper);
                //如果是乐企
                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"0".equals(enterpriseConfigEntity.getJrfs())){
                    map.put("isTsTjDqy", "1");
                }else{
                    map.put("isTsTjDqy", "0");
                }

                //查询退税抵扣表
                TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>().eq(TdxDkTsCountEntity::getTaxno, map.get("gfTaxNo"))
                        .eq(TdxDkTsCountEntity::getSkssq, map.get("rzhBelongDate"))
                );
                if(tdxDkTsCountEntity!=null){
                    map.put("tsqrStatus", dictdetaServcice.queryDictName(DictConstant.TSQR_STATUS, tdxDkTsCountEntity.getQrStatus()));
                    List<TdxDkTsCountDetailEntity> tdxDkTsCountEntities = tdxDkTsCountDetailDao.selectList(new LambdaQueryWrapper<TdxDkTsCountDetailEntity>().eq(TdxDkTsCountDetailEntity::getTaxno, map.get("gfTaxNo"))
                            .eq(TdxDkTsCountDetailEntity::getQrMonth, map.get("rzhBelongDate")));

                    BigDecimal tsqrTaxAmount = new BigDecimal("0.00");
                    for (int j = 0; j < tdxDkTsCountEntities.size() ; j++) {
                        tsqrTaxAmount = tsqrTaxAmount.add(new BigDecimal(tdxDkTsCountEntities.get(j).getTotalTaxAmount()));
                    }
                    map.put("tsqrTaxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(tsqrTaxAmount.toString())) );
                }

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

    @Override
    public String queryRefundCountDetailPage(Page page, BaseCustomsVO entity) throws Exception {
        // List<DictdetaModel> fplxModels = dictdetaServcice.selectDictdeta("INVOICE_TYPE");
        DynamicContextHolder
            .push(StringUtils.defaultString(entity.getUserInfo().getDbName(), "business") + DbConstant.BUSINESS_READ);
        Page<Map> result = this.baseMapper.queryRefundCountDetailPage(page, entity);
        if (CollectionUtils.isEmpty(result.getRecords()) || result.getRecords().size() < 5) {
            if (CollectionUtils.isEmpty(result.getRecords())) {
                Map<String, Object> map1 = new HashMap<>(16);
                map1.put("invoiceType", "增值税专用发票");
                map1.put("type", "01");
                map1.put("invCount", "0");
                map1.put("taxAmount", "0.00");
                map1.put("invoiceAmount", "0.00");
                result.getRecords().add(map1);
                Map<String, Object> map2 = new HashMap<>(16);
                map2.put("invoiceType", "增值税电子专用发票");
                map2.put("type", "08");
                map2.put("invCount", "0");
                map2.put("taxAmount", "0.00");
                map2.put("invoiceAmount", "0.00");
                result.getRecords().add(map2);
                Map<String, Object> map4 = new HashMap<>(16);
                map4.put("invoiceType", "电子发票(增值税专用发票)");
                map4.put("type", "31");
                map4.put("invCount", "0");
                map4.put("taxAmount", "0.00");
                map4.put("invoiceAmount", "0.00");
                result.getRecords().add(map4);
                Map<String, Object> map5 = new HashMap<>(16);
                map5.put("invoiceType", "数电纸票(增值税专用发票)");
                map5.put("type", "185");
                map5.put("invCount", "0");
                map5.put("taxAmount", "0.00");
                map5.put("invoiceAmount", "0.00");
                result.getRecords().add(map5);

                Map<String, Object> map3 = new HashMap<>(16);
                map3.put("invoiceType", "海关缴款书");
                map3.put("type", "17");
                map3.put("invCount", "0");
                map3.put("taxAmount", "0.00");
                map3.put("invoiceAmount", "0.00");
                result.getRecords().add(map3);

                Map<String, Object> map6 = new HashMap<>(16);
                map6.put("invoiceType", "合计");
                map6.put("type", "99");
                map6.put("invCount", "0");
                map6.put("taxAmount", "0.00");
                map6.put("invoiceAmount", "0.00");
                result.getRecords().add(map6);

            } else {
                StringBuilder type = new StringBuilder();
                for (int i = 0; i < result.getRecords().size(); i++) {
                    Map map = result.getRecords().get(i);
                    type.append(map.get("invoiceType"));
                    map.put("type", map.get("invoiceType"));
                    String invoiceType = (String)map.get("invoiceType");
                    map.put("invoiceType", dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPEALL, invoiceType));
                    // if (fplxModels!=null){
                    // for (DictdetaModel model : fplxModels){
                    // if (model.getDictcode().equals(map.get("invoiceType"))){
                    // map.put("invoiceType",model.getDictname());
                    // }
                    // }
                    // }
                    // Double amountTotal = (Double)map.get("taxAmount");
                    if(map.get("taxAmount")!=null){
                        map.put("taxAmount",
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(map.get("taxAmount").toString())));
                    }else{
                        map.put("taxAmount",
                                "0.00");
                    }

                    BigDecimal invoiceAmount = (BigDecimal)map.get("invoiceAmount");
                    if(invoiceAmount!=null){
                        map.put("invoiceAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceAmount.toString())));
                    }else{
                        map.put("invoiceAmount", "0.00");
                    }
                }

                if (type.indexOf("01") < 0) {
                    Map<String, Object> map1 = new HashMap<>(16);
                    map1.put("invoiceType", "增值税专用发票");
                    map1.put("type", "01");
                    map1.put("invCount", "0");
                    map1.put("taxAmount", "0.00");
                    map1.put("invoiceAmount", "0.00");
                    result.getRecords().add(map1);
                }
                if (type.indexOf("08") < 0) {
                    Map<String, Object> map1 = new HashMap<>(16);
                    map1.put("invoiceType", "增值税电子专用发票");
                    map1.put("type", "08");
                    map1.put("invCount", "0");
                    map1.put("taxAmount", "0.00");
                    map1.put("invoiceAmount", "0.00");
                    result.getRecords().add(map1);
                }
                if (type.indexOf("17") < 0) {
                    Map<String, Object> map1 = new HashMap<>(16);
                    map1.put("invoiceType", "海关缴款书");
                    map1.put("type", "17");
                    map1.put("invCount", "0");
                    map1.put("taxAmount", "0.00");
                    map1.put("invoiceAmount", "0.00");
                    result.getRecords().add(map1);
                }
                if (type.indexOf("31") < 0) {
                    Map<String, Object> map1 = new HashMap<>(16);
                    map1.put("invoiceType", "电子发票(增值税专用发票)");
                    map1.put("type", "31");
                    map1.put("invCount", "0");
                    map1.put("taxAmount", "0.00");
                    map1.put("invoiceAmount", "0.00");
                    result.getRecords().add(map1);
                }
                if (type.indexOf("185") < 0) {
                    Map<String, Object> map1 = new HashMap<>(16);
                    map1.put("invoiceType", "数电纸票(增值税专用发票)");
                    map1.put("type", "185");
                    map1.put("invCount", "0");
                    map1.put("taxAmount", "0.00");
                    map1.put("invoiceAmount", "0.00");
                    result.getRecords().add(map1);
                }
                //添加合计
                int invCount = 0;
                BigDecimal taxAmount  = new BigDecimal("0.00");
                BigDecimal invoiceAmount  = new BigDecimal("0.00");
                for (int j = 0; j < result.getRecords().size(); j++) {
                    invCount+=Integer.parseInt(result.getRecords().get(j).get("invCount").toString());
                    taxAmount = taxAmount.add(new BigDecimal(result.getRecords().get(j).get("taxAmount").toString().replace(",", ""))) ;
                    invoiceAmount = invoiceAmount.add(new BigDecimal(result.getRecords().get(j).get("invoiceAmount").toString().replace(",", ""))) ;
                }
                Map<String, Object> map99 = new HashMap<>(16);
                map99.put("invoiceType", "合计");
                map99.put("type", "99");
                map99.put("invCount", invCount);
                map99.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toString())));
                map99.put("invoiceAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceAmount.toString())));
                result.getRecords().add(map99);

            }
        } else {
            for (int i = 0; i < result.getRecords().size(); i++) {
                Map map = result.getRecords().get(i);

                map.put("type", map.get("invoiceType"));
                // if (fplxModels!=null){
                // for (DictdetaModel model : fplxModels){
                // if (model.getDictcode().equals(map.get("invoiceType"))){
                // map.put("invoiceType",model.getDictname());
                // }
                // }
                // }
                String invoiceType = (String)map.get("invoiceType");
                map.put("invoiceType", dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPEALL, invoiceType));
                // Double amountTotal = (Double)map.get("taxAmount");
                map.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(map.get("taxAmount").toString())));
                BigDecimal invoiceAmount = (BigDecimal)map.get("invoiceAmount");
                map.put("invoiceAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceAmount.toString())));
            }
        }
        return new ResultData().getPageData(result)
            .putTitleList(DicProp.REFUND_COUNT_DETAIL_LIST_TITLE, DicProp.REFUND_COUNT_DETAIL_LIST_PROP).toJsonBase();
    }
    /**
     * @Description 退税确认弹框界面
     * @param page
     * @param entity
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/3/15 11:17
     **/
    @Override
    public String queryRefundAlertPage(Page<Object> page, BaseCustomsVO entity) {
        //
        TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>().eq(TdxDkTsCountEntity::getSkssq, entity.getBelongDate())
                .eq(TdxDkTsCountEntity::getTaxno, entity.getGfsh())
        );
        List<Map> result = new LinkedList();

        Map<String, Object> map1 = new HashMap<>(16);
        map1.put("invoiceType", "专票");
        map1.put("type", "01");
        map1.put("invCount", "");
        map1.put("taxAmount", "");
        result.add(map1);
        Map<String, Object> map3 = new HashMap<>(16);
        map3.put("invoiceType", "海关缴款书");
        map3.put("type", "17");
        map3.put("invCount", "");
        map3.put("taxAmount", "");
        result.add(map3);
        Map<String, Object> map4 = new HashMap<>(16);
        map4.put("invoiceType", "合计");
        map4.put("type", "99");
        map4.put("invCount", "");
        map4.put("taxAmount", "");
        result.add(map4);


        String showProcess = "0";
        String applyMsg = "";

        //如果没找到，说明还没申请，可点击按钮
        if(tdxDkTsCountEntity==null){
            //没找到，用上面默认的值
            showProcess = "0";
        }else{
            //确认状态 0 未确认 1：确认中 2：确认成功 3：确认失败
            String qrStatus = tdxDkTsCountEntity.getQrStatus();
            showProcess = qrStatus;
            if("2".equals(qrStatus)){
                //取明细里的值，其他都是默认值
                result.clear();
                List<TdxDkTsCountDetailEntity> tdxDkTsCountDetailEntities = tdxDkTsCountDetailDao.selectList(new LambdaQueryWrapper<TdxDkTsCountDetailEntity>()
                        .eq(TdxDkTsCountDetailEntity::getTaxno, tdxDkTsCountEntity.getTaxno())
                        .eq(TdxDkTsCountDetailEntity::getQrMonth, tdxDkTsCountEntity.getSkssq())
                        //.last("order by  CAST(invoice_type AS UNSIGNED) ")
                );
                //按invoice_type的数字类型排序,由小到大
                Collections.sort(tdxDkTsCountDetailEntities,new Comparator<TdxDkTsCountDetailEntity>(){
                    @Override
                    public int compare(TdxDkTsCountDetailEntity o1, TdxDkTsCountDetailEntity o2) {
                        return MathUtil.compare(o1.getInvoiceType(), o2.getInvoiceType());
                    }
                });
                //true 用数据库数据。  false设置数量和金额都为空
                boolean hjcheck = false;
                //专票
                List<TdxDkTsCountDetailEntity> invoiceData = tdxDkTsCountDetailEntities.stream().filter(e -> "01".equals(e.getInvoiceType())).collect(Collectors.toList());
                if(invoiceData.size()>0){
                    Map<String,Object> resultMap1 = new HashMap();
                    resultMap1.put("invoiceType", "专票");
                    resultMap1.put("type", "01");
                    resultMap1.put("invCount", invoiceData.get(0).getTotalNumber());
                    resultMap1.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceData.get(0).getTotalTaxAmount())));
                    result.add(resultMap1);
                    hjcheck = true;
                }else{
                    Map<String,Object> resultMap1 = new HashMap();
                    resultMap1.put("invoiceType", "专票");
                    resultMap1.put("type", "01");
                    map4.put("invCount", "");
                    map4.put("taxAmount", "");
                    result.add(resultMap1);
                }
                //缴款书
                List<TdxDkTsCountDetailEntity> jksData = tdxDkTsCountDetailEntities.stream().filter(e -> "17".equals(e.getInvoiceType())).collect(Collectors.toList());
                if(jksData.size()>0){
                    Map<String,Object> resultMap1 = new HashMap();
                    resultMap1.put("invoiceType", "海关缴款书");
                    resultMap1.put("type", "17");
                    resultMap1.put("invCount", jksData.get(0).getTotalNumber());
                    resultMap1.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(jksData.get(0).getTotalTaxAmount())));
                    result.add(resultMap1);
                    hjcheck = true;
                }else{
                    Map<String,Object> resultMap1 = new HashMap();
                    resultMap1.put("invoiceType", "海关缴款书");
                    resultMap1.put("type", "17");
                    map4.put("invCount", "");
                    map4.put("taxAmount", "");
                    result.add(resultMap1);
                }

                int invCount = 0;
                BigDecimal taxAmount  = new BigDecimal("0.00");
                for (int i = 0; i < tdxDkTsCountDetailEntities.size(); i++) {
                    invCount+=Integer.parseInt(StringUtils.isBlank(tdxDkTsCountDetailEntities.get(i).getTotalNumber())?"0":tdxDkTsCountDetailEntities.get(i).getTotalNumber());
                    taxAmount = taxAmount.add(new BigDecimal(StringUtils.isBlank(tdxDkTsCountDetailEntities.get(i).getTotalTaxAmount())?"0":tdxDkTsCountDetailEntities.get(i).getTotalTaxAmount()));
                }
                Map<String,Object> resultMap1 = new HashMap();
                resultMap1.put("invoiceType", "合计");
                resultMap1.put("type", "99");
                //如果合计里都是空，则为空，否则弄对应的值
                if(hjcheck){
                    resultMap1.put("invCount", invCount);
                    resultMap1.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toString())));
                }else{
                    resultMap1.put("invCount", "");
                    resultMap1.put("taxAmount", "");
                }
                result.add(resultMap1);

            }else if("3".equals(qrStatus)){
                applyMsg = dictdetaServcice.queryDictName(DictConstant.APPLY_TS_MSG, tdxDkTsCountEntity.getFailReason());
            }
        }
        Map<String,String> resultProcess = new HashMap();
        resultProcess.put("showProcess", showProcess);
        resultProcess.put("applyMsg", applyMsg);

        ResultData resultData = new ResultData();
        resultData.setDataList(result);
        resultData.setData(resultProcess);
        return resultData.toJsonBase();
    }

    /**
     * @Description 退税确认弹框点击申请
     * @param baseCustomsVO
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/3/15 15:44
     **/
    @Override
    public ResponseEntity refundAlertApply(BaseCustomsVO baseCustomsVO) {
        log.info("退税确认申请开始");
        //发票和缴款书明细数据
        Map<String,String> result = applyService.taxRefundApplyPage(baseCustomsVO.getGfsh(), baseCustomsVO.getBelongDate());
        if(!"0000".equals(result.get("code"))){
            //申请失败
            return ResponseEntity.ok(R.error(result.get("msg")));
        }else{
            //申请成功
            return ResponseEntity.ok(R.ok().put("msg", "申请成功"));
        }
    }

    private String getFpzlMc(String invoiceType) {
        String fplx = "";
        if (FplxEnum.DZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.DZP.getFplxMc(FplxEnum.DZP.getIndex());
        } else if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.JDC.getFplxMc(FplxEnum.JDC.getIndex());
        } else if (FplxEnum.JSP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.JSP.getFplxMc(FplxEnum.JSP.getIndex());
        } else if (FplxEnum.PP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.PP.getFplxMc(FplxEnum.PP.getIndex());
        } else if (FplxEnum.TXF.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.TXF.getFplxMc(FplxEnum.TXF.getIndex());
        } else if (FplxEnum.ZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.ZP.getFplxMc(FplxEnum.ZP.getIndex());
        } else if (FplxEnum.HGJKS.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.HGJKS.getFplxMc(FplxEnum.HGJKS.getIndex());
        } else if (FplxEnum.DZZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.DZZP.getFplxMc(FplxEnum.DZZP.getIndex());
        }
        return fplx;
    }

}
