package com.dxhy.erp.service.impl;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.erp.dao.AllTaxesSaleCountDao;
import com.dxhy.erp.dao.AllTaxesSaleDao;
import com.dxhy.erp.dao.AllTaxesSaleRateDao;
import com.dxhy.erp.entity.alltax.*;
import com.dxhy.erp.rabbitmq.Sender;
import com.dxhy.erp.service.AllTaxesSaleService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author luxiaoxu
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("allTaxesSaleService")
@Slf4j
public class AllTaxesSaleServiceImpl implements AllTaxesSaleService {
    @Resource
    private AllTaxesSaleDao allTaxesSaleDao;
    @Resource
    private AllTaxesSaleCountDao allTaxesSaleCountDao;
    @Resource
    private AllTaxesSaleRateDao allTaxesSaleRateDao;
    @Resource
    private Sender sender;

    @Override
    public String getInvoiceSaleSign(TaxesSaleRequestSign req) {
        // 完成标识
        int flag = 1;
        ReturnSaleSign returnSign = new ReturnSaleSign();
        List<SaleParams> taxnoList = req.getParam();
        List<SaleSignInfo> signList = new ArrayList<SaleSignInfo>();
        try {
            if ("1".equals(req.getInformType())) {
                for (SaleParams params : taxnoList) {
                    SaleSignInfo signInfo = new SaleSignInfo();
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(params.getTaxNumber());
                    log.info("线程{},获取完成标识税号{}", Thread.currentThread().getId(), params.getTaxNumber());
                    if (deptInfo == null) {
                        flag = 2;
                        signInfo.setCompleteFlag(flag);
                        signInfo.setTaxNumber(params.getTaxNumber());
                        signInfo.setBillingDate(params.getBillingDate());
                        signList.add(signInfo);
                    } else {
                        // 主体数据入库标识
                        String dbName = deptInfo.getString("db_name");
                        // 明细数据入库标识
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                        // try {
                        int count =
                            allTaxesSaleDao.getCountSaleSign(params.getTaxNumber(), params.getBillingDate(), "1");
                        // 若count大于0,则返回 已完成标识、否则为未完成
                        if (count > 0) {
                            flag = 2;
                            signInfo.setCompleteFlag(flag);
                            signInfo.setTaxNumber(params.getTaxNumber());
                            signInfo.setBillingDate(params.getBillingDate());
                        } else {
                            flag = 1;
                            signInfo.setCompleteFlag(flag);
                            signInfo.setTaxNumber(params.getTaxNumber());
                            signInfo.setBillingDate(params.getBillingDate());
                            // 判断如果明细中没有数据需要再调用一遍汇总
                            TaxesSaleRequestInfo taxesRequestInfo = new TaxesSaleRequestInfo();
                            List<SaleParams> list = new ArrayList<>();
                            list.add(params);
                            taxesRequestInfo.setInformType("1");
                            taxesRequestInfo.setParam(list);
                            this.countSale(taxesRequestInfo);
                        }
                    }

                    signList.add(signInfo);
                }

            } else if ("2".equals(req.getInformType())) {
                for (SaleParams params : taxnoList) {
                    SaleSignInfo signInfo = new SaleSignInfo();
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(params.getTaxNumber());
                    if (deptInfo == null) {
                        flag = 2;
                        signInfo.setCompleteFlag(flag);
                        signInfo.setTaxNumber(params.getTaxNumber());
                        signInfo.setBillingDate(params.getBillingDate());
                        signList.add(signInfo);
                    } else {
                        // 主体数据入库标识
                        String dbName = deptInfo.getString("db_name");
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                        try {
                            int count =
                                allTaxesSaleDao.getCountSaleSign(params.getTaxNumber(), params.getBillingDate(), "0");
                            // 若count大于0,则返回 已完成标识、否则为未完成
                            if (count > 0) {
                                flag = 2;
                                signInfo.setCompleteFlag(flag);
                                signInfo.setTaxNumber(params.getTaxNumber());
                                signInfo.setBillingDate(params.getBillingDate());
                            } else {
                                flag = 1;
                                signInfo.setCompleteFlag(flag);
                                signInfo.setTaxNumber(params.getTaxNumber());
                                signInfo.setBillingDate(params.getBillingDate());
                                // 判断如果明细中没有数据需要再调用一遍汇总
                                TaxesSaleRequestInfo taxesRequestInfo = new TaxesSaleRequestInfo();
                                List<SaleParams> list = new ArrayList<>();
                                list.add(params);
                                taxesRequestInfo.setInformType("2");
                                taxesRequestInfo.setParam(list);
                                this.countSale(taxesRequestInfo);
                            }
                        } catch (Exception e) {
                            flag = 3;
                            signInfo.setCompleteFlag(flag);
                            signInfo.setTaxNumber(params.getTaxNumber());
                            signInfo.setBillingDate(params.getBillingDate());
                        }
                        signList.add(signInfo);
                    }
                }
            } else {
                return null;
            }
            returnSign.setInformType(req.getInformType());
            returnSign.setCode("0000");
            returnSign.setMessage("获取成功");
            returnSign.setParam(signList);
            return JSONObject.toJSONString(returnSign, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            e.printStackTrace();
            returnSign.setInformType(req.getInformType());
            returnSign.setCode("0001");
            returnSign.setMessage("获取失败");
            returnSign.setParam(null);
            return JSONObject.toJSONString(returnSign, SerializerFeature.WriteMapNullValue);
        }
    }

    @Override
    public String getInvoiceSale(String params, TaxesSaleRequestInfo req) {
        AllTaxReturnInfo returnInfo = new AllTaxReturnInfo();
        try {
            String type = req.getInformType();
            // 类型为空，失败 类型为2，关键字为空 失败。
            log.info("线程{},通知类型{}", Thread.currentThread().getId(), type);
            if (StringUtils.isEmpty(type)) {
                returnInfo.setCode("0001");
                returnInfo.setMessage("通知失败");
                return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
            } else {
                returnInfo.setCode("0000");
                returnInfo.setMessage("通知成功");
                return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
            }
        } catch (Exception e) {
            returnInfo.setCode("0001");
            returnInfo.setMessage("通知失败");
            return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
        }
    }

    @Override
    public void countSale(TaxesSaleRequestInfo req) {
        // 汇总
        try {
            if ("1".equals(req.getInformType())) {
                List<SaleParams> list = req.getParam();
                // 根据参数入库
                countByTaxRate(list);
            }

            // 按项目统计
            if ("2".equals(req.getInformType())) {
                // 根据参数入库
                sender.sendToStatus(JSONObject.toJSONString(req));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void countByTaxRate(List<SaleParams> list) {
        for (SaleParams saleParams : list) {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(saleParams.getTaxNumber());
            if (deptInfo == null) {
                log.info("线程{}税号未配置{}", Thread.currentThread().getId(), saleParams.getTaxNumber());
                continue;

            }
            String dbName = deptInfo.getString("db_name");
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            String taxno = saleParams.getTaxNumber();
            String belongDate = saleParams.getBillingDate();
            SaleParamsEntity entity = new SaleParamsEntity();
            entity.setBillingDate(saleParams.getBillingDate());
            entity.setCreateDate(new Date());
            entity.setTaxNumber(saleParams.getTaxNumber());
            entity.setSign("1");
            entity.setStatus("1");
            int count =
                allTaxesSaleDao.selectCountByDateAndTax(saleParams.getBillingDate(), saleParams.getTaxNumber(), "1");
            if (count > 0) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                // 删除汇总主信息
                allTaxesSaleDao.deleteCount(saleParams.getBillingDate(), saleParams.getTaxNumber(), "1");
                allTaxesSaleDao.deleteDetailTaxRate(saleParams.getBillingDate(), saleParams.getTaxNumber());
            }
            // 保存参数入库
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            allTaxesSaleDao.insert(entity);
            List<String> monthList;
            // 获取需要汇总的日期返回 --销项以开票日期查询
            monthList = getBelongByParam(belongDate);
            // 获取符合参数的发票信息
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            List<SaleInvoiceRatePo> invoiceList = allTaxesSaleDao.getInvoiceCountByTaxRate(taxno, monthList);
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            for (SaleInvoiceRatePo po : invoiceList) {
                SaleInvoiceRateEntity rateEntity = new SaleInvoiceRateEntity();
                rateEntity.setCreateDate(new Date());
                rateEntity.setBillingDate(belongDate);
                BigDecimal totalAmount = po.getInvoiceAmount().add(po.getTaxAmount());
                String invoiceType = exchangeInvoiceTypeByRate(po.getInvoiceType());
                rateEntity.setInvoiceKindCode(invoiceType);
                // 转换实体入库
                if (!"2".equals(po.getInvoiceStatus()) && po.getInvoiceAmount().compareTo(new BigDecimal("0")) < 0) {
                    // 转换实体
                    rateEntity.setInvoiceType("1");
                    rateEntity.setTaxRate(po.getTaxRate());
                    rateEntity.setTaxNumber(taxno);
                    rateEntity.setInvoiceAmountNt(po.getInvoiceAmount());
                    rateEntity.setTaxAmountNt(po.getTaxAmount());
                    rateEntity.setTotalAmountNt(totalAmount);

                } else if (!"2".equals(po.getInvoiceStatus())
                    && po.getInvoiceAmount().compareTo(new BigDecimal("0")) >= 0) {
                    rateEntity.setInvoiceType("0");
                    rateEntity.setTaxRate(po.getTaxRate());
                    rateEntity.setTaxNumber(taxno);
                    rateEntity.setInvoiceAmountPt(po.getInvoiceAmount());
                    rateEntity.setTaxAmountPt(po.getTaxAmount());
                    rateEntity.setTotalAmountPt(totalAmount);
                } else if ("2".equals(po.getInvoiceStatus())
                    && po.getInvoiceAmount().compareTo(new BigDecimal("0")) < 0) {
                    rateEntity.setInvoiceType("4");
                    rateEntity.setTaxRate(po.getTaxRate());
                    rateEntity.setTaxNumber(taxno);
                    rateEntity.setInvoiceAmountNtVoid(po.getInvoiceAmount());
                    rateEntity.setTaxAmountNtVoid(po.getTaxAmount());
                    rateEntity.setTotalAmountNtVoid(totalAmount);
                } else if ("2".equals(po.getInvoiceStatus())
                    && po.getInvoiceAmount().compareTo(new BigDecimal("0")) >= 0) {
                    rateEntity.setInvoiceType("3");
                    rateEntity.setTaxRate(po.getTaxRate());
                    rateEntity.setTaxNumber(taxno);
                    rateEntity.setInvoiceAmountPtVoid(po.getInvoiceAmount());
                    rateEntity.setTaxAmountPtVoid(po.getTaxAmount());
                    rateEntity.setTotalAmountPtVoid(totalAmount);
                }
                allTaxesSaleRateDao.insert(rateEntity);
            }
            allTaxesSaleDao.updateStatusByTaxNumberAndBill(taxno, belongDate, "1");
        }
    }

    private String exchangeInvoiceTypeByRate(String invoiceType) {
        if ("01".equals(invoiceType)) {
            return "0";
        }
        if ("04".equals(invoiceType)) {
            return "2";
        }
        if ("10".equals(invoiceType)) {
            return "51";
        }
        if ("11".equals(invoiceType)) {
            return "41";
        }
        if ("08".equals(invoiceType)) {
            return "61";
        }
        return "";
    }

    /**
     * 按项目统计方法
     *
     * @param list
     *            数据
     */
    @Override
    public void countByItem(List<SaleParams> list) {
        for (SaleParams saleParams : list) {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(saleParams.getTaxNumber());
            if (deptInfo == null) {
                log.info("线程{}税号未配置{}", Thread.currentThread().getId(), saleParams.getTaxNumber());
                continue;

            }
            String dbName = deptInfo.getString("db_name");
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            String taxno = saleParams.getTaxNumber();
            String belongDate = saleParams.getBillingDate();
            SaleParamsEntity entity = new SaleParamsEntity();
            entity.setBillingDate(saleParams.getBillingDate());
            entity.setCreateDate(new Date());
            entity.setTaxNumber(saleParams.getTaxNumber());
            entity.setSign("1");
            entity.setStatus("0");
            int count =
                allTaxesSaleDao.selectCountByDateAndTax(saleParams.getBillingDate(), saleParams.getTaxNumber(), "0");
            if (count > 0) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                // 删除汇总主信息
                allTaxesSaleDao.deleteCount(saleParams.getBillingDate(), saleParams.getTaxNumber(), "0");
                allTaxesSaleDao.deleteDetailItem(saleParams.getBillingDate(), saleParams.getTaxNumber());
            }
            // 保存参数入库
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            int id = allTaxesSaleDao.insert(entity);

            List<String> monthList;
            // 特殊流程 保留其他明细行数据
            // 获取需要汇总的日期返回 --销项以开票日期查询
            monthList = getBelongByParam(belongDate);
            // 获取符合参数的发票信息
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            List<SaleInvoicePo> invoiceList = allTaxesSaleDao.getInvoiceByParam(taxno, monthList);
            // 通过发票信息获取明细
            for (SaleInvoicePo po : invoiceList) {
                // 是否已归发票数量
                boolean isAdd = false;
                // 遍历明细-判断明细行
                String uuid = po.getUuid();
                DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
                List<SaleInvoiceDetailInfo> detailListByDb = allTaxesSaleDao.getInvoiceDetailByUuid(uuid);
                List<SaleInvoiceDetailInfo> detailListByDbLast = new ArrayList<>(detailListByDb);
                Map<String, String> map = new HashMap<>();
                // 特殊流程判断汇总
                for (SaleInvoiceDetailInfo detail : detailListByDb) {
                    BigDecimal bindDetailAmount = new BigDecimal("0");
                    BigDecimal bindTaxAmount = new BigDecimal("0");
                    BigDecimal bindTotalAmount = new BigDecimal("0");
                    SaleInvoiceDetailInfo bindEntity = null;
                    boolean isDelete = false;
                    boolean isSpecial1 = false;
                    if ("原价合计".equals(detail.getGoodsName()) || "折扣额合计".equals(detail.getGoodsName())
                        || "(详见销货清单)".equals(detail.getGoodsName()) || "（详见销货清单）".equals(detail.getGoodsName())) {
                        detailListByDbLast.remove(detail);
                        continue;
                    }

                    if (detail.getGoodsNum() != null) {
                        if (detail.getGoodsNum().startsWith("30404")) {
                            boolean isBind = false;
                            boolean isJzjt = false;
                            // 判断是否有货物 非即征即退优惠政策
                            for (SaleInvoiceDetailInfo d : detailListByDb) {
                                if (d.getGoodsNum() != null) {
                                    if (d.getGoodsNum().startsWith("1")) {
                                        if (detail.getTaxRate().equals(d.getTaxRate())) {
                                            if ("非即征即退".equals(exchangeIncentiveFlag(d.getIncentiveFlag()))) {
                                                isJzjt = true;
                                            }
                                        }
                                    }
                                }
                            }
                            for (SaleInvoiceDetailInfo speDetail : detailListByDb) {
                                if (speDetail.getGoodsNum() != null) {
                                    if (speDetail.getGoodsNum().startsWith("1")) {
                                        if (detail.getTaxRate().equals(speDetail.getTaxRate())) {
                                            // 如果有非即征即退明细行时，往非即征即退汇总
                                            if (isBind) {
                                                continue;
                                            }
                                            bindEntity = speDetail;
                                            if (isJzjt) {
                                                if ("非即征即退"
                                                    .equals(exchangeIncentiveFlag(speDetail.getIncentiveFlag()))) {
                                                    // 捆绑
                                                    if (!isSpecial1 && notAddTax(map, detail.getTaxRate())) {
                                                        isBind = true;
                                                        isDelete = true;
                                                        isSpecial1 = true;
                                                        bindDetailAmount = new BigDecimal(detail.getDetailAmount())
                                                            .add(new BigDecimal(speDetail.getDetailAmount()));
                                                        bindTaxAmount = new BigDecimal(detail.getTaxAmount())
                                                            .add(new BigDecimal(speDetail.getTaxAmount()));
                                                        bindTotalAmount = bindDetailAmount.add(bindTaxAmount);
                                                        map.put(speDetail.getTaxRate(), speDetail.getTaxRate());
                                                    } else {
                                                        isBind = true;
                                                        isDelete = true;
                                                        isSpecial1 = true;
                                                        bindDetailAmount = bindDetailAmount
                                                            .add(new BigDecimal(detail.getDetailAmount()));
                                                        bindTaxAmount =
                                                            bindTaxAmount.add(new BigDecimal(detail.getTaxAmount()));
                                                        bindTotalAmount = bindDetailAmount.add(bindTaxAmount);
                                                    }
                                                }
                                            } else {
                                                if (!isSpecial1 && notAddTax(map, detail.getTaxRate())) {
                                                    isBind = true;
                                                    isDelete = true;
                                                    isSpecial1 = true;
                                                    bindDetailAmount = new BigDecimal(detail.getDetailAmount())
                                                        .add(new BigDecimal(speDetail.getDetailAmount()));
                                                    bindTaxAmount = new BigDecimal(detail.getTaxAmount())
                                                        .add(new BigDecimal(speDetail.getTaxAmount()));
                                                    bindTotalAmount = bindDetailAmount.add(bindTaxAmount);
                                                    map.put(speDetail.getTaxRate(), speDetail.getTaxRate());
                                                } else {
                                                    isBind = true;
                                                    isDelete = true;
                                                    isSpecial1 = true;
                                                    bindDetailAmount =
                                                        bindDetailAmount.add(new BigDecimal(detail.getDetailAmount()));
                                                    bindTaxAmount =
                                                        bindTaxAmount.add(new BigDecimal(detail.getTaxAmount()));
                                                    bindTotalAmount = bindDetailAmount.add(bindTaxAmount);
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                            if (isDelete) {
                                detailListByDbLast.remove(detail);
                            }

                        }

                    }
                    if (isSpecial1) {
                        boolean isSpecial = false;
                        // 继续走特殊流程
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        String taxRate = bindEntity.getTaxRate();
                        // 转换税率
                        if (!"免税".equals(taxRate) && !"不征税".equals(taxRate)) {
                            taxRate = new BigDecimal(bindEntity.getTaxRate()).multiply(new BigDecimal(100)).toString();
                            if (!"0".equals(taxRate)) {
                                taxRate = taxRate.substring(0, taxRate.indexOf(".00"));
                                if ("3".equals(taxRate) || "6".equals(taxRate)) {
                                    taxRate = taxRate + "%征收率";
                                }
                            }
                        }
                        int updateCount = allTaxesSaleDao.updateByRule(isAdd, bindEntity.getGoodsNum().substring(0, 1),
                            exchangeInvoiceType(po.getInvoiceType()), taxRate,
                            exchangeIncentiveFlag(bindEntity.getIncentiveFlag()), bindDetailAmount, bindTaxAmount,
                            bindTotalAmount, isSpecial);
                        log.info("销项汇总特殊流程: 更新" + updateCount + "条，");
                        detailListByDbLast.remove(bindEntity);
                        isAdd = true;
                    }
                    // 捆绑结束
                    // 正常流程汇总

                }
                normalLine(detailListByDbLast, isAdd, po, dbName);

            }
            // 汇总所有数据插入汇总记录表
            countAllData(dbName, belongDate, taxno);

        }
    }

    private boolean notAddTax(Map<String, String> map, String taxRate) {
        return !map.containsKey(taxRate);
    }

    private void countAllData(String dbName, String billingDate, String taxNumber) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        List<ItemPo> list = allTaxesSaleDao.findAllData();
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        for (ItemPo po : list) {
            po.setId(null);
            po.setBillingDate(billingDate);
            po.setTaxNumber(taxNumber);
            if ("专票".equals(po.getInvoiceType())) {
                po.setInvoiceType("0");
            } else {
                po.setInvoiceType("1");
            }
            po.setCreateDate(new Date());
            allTaxesSaleCountDao.insert(po);
        }
        allTaxesSaleDao.updateInit();
        allTaxesSaleDao.updateStatusByTaxNumberAndBill(taxNumber, billingDate, "0");

    }

    private void normalLine(List<SaleInvoiceDetailInfo> detailListByDb, boolean isAdd, SaleInvoicePo po,
        String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);

        for (SaleInvoiceDetailInfo detail : detailListByDb) {
            boolean isSpecial = false;
            String taxRate = detail.getTaxRate();
            // 转换税率
            if (!"免税".equals(taxRate) && !"不征税".equals(taxRate)) {
                taxRate = new BigDecimal(detail.getTaxRate()).multiply(new BigDecimal(100)).toString();
                if (!"0".equals(taxRate)) {
                    taxRate = taxRate.substring(0, taxRate.indexOf(".00"));
                    if ("3".equals(taxRate) || "6".equals(taxRate)) {
                        taxRate = taxRate + "%征收率";
                    }
                }
            }
            isSpecial = checkIsSpecial(exchangeIncentiveFlag(detail.getIncentiveFlag()), taxRate);
            BigDecimal detailAmount = new BigDecimal(detail.getDetailAmount());
            BigDecimal taxAmount = new BigDecimal(detail.getTaxAmount());
            BigDecimal totalAmount = detailAmount.add(taxAmount);
            int updateCount = allTaxesSaleDao.updateByRule(isAdd, detail.getGoodsNum().substring(0, 1),
                exchangeInvoiceType(po.getInvoiceType()), taxRate, exchangeIncentiveFlag(detail.getIncentiveFlag()),
                detailAmount, taxAmount, totalAmount, isSpecial);
            log.info("销项汇总正常流程: uuid:" + po.getUuid() + " 更新" + updateCount + "条，");
            isAdd = true;
        }

    }

    private boolean checkIsSpecial(String exchangeIncentiveFlag, String taxRate) {
        if ("非即征即退".equals(exchangeIncentiveFlag) && "6%征收率".equals(taxRate)) {
            return true;
        } else if ("非即征即退".equals(exchangeIncentiveFlag) && "4".equals(taxRate)) {
            return true;
        } else if ("即征即退".equals(exchangeIncentiveFlag) && "6%征收率".equals(taxRate)) {
            return true;
        } else if ("即征即退".equals(exchangeIncentiveFlag) && "4".equals(taxRate)) {
            return true;
        } else {
            return false;

        }
    }

    /**
     * 转换优惠政策
     *
     * @param incentiveFlag
     *            类型
     * @return 类型
     */
    private String exchangeIncentiveFlag(String incentiveFlag) {
        if (incentiveFlag != null) {
            if (incentiveFlag.contains("即征即退") && !"非即征即退".equals(incentiveFlag)) {
                return "即征即退";
            } else if (incentiveFlag.contains("免税")) {
                return "免税";
            } else if (incentiveFlag.contains("不征税")) {
                return "不征税";
            } else {
                return "非即征即退";
            }
        } else {
            return "非即征即退";
        }
    }

    /**
     * 转换发票类型
     *
     * @param invoiceType
     *            发票类型
     * @return 发票类型
     */
    private String exchangeInvoiceType(String invoiceType) {
        if ("01".equals(invoiceType) || "08".equals(invoiceType) ||"31".equals(invoiceType)) {
            return "专票";
        } else {
            return "其他发票";
        }
    }

    private List<String> getBelongByParam(String belongDate) {
        List<String> monthList = new ArrayList<>();
        // 判断是否为季度，包含Q
        if (!belongDate.contains("Q")) {
            monthList.add(belongDate);

        } else {
            // 截取季度的 年属性
            String allYear = belongDate.substring(0, belongDate.indexOf("Q"));
            // 截取季度的 月属性
            String allMonth = belongDate.substring(belongDate.indexOf("Q") + 1);
            if ("1".equals(allMonth)) {
                monthList.add(allYear.concat("01"));
                monthList.add(allYear.concat("02"));
                monthList.add(allYear.concat("03"));
            }
            if ("2".equals(allMonth)) {
                monthList.add(allYear.concat("04"));
                monthList.add(allYear.concat("05"));
                monthList.add(allYear.concat("06"));
            }
            if ("3".equals(allMonth)) {
                monthList.add(allYear.concat("07"));
                monthList.add(allYear.concat("08"));
                monthList.add(allYear.concat("09"));
            }
            if ("4".equals(allMonth)) {
                monthList.add(allYear.concat("10"));
                monthList.add(allYear.concat("11"));
                monthList.add(allYear.concat("12"));
            }

        }
        return monthList;
    }

    @Override
    public String getInvoiceSaleTaxRateCount(List<ReqSaleCountInfo> reqList) {
        SaleTaxRateReturnCount returnInfo = new SaleTaxRateReturnCount();
        List<SaleTaxRateData> saleItemDataList = new ArrayList<>();
        String dbName;
        try {
            for (ReqSaleCountInfo info : reqList) {
                List<SummarySaleTaxRateData> list = new ArrayList<>();
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(info.getTaxNumber());
                SaleTaxRateData data = new SaleTaxRateData();
                if (deptInfo != null) {
                    // 主体数据入库标识
                    dbName = deptInfo.getString("db_name");
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    list = allTaxesSaleDao.getTaxRateCount(info.getBillingDate(), info.getTaxNumber());
                    if (list != null) {
                        data.setSummaryData(list);
                        data.setTaxNumber(info.getTaxNumber());
                        data.setBillingDate(info.getBillingDate());
                        saleItemDataList.add(data);
                    }
                } else {
                    data.setSummaryData(list);
                    data.setTaxNumber(info.getTaxNumber());
                    data.setBillingDate(info.getBillingDate());
                    saleItemDataList.add(data);
                }

            }
            returnInfo.setInformType("1");
            returnInfo.setData(saleItemDataList);
            returnInfo.setCode("0000");
            returnInfo.setMessage("获取成功");
            return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            e.printStackTrace();
            returnInfo.setCode("0001");
            returnInfo.setMessage("获取失败");
            returnInfo.setData(null);
            return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
        }
    }

    @Override
    public String getInvoiceSaleItemCount(List<ReqSaleCountInfo> reqList) {
        SaleItemReturnCount returnInfo = new SaleItemReturnCount();
        List<SaleItemData> saleItemDataList = new ArrayList<>();
        String dbName;
        try {
            for (ReqSaleCountInfo info : reqList) {
                List<SummarySaleItemData> list = new ArrayList<>();
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                JSONObject deptInfo = allTaxesSaleDao.getBlocInfoBytaxNo(info.getTaxNumber());
                SaleItemData data = new SaleItemData();
                if (deptInfo != null) {
                    // 主体数据入库标识
                    dbName = deptInfo.getString("db_name");
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    list = allTaxesSaleDao.getItemCount(info.getBillingDate(), info.getTaxNumber());
                    if (list != null) {
                        data.setSummaryData(list);
                        data.setTaxNumber(info.getTaxNumber());
                        data.setBillingDate(info.getBillingDate());
                        saleItemDataList.add(data);
                    }
                } else {
                    data.setSummaryData(list);
                    data.setTaxNumber(info.getTaxNumber());
                    data.setBillingDate(info.getBillingDate());
                    saleItemDataList.add(data);
                }

            }
            returnInfo.setInformType("2");
            returnInfo.setData(saleItemDataList);
            returnInfo.setCode("0000");
            returnInfo.setMessage("拉取成功");
            return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            e.printStackTrace();
            returnInfo.setCode("0001");
            returnInfo.setMessage("拉取失败");
            returnInfo.setData(null);
            return JSONObject.toJSONString(returnInfo, SerializerFeature.WriteMapNullValue);
        }
    }
}
