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

import cn.hutool.core.util.ObjectUtil;
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.conditions.update.LambdaUpdateWrapper;
import com.dxhy.api.model.db.TDxDkCountEntity;
import com.dxhy.api.model.ncp.ncpInvoice.TDxRecordInvoiceNcpVo;
import com.dxhy.api.model.ncp.ncpJjkcInvoice.*;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.NcpQrlxEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.NcpJjkcRecordInvoiceDao;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.NcpRecordInvoiceDao;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.TdxDkCountDao;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.TdxTaxCurrentDao;
import com.dxhy.jxpt.baseService.ncpInvoice.service.NcpJjkcInvoiceService;
import com.dxhy.jxpt.baseService.rzInvoice.dao.BaseServiceTdxInvoiceNcpDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 农产品页面功能业务
 * @Author wangruwei
 * @Date 2023/9/21 16:20
 **/
@Service("ncpJjkcInvoiceService")
@Slf4j
public class NcpJjkcInvoiceServiceImpl extends MpBaseServiceImpl<NcpJjkcRecordInvoiceDao, TdxInvoiceNcpJjkcEntity> implements NcpJjkcInvoiceService {

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private NcpRecordInvoiceDao ncpRecordInvoiceDao;

    @Resource
    private BaseServiceTdxInvoiceNcpDao baseServiceTdxInvoiceNcpDao;

    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Resource
    private TdxTaxCurrentDao tdxTaxCurrentDao;

    @Resource
    private NcpJjkcRecordInvoiceDao ncpJjkcRecordInvoiceDao;

    @Resource
    private TdxDkCountDao tdxDkCountDao;

    /**
     * @Description 农产品加计扣除界面分页查询
     * @param pramsMap
     * @param curr
     * @param size
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2023/10/17 15:44
     **/
    @Override
    public Object ncpJjkcInvoice(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        try {
            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            List<String> notInFphmList = new LinkedList();
            log.info("查询出当前属期，且属于加计扣除状态的发票");
            List<TDxDkCountEntity> dkCountList = new LinkedList();
            for (String gfsh:gfshList) {
                TDxTaxCurrentEntity tdxTaxCurrentEntity = tdxTaxCurrentDao.selectOne(
                        new QueryWrapper<TDxTaxCurrentEntity>().eq("taxno", gfsh));
                if(ObjectUtil.isNotEmpty(tdxTaxCurrentEntity)){
                    //当前税款所属期
                    String currentTaxPeriod = tdxTaxCurrentEntity.getCurrentTaxPeriod();
                    //查找出来不允许查询的发票号码集合
                    List<TdxInvoiceNcpJjkcEntity> notInJjkcList = ncpJjkcRecordInvoiceDao.selectList(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                            .eq(TdxInvoiceNcpJjkcEntity::getJjssq, currentTaxPeriod)
                            .eq(TdxInvoiceNcpJjkcEntity::getGfTaxNo, gfsh)
                            .notIn(TdxInvoiceNcpJjkcEntity::getClzt, "3", "8")
                    );
                    notInFphmList.addAll(notInJjkcList.stream().map(e->e.getInvoiceNo()).collect(Collectors.toList()));

                    log.info("查询所传税号是否已统计成功，用作限制是否可勾选。已统计成功的不允许勾选");
                    TDxDkCountEntity tdxDkCountEntity = tdxDkCountDao.selectOne(new LambdaQueryWrapper<TDxDkCountEntity>()
                            .eq(TDxDkCountEntity::getTaxno,gfsh)
                            .eq(TDxDkCountEntity::getSkssq, currentTaxPeriod));
                    if (ObjectUtil.isNotEmpty(tdxDkCountEntity)) {
                        dkCountList.add(tdxDkCountEntity);
                    }
                }
            }
            if(notInFphmList.size()>0){
                log.info("列表里排除出去的发票号码{}",notInFphmList);
                pramsMap.put("notInFphmList", notInFphmList);
            }
            //筛选税号和是否当前属期 统计中,统计成功。只要此方法筛选出来有数据，则不让勾选
            Map<String, List<TDxDkCountEntity>> tjSucList = dkCountList.stream().filter(e -> "1".equals(e.getTjStatus())||"2".equals(e.getTjStatus())).collect(Collectors.groupingBy(TDxDkCountEntity::getTaxno));


            //json = tabulateRedisService.getTabulateMenu(company, menuId);
            //TDxTaxCurrent tdxTaxCurrent = domesticTdxTaxCurrentDao.selectOne(
            //        new QueryWrapper<TDxTaxCurrent>().eq("taxno", customRecord.getGfTaxNo()));


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

            PageHelper.startPage(curr, size);
            List<TDxRecordInvoiceNcpVo> pageList = super.baseMapper.selectNcpJjkcInvoiceList(pramsMap);
            PageInfo<TDxRecordInvoiceNcpVo> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoiceNcpVo> resultList = pageInfo.getList();
            String searchPageType = pramsMap.get("searchPageType").toString();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + start));
                    /*
                     * @Description 可勾选条件-只要出来的数据都可勾选，因为限定发票是已认证的
                     **/
                    //认证处理状态  认证处理状态  0-未认证 1-已勾选未确认，2已确认 3 已发送认证 4 认证成功 5 认证失败 6已撤销认证
                    String rzclzt = resultList.get(i).getRzclzt();

                    pageList.get(i)
                            .setSelect(true);

                    //统计状态是已统计，统计中。则不让勾选
                    if(ObjectUtil.isNotEmpty(tjSucList.get(pageList.get(i).getGfsh()))&&tjSucList.get(pageList.get(i).getGfsh()).size()>0){
                        pageList.get(i)
                                .setSelect(false);
                    }

                    resultList.get(i).setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                    if (!"01".equals(resultList.get(i).getInvoiceType())
                            && !"03".equals(resultList.get(i).getInvoiceType())
                            && !"08".equals(resultList.get(i).getInvoiceType())
                            && !"14".equals(resultList.get(i).getInvoiceType())
                            && !"31".equals(resultList.get(i).getInvoiceType())) {
                        resultList.get(i).setDkTaxAmount(null);
                    } else {
                        if (StringUtils.isNotBlank(resultList.get(i).getDkTaxAmount())) {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkTaxAmount())));
                        } else {
                            resultList.get(i).setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                        }
                    }
                    //格式化农产品部分金额和农产品可抵扣税额
                    if(StringUtils.isNotEmpty(resultList.get(i).getNcpbfje())){
                        resultList.get(i).setNcpbfje(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getNcpbfje())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getNcpbfse())){
                        resultList.get(i).setNcpbfse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getNcpbfse())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getYxdkse())){
                        resultList.get(i).setYxdkse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getYxdkse())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getKjjkcse())){
                        resultList.get(i).setKjjkcse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getKjjkcse())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getSykjjkcse())){
                        resultList.get(i).setSykjjkcse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getSykjjkcse())));
                    }

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

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

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


                    //农产品
                    //申请确认状态  当前申请确认处理状态：0未确认，1申请确认，2发送确认请求，3确认失败，4确认成功
                    String dqsqqrclzt = resultList.get(i)
                            .getDqsqqrclzt();
                    resultList.get(i)
                            .setDqsqqrclzt(dictdetaServcice.queryDictName(DictConstant.NCPFPQR_SQQRZT, dqsqqrclzt));

                    //申请确认类型 1：待确认自产农产品销售发票，13：全部自产，14：不属于自产，15：部分属于自产，
                    //2：待确认从小规模处获取的 3%税率的专票，16：按票面金额和基础扣除率确认，17：按票面税额确认，
                    //3：代开农产品发票录入，4：农产品发票
                    String ncpSqqrlx = resultList.get(i).getNcpfpcllx();
                    resultList.get(i)
                            .setNcpfpcllx(dictdetaServcice.queryDictName(DictConstant.NCPFPCLLX_ALL, ncpSqqrlx));

                    //申请确认状态
                    String Jdqrzt = resultList.get(i).getJdqrzt();
                    resultList.get(i)
                            .setJdqrzt(dictdetaServcice.queryDictName(DictConstant.NCPFPQR_FPQRZT, Jdqrzt));

                    //申请确认类型
                    String Jdqrlx = resultList.get(i).getJdqrlx();
                    resultList.get(i)
                            .setJdqrlx(dictdetaServcice.queryDictName(DictConstant.NCPFPCLLX_ALL, Jdqrlx));




                }
            }

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

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

        return super.responseResult(json);
    }

    /**
     * @Description 加计扣除申请
     * @param req
     * @Return void
     * @Author wangruwei
     * @Date 2023/10/18 17:09
     **/
    @Override
    public String ncpJjkcSq(NcpJjkcSqReq req, String userName) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        //筛选出购方税号
        List<String> gfList = req.getInvoiceList().stream().map(e -> e.getGfsh()).distinct().collect(Collectors.toList());
        //筛选出属期
        List<TDxTaxCurrentEntity> taxCurrents = tdxTaxCurrentDao.selectList(new LambdaQueryWrapper<TDxTaxCurrentEntity>().in(TDxTaxCurrentEntity::getTaxno, gfList));
        /*//筛选出有当前属期的数据，没有的话，返回错误    当前属期肯定会有
        List<String> haveDqSqList = taxCurrents.stream().map(e -> e.getTaxno()).collect(Collectors.toList());
        gfList.removeAll(haveDqSqList);
        if(gfList.size()>0){
            json.put("code", "9999");
            json.put("msg", "以下税号没有当前属期信息");
            json.put("data", gfList);
            return super.responseResult(json);
        }*/

        //税号和属期分组
        Map<String, List<TDxTaxCurrentEntity>> gfTaxSqMap = taxCurrents.stream().collect(Collectors.groupingBy(e -> e.getTaxno()));
        List<NcpJjkcSqReqItem> invoiceList = req.getInvoiceList();
        if("0".equals(req.getSqType())){
            log.info("0申请全部项目不加计");
            for (NcpJjkcSqReqItem item:invoiceList) {
                TDxRecordInvoiceNcpVo ncpVo = ncpRecordInvoiceDao.selectNcpXsInvoiceByUuid(item.getUuid());
                String gfCurrent = findGfCurrent(gfTaxSqMap, ncpVo.getGfsh());
                TdxInvoiceNcpJjkcEntity jjkcEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                        .eq(TdxInvoiceNcpJjkcEntity::getUuid, item.getUuid())
                        .eq(TdxInvoiceNcpJjkcEntity::getJjssq, gfCurrent)
                );
                if(ObjectUtil.isEmpty(jjkcEntity)){
                    createJjkcData(req.getSqType(),ncpVo,gfCurrent,userName);
                }else{
                    log.info("加计扣除表中存在数据(存在则肯定是 3加计失败,8撤销成功)。删除当前数据，重新插入jjkc信息");
                    this.baseMapper.deleteById(jjkcEntity);
                    createJjkcData(req.getSqType(),ncpVo,gfCurrent,userName);
                }
            }
        }else if("1".equals(req.getSqType())){
            log.info("1申请剩余金额全部加计");
            for (NcpJjkcSqReqItem item:invoiceList) {
                TDxRecordInvoiceNcpVo ncpVo = ncpRecordInvoiceDao.selectNcpXsInvoiceByUuid(item.getUuid());
                String gfCurrent = findGfCurrent(gfTaxSqMap, ncpVo.getGfsh());
                TdxInvoiceNcpJjkcEntity jjkcEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                        .eq(TdxInvoiceNcpJjkcEntity::getUuid, item.getUuid())
                        .eq(TdxInvoiceNcpJjkcEntity::getJjssq, gfCurrent)
                );
                if(ObjectUtil.isEmpty(jjkcEntity)){
                    createJjkcData(req.getSqType(),ncpVo,gfCurrent,userName);
                }else{
                    log.info("加计扣除表中存在数据(存在则肯定是 3加计失败,8撤销成功)。删除当前数据，重新插入jjkc信息");
                    this.baseMapper.deleteById(jjkcEntity);
                    createJjkcData(req.getSqType(),ncpVo,gfCurrent,userName);
                }
            }
        }else if("2".equals(req.getSqType())){
            log.info("2申请剩余金额部分加计");

            //验证本次税额是否小于等于剩余可加计扣除税额
            for (int i = 0; i < invoiceList.size(); i++) {
                invoiceList.get(i).setRowNum(i+1);
            }
            List<NcpJjkcSqReqItem> errList = invoiceList.stream().filter(e -> MathUtil.compare(e.getBcjjkcse(), e.getSykjjkcse()) > 0).collect(Collectors.toList());
            if(errList.size()>0){
                json.put("code", "9999");
                json.put("msg", "验证失败");
                json.put("errList", errList);
                return super.responseResult(json);
            }

            for (NcpJjkcSqReqItem item:invoiceList) {
                TDxRecordInvoiceNcpVo ncpVo = ncpRecordInvoiceDao.selectNcpXsInvoiceByUuid(item.getUuid());
                String gfCurrent = findGfCurrent(gfTaxSqMap, ncpVo.getGfsh());
                TdxInvoiceNcpJjkcEntity jjkcEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                        .eq(TdxInvoiceNcpJjkcEntity::getUuid, item.getUuid())
                        .eq(TdxInvoiceNcpJjkcEntity::getJjssq, gfCurrent)
                );
                if(ObjectUtil.isEmpty(jjkcEntity)){
                    createJjkcBfData(req.getSqType(),ncpVo,gfCurrent,userName,item.getBcjjkcse());
                }else{
                    log.info("加计扣除表中存在数据(存在则肯定是 3加计失败,8撤销成功)。删除当前数据，重新插入jjkc信息");
                    this.baseMapper.deleteById(jjkcEntity);
                    createJjkcBfData(req.getSqType(),ncpVo,gfCurrent,userName,item.getBcjjkcse());
                }
            }

        }else{
            log.info("没有此类型");
            json.put("code", "9999");
            json.put("msg", "没有此类型");
            return super.responseResult(json);
        }
        json.put("code", "0000");
        json.put("msg", "申请成功");
        return super.responseResult(json);
    }

    /**
    * @Description 创建加计扣除信息
    * @Author wangruwei
    * @Date 2023/11/15 9:44
    **/
    private void createJjkcData(String sqType, TDxRecordInvoiceNcpVo ncpVo, String gfCurrent, String userName) {
        if("0".equals(sqType)){
            TdxInvoiceNcpJjkcEntity jjkcInsert = new TdxInvoiceNcpJjkcEntity();
            jjkcInsert.setInvoiceCode(ncpVo.getInvoiceCode());
            jjkcInsert.setInvoiceNo(ncpVo.getInvoiceNo());
            jjkcInsert.setEleInvoiceNo(ncpVo.getEleInvoiceNo());
            jjkcInsert.setInvoiceDate(ncpVo.getInvoiceDateDate());
            jjkcInsert.setInvoiceType(ncpVo.getInvoiceType());
            jjkcInsert.setCkznxzmbh(ncpVo.getLqCkznxzmbh());
            jjkcInsert.setGfTaxNo(ncpVo.getGfsh());
            jjkcInsert.setUuid(ncpVo.getUuid());
            jjkcInsert.setJjssq(gfCurrent);
            jjkcInsert.setBcjjkcse(null);
            jjkcInsert.setSqlx(NcpQrlxEnum.NCP_QR_TYPE_JJKC_SQQBBJJ_20.getKey());
            jjkcInsert.setClzt("1");
            jjkcInsert.setSbyy("");
            jjkcInsert.setCzsj(new Date());
            jjkcInsert.setCzr(userName);
            jjkcInsert.setCreateTime(new Date());
            this.baseMapper.insert(jjkcInsert);
        }else if("1".equals(sqType)){
            TdxInvoiceNcpJjkcEntity jjkcInsert = new TdxInvoiceNcpJjkcEntity();
            jjkcInsert.setInvoiceCode(ncpVo.getInvoiceCode());
            jjkcInsert.setInvoiceNo(ncpVo.getInvoiceNo());
            jjkcInsert.setEleInvoiceNo(ncpVo.getEleInvoiceNo());
            jjkcInsert.setInvoiceDate(ncpVo.getInvoiceDateDate());
            jjkcInsert.setInvoiceType(ncpVo.getInvoiceType());
            jjkcInsert.setCkznxzmbh(ncpVo.getLqCkznxzmbh());
            jjkcInsert.setGfTaxNo(ncpVo.getGfsh());
            jjkcInsert.setUuid(ncpVo.getUuid());
            jjkcInsert.setJjssq(gfCurrent);
            jjkcInsert.setBcjjkcse(ncpVo.getSykjjkcse());
            jjkcInsert.setSqlx(NcpQrlxEnum.NCP_QR_TYPE_JJKC_SQJJ_18.getKey());
            jjkcInsert.setClzt("1");
            jjkcInsert.setSbyy("");
            jjkcInsert.setCzsj(new Date());
            jjkcInsert.setCzr(userName);
            jjkcInsert.setCreateTime(new Date());
            this.baseMapper.insert(jjkcInsert);
        }
    }

    /**
     * @Description 创建加计扣除信息,自定义部分扣除
     * @Author wangruwei
     * @Date 2023/11/15 9:44
     **/
    private void createJjkcBfData(String sqType, TDxRecordInvoiceNcpVo ncpVo, String gfCurrent, String userName,String bcjjkcse) {
        TdxInvoiceNcpJjkcEntity jjkcInsert = new TdxInvoiceNcpJjkcEntity();
        jjkcInsert.setInvoiceCode(ncpVo.getInvoiceCode());
        jjkcInsert.setInvoiceNo(ncpVo.getInvoiceNo());
        jjkcInsert.setEleInvoiceNo(ncpVo.getEleInvoiceNo());
        jjkcInsert.setInvoiceDate(ncpVo.getInvoiceDateDate());
        jjkcInsert.setInvoiceType(ncpVo.getInvoiceType());
        jjkcInsert.setCkznxzmbh(ncpVo.getLqCkznxzmbh());
        jjkcInsert.setGfTaxNo(ncpVo.getGfsh());
        jjkcInsert.setUuid(ncpVo.getUuid());
        jjkcInsert.setJjssq(gfCurrent);
        jjkcInsert.setBcjjkcse(bcjjkcse);
        jjkcInsert.setSqlx(NcpQrlxEnum.NCP_QR_TYPE_JJKC_SQJJ_18.getKey());
        jjkcInsert.setClzt("1");
        jjkcInsert.setSbyy("");
        jjkcInsert.setCzsj(new Date());
        jjkcInsert.setCzr(userName);
        jjkcInsert.setCreateTime(new Date());
        this.baseMapper.insert(jjkcInsert);
    }

    /**
     * @Description 农产品加计扣除结果查询
     * @Author wangruwei
     * @Date 2023年10月19日16:57:06
     **/
    @Override
    public Object ncpJjkcResultPage(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {

            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            log.info("查询出当前属期，且属于加计扣除状态的发票");
            List<TDxDkCountEntity> dkCountList = new LinkedList();
            //查询出税号和属期对应的关系
            List<TDxTaxCurrentEntity> AllgfCurrentList = new LinkedList();
            for (String gfsh:gfshList) {
                TDxTaxCurrentEntity tdxTaxCurrentEntity = tdxTaxCurrentDao.selectOne(
                        new QueryWrapper<TDxTaxCurrentEntity>().eq("taxno", gfsh));
                if(ObjectUtil.isNotEmpty(tdxTaxCurrentEntity)){
                    AllgfCurrentList.add(tdxTaxCurrentEntity);
                    //当前税款所属期
                    String currentTaxPeriod = tdxTaxCurrentEntity.getCurrentTaxPeriod();

                    log.info("查询所传税号是否已统计成功，用作限制是否可勾选。已统计成功的不允许勾选");
                    TDxDkCountEntity tdxDkCountEntity = tdxDkCountDao.selectOne(new LambdaQueryWrapper<TDxDkCountEntity>()
                            .eq(TDxDkCountEntity::getTaxno,gfsh)
                            .eq(TDxDkCountEntity::getSkssq, currentTaxPeriod));
                    if (ObjectUtil.isNotEmpty(tdxDkCountEntity)) {
                        dkCountList.add(tdxDkCountEntity);
                    }
                }
            }
            //筛选税号和是否当前属期 统计中,统计成功。只要此方法筛选出来有数据，则不让勾选
            Map<String, List<TDxDkCountEntity>> tjSucList = dkCountList.stream().filter(e -> "0".equals(e.getTjStatus())||"3".equals(e.getTjStatus())).collect(Collectors.groupingBy(TDxDkCountEntity::getTaxno));
            //税号对应属期
            Map<String, List<TDxTaxCurrentEntity>> AllgfCurrentMap = AllgfCurrentList.stream().collect(Collectors.groupingBy(TDxTaxCurrentEntity::getTaxno));


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

            PageHelper.startPage(curr, size);
            List<TDxRecordInvoiceNcpJjkcVo> pageList = super.baseMapper.selectNcpJjkcResultList(pramsMap);
            PageInfo<TDxRecordInvoiceNcpJjkcVo> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoiceNcpJjkcVo> resultList = pageInfo.getList();
            String searchPageType = pramsMap.get("searchPageType").toString();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                log.info("需要判断复选框是否可勾选：1.当前属期状态为 未统计，统计失败。2.农产品发票处理状态为加计成功。3.加计属期等于当前属期");
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + start));

                    pageList.get(i)
                            .setSelect(false);

                    List<TDxTaxCurrentEntity> tDxTaxCurrentEntities = AllgfCurrentMap.get(pageList.get(i).getGfTaxNo());
                    String currentSq = "";
                    if(!CollectionUtils.isEmpty(tDxTaxCurrentEntities)&&tDxTaxCurrentEntities.size()>0){
                        currentSq = tDxTaxCurrentEntities.get(0).getCurrentTaxPeriod();
                    }

                    //统计状态是未统计，统计失败
                    if( (
                            (ObjectUtil.isNotEmpty(tjSucList.get(pageList.get(i).getGfTaxNo()))&&tjSucList.get(pageList.get(i).getGfTaxNo()).size()>0)||
                                    ObjectUtil.isEmpty(tjSucList.get(pageList.get(i).getGfTaxNo()))
                    )
                            &&"4".equals(resultList.get(i).getClzt())
                            &&currentSq.equals(pageList.get(i).getJjssq())
                    ){
                        pageList.get(i)
                                .setSelect(true);
                    }

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

                    if(StringUtils.isNotEmpty(resultList.get(i).getKjjkcse())) {
                        resultList.get(i).setKjjkcse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getKjjkcse())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getBcjjkcse())) {
                        resultList.get(i).setBcjjkcse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getBcjjkcse())));
                    }
                    if(StringUtils.isNotEmpty(resultList.get(i).getSykjjkcse())) {
                        resultList.get(i).setSykjjkcse(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getSykjjkcse())));
                    }

                    //加计处理状态
                    String clzt = resultList.get(i).getClzt();
                    resultList.get(i)
                            .setClzt(dictdetaServcice.queryDictName(DictConstant.NCPJJKC_JJCLZT, clzt));

                    String sqlx = resultList.get(i).getSqlx();
                    resultList.get(i)
                            .setSqlx(dictdetaServcice.queryDictName(DictConstant.NCPJJKC_SQLX, sqlx));
                }
            }

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

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

    /**
     * @Description 农产品撤销加计
     * @Author wangruwei
     * @Date 2023年10月19日16:57:06
     **/
    @Override
    public String ncpJjkcCx(List<NcpJjkcSqReqItem> invoiceList, String userName) {
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        for (int i = 0; i < invoiceList.size(); i++) {
            NcpJjkcSqReqItem ncpJjkcSqReqItem = invoiceList.get(i);
            TdxInvoiceNcpJjkcEntity jjkcEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                    .eq(TdxInvoiceNcpJjkcEntity::getUuid, ncpJjkcSqReqItem.getUuid())
                    .eq(TdxInvoiceNcpJjkcEntity::getJjssq, ncpJjkcSqReqItem.getJjssq())
            );
            TdxInvoiceNcpJjkcEntity updateJjkc = new TdxInvoiceNcpJjkcEntity();
            if(NcpQrlxEnum.NCP_QR_TYPE_JJKC_SQJJ_18.getKey().equals(jjkcEntity.getSqlx())){
                updateJjkc.setSqlx(NcpQrlxEnum.NCP_QR_TYPE_JJKC_CXJJ_19.getKey());
            }
            if(NcpQrlxEnum.NCP_QR_TYPE_JJKC_SQQBBJJ_20.getKey().equals(jjkcEntity.getSqlx())){
                updateJjkc.setSqlx(NcpQrlxEnum.NCP_QR_TYPE_JJKC_CXQBBJJ_21.getKey());
            }
            updateJjkc.setClzt("5");
            updateJjkc.setCzsj(new Date());
            this.baseMapper.update(updateJjkc, new LambdaUpdateWrapper<TdxInvoiceNcpJjkcEntity>()
                    .eq(TdxInvoiceNcpJjkcEntity::getUuid, ncpJjkcSqReqItem.getUuid())
                    .eq(TdxInvoiceNcpJjkcEntity::getJjssq, ncpJjkcSqReqItem.getJjssq())
            );
        }
        JSONObject json = new JSONObject();
        json.put("code", "0000");
        json.put("msg", "撤销成功");
        return super.responseResult(json);
    }

    private String findGfCurrent(Map<String, List<TDxTaxCurrentEntity>> gfTaxSqMap, String gfsh) {
        if(ObjectUtil.isNotEmpty(gfTaxSqMap.get(gfsh))){
            return gfTaxSqMap.get(gfsh).size() > 0 ? gfTaxSqMap.get(gfsh).get(0).getCurrentTaxPeriod() : "";
        }else{
            return "";
        }
    }


}
