package com.dxhy.manage.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.dxhy.manage.model.BlocDataModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.manage.dao.SellersStatDao;
import com.dxhy.manage.entity.SysDeptEntity;
import com.dxhy.manage.model.BlocNumModel;
import com.dxhy.manage.model.CollectNumModel;
import com.dxhy.manage.service.SellersStatService;

/**
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("sellersStatService")
public class SellersStatServiceImpl extends MpBaseServiceImpl<SellersStatDao, SysDeptEntity>
    implements SellersStatService {

    @Resource
    private EasyExcelUtil excelUtil;

    @Override
    public List<SysDeptEntity> queryList(String userId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryList(userId);
    }

    @Override
    public List<SysDeptEntity> queryTaxnoList(String deptId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryTaxnoList(deptId);
    }

    @Override
    public PageUtils queryTotal(Map<String, String> params) {

        // 根据集团id和税号
        String company = params.get("company");
        String taxno = params.get("taxno");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        List<CollectNumModel> totalList = new ArrayList<>();
        List<SysDeptEntity> taxnos;
        List<SysDeptEntity> sbList;
        List<SysDeptEntity> lastTaxnos = null;
        // 通过deptid获取分库信息
        if (taxno.length() > 0 && !"99".equals(taxno)) {
            // 单独查询一个税号的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String database = baseMapper.getDataBase(company);
            SysDeptEntity entity = baseMapper.getTaxNameByTaxno(taxno);
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            taxnos = new ArrayList<>();
            lastTaxnos = new ArrayList<>();
            lastTaxnos.add(entity);
            taxnos.add(entity);
            totalList = getTaxnoTotal(taxnos, beginDate, endDate);
        } else if ("99".equals(taxno)) {
            // 查询一个集团的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 查询集团所属分库
            String database = baseMapper.getDataBase(company);
            // 对于税号需要拆分
            taxnos = baseMapper.getSysDept(company);
            lastTaxnos = baseMapper.getSysDept(company);
            // 设置每次多少条数据
            int perCount = 100;
            // 默认0
            int index = 0;
            // 遍历次数
            int times = taxnos.size() / perCount;
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            for (index = 0; index <= times; index++) {
                if (taxnos.size() >= perCount) {
                    sbList = taxnos.subList(0, perCount);
                    // 汇总税号的采集数量
                    List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                    totalList.addAll(list);
                    taxnos.removeAll(sbList);
                } else {
                    if (taxnos.size() != 0) {
                        sbList = taxnos.subList(0, taxnos.size());
                        // 汇总税号的采集数量
                        List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                        totalList.addAll(list);
                        taxnos.removeAll(sbList);
                    }
                }
            }

        }
        List<CollectNumModel> lastList = new ArrayList<>();
        int order = 1;
        // 拼凑需要返回的字段 税号，企业名称，采集数量
        assert lastTaxnos != null;
        for (SysDeptEntity model : lastTaxnos) {
            CollectNumModel collectNumModel = new CollectNumModel();
            collectNumModel.setTaxno(model.getTaxno());
            collectNumModel.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(model.getCreateDate()));
            collectNumModel.setTaxname(model.getTaxname());
            String num = "0";
            for (CollectNumModel collect : totalList) {
                if (model.getTaxno().equals(collect.getTaxno())) {
                    num = collect.getNum();
                }
            }
            collectNumModel.setNum(num);
            collectNumModel.setOrder(order + "");
            lastList.add(collectNumModel);
            order = order + 1;
        }

        return new PageUtils(lastList, lastTaxnos.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    /**
     * 根据税号获取采集总数
     *
     * @param sbList
     * @param beginDate
     * @param endDate
     * @return
     */
    private List<CollectNumModel> getTaxnoTotal(List<SysDeptEntity> sbList, String beginDate, String endDate) {
        return baseMapper.getCollectNumByTaxno(sbList, beginDate, endDate);
    }

    @Override
    public void exportExcel(Map<String, String> params, HttpServletResponse response) {
        String timeType = params.get("timeType");
        String confirmType = params.get("confirmType");
        PageUtils page = null;
        if ("0".equals(timeType) && "".equals(confirmType)) {
            page = queryTotal(params);
        } else if ("0".equals(timeType)) {
            page = queryConfirmTotal(params);
        } else if ("1".equals(timeType)) {
            page = queryYear(params);
        } else if ("2".equals(timeType)) {
            page = queryMonth(params);
        }
        try {
            if ("1".equals(timeType) || "2".equals(timeType)) {
                excelUtil.writeExcel(response, page.getList(), "Stat" + System.currentTimeMillis(), "sheet1",
                    BlocNumModel.class);
            } else {
                assert page != null;
                excelUtil.writeExcel(response, page.getList(), "Stat" + System.currentTimeMillis(), "sheet1",
                    CollectNumModel.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public JSONObject getTitle() {
        JSONObject json = new JSONObject();
        String[] titlelist = {"序号", "税号", "企业名称", "票量", "配置时间"};
        String[] titleprop = {"order", "taxno", "taxname", "num", "createDate"};
        // 需要设置返回列表标题时调用
        json = super.setTitleList(titlelist, titleprop);
        return json;
    }

    /**
     * 按集团维度进行年度统计
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryYear(Map<String, String> params) {
        String taxname = params.get("taxname");
        String company = params.get("company");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String confirmType = params.get("confirmType");
        // 年度，分年合计 --由于需要拆分税号合计，所以不能一次性查出结果，需要进行拼接
        List<String> years = getYearDate(beginDate, endDate, "yyyy");

        List<BlocNumModel> totalList = new ArrayList<>();
        // 查询一个集团的
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 查询集团所属分库
        String database = baseMapper.getDataBase(company);
        List<String> dept = baseMapper.queryAllTable(company);
        int order = 1;
        // 根据年度进行汇总合计
        for (String year : years) {
            BlocNumModel totalModel = new BlocNumModel();
            totalModel.setYearDate(year);
            totalModel.setCount("0");
            totalModel.setCompany(company);
            totalModel.setTaxname(taxname);
            totalModel.setOrder(order + "");
            order = order + 1;
            // 遍历集团分表情况
            for (String table : dept) {
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                // 对于税号需要拆分 根据集团下不同分表取税号
                List<String> taxnos = baseMapper.getTaxnoes(company, table);
                // 设置每次多少条数据
                int perCount = 100;
                // 默认0
                int index = 0;
                // 遍历次数
                int times = taxnos.size() / perCount;
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                for (index = 0; index <= times; index++) {
                    List<String> sbList = null;
                    if (taxnos.size() >= perCount) {
                        sbList = taxnos.subList(0, perCount);
                        // 汇总税号的采集数量
                        BlocNumModel model = getTaxnoYearTotal(sbList, beginDate, endDate, year, confirmType);
                        if (model != null) {
                            totalModel.setCount(
                                new BigDecimal(totalModel.getCount()).add(new BigDecimal(model.getCount())).toString());
                        }
                        taxnos.removeAll(sbList);
                    } else {
                        if (taxnos.size() != 0) {
                            sbList = taxnos.subList(0, taxnos.size());
                            // 汇总税号的采集数量
                            BlocNumModel model = getTaxnoYearTotal(sbList, beginDate, endDate, year, confirmType);
                            if (model != null) {
                                totalModel.setCount(new BigDecimal(totalModel.getCount())
                                    .add(new BigDecimal(model.getCount())).toString());
                            }
                            taxnos.removeAll(sbList);
                        }
                    }
                }
            }

            totalList.add(totalModel);
        }
        return new PageUtils(totalList, totalList.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    private BlocNumModel getTaxnoYearTotal(List<String> sbList, String beginDate, String endDate, String year,
        String confirmType) {
        // 判断confirmType是否有值， 有的话查询认证的，没有的话查询采集的
        if (StringUtils.isNotBlank(confirmType)) {
            // 返回认证票量
            beginDate = getExchangeDate(beginDate);
            endDate = getExchangeDate(endDate);
            return baseMapper.getTaxnoYearConfirmTotalByBelong(sbList, beginDate, endDate, year);

        } else {
            // 返回采集票量
            return baseMapper.getTaxnoYearTotal(sbList, beginDate, endDate, year);
        }

    }

    /**
     * 通过时间段生成年度时间集合
     *
     * @param beginDate
     * @param endDate
     * @param format
     * @return
     */
    private List<String> getYearDate(String beginDate, String endDate, String format) {
        // 返回的日期集合
        List<String> days = new ArrayList<>();

        DateFormat dateFormat = new SimpleDateFormat(format);
        try {
            Date start = dateFormat.parse(beginDate);
            Date end = dateFormat.parse(endDate);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.YEAR, +1);
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 通过时间段生成年度时间集合
     *
     * @param beginDate
     * @param endDate
     * @param format
     *            yyyy-MM
     * @return
     */
    private List<String> getMonthDate(String beginDate, String endDate, String format) {
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(sdf.parse(beginDate));

            c2.setTime(sdf.parse(endDate));
            int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
            int month = c2.get(Calendar.MONTH) + year * 12 - c1.get(Calendar.MONTH);
            for (int i = 0; i <= month; i++) {
                c1.setTime(sdf.parse(beginDate));
                c1.add(Calendar.MONTH, i);
                list.add(sdf.format(c1.getTime()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 统计集团按月份汇总
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryMonth(Map<String, String> params) {
        String taxname = params.get("taxname");
        String company = params.get("company");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String confirmType = params.get("confirmType");
        // 年度，分年合计 --由于需要拆分税号合计，所以不能一次性查出结果，需要进行拼接
        List<String> years = getMonthDate(beginDate, endDate, "yyyy-MM");

        List<BlocNumModel> totalList = new ArrayList<>();
        // 查询一个集团的
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 查询集团所属分库
        String database = baseMapper.getDataBase(company);
        List<String> dept = baseMapper.queryAllTable(company);
        // 根据年度进行汇总合计
        int order = 1;
        for (String year : years) {
            BlocNumModel totalModel = new BlocNumModel();
            totalModel.setYearDate(year);
            totalModel.setCount("0");
            totalModel.setCompany(company);
            totalModel.setOrder(order + "");
            totalModel.setTaxname(taxname);
            order = order + 1;
            // 遍历集团分表情况
            for (String table : dept) {
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                // 对于税号需要拆分 根据集团下不同分表取税号
                List<String> taxnos = baseMapper.getTaxnoes(company, table);
                // 设置每次多少条数据
                int perCount = 100;
                // 默认0
                int index = 0;
                // 遍历次数
                int times = taxnos.size() / perCount;
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                for (index = 0; index <= times; index++) {
                    List<String> sbList = null;
                    if (taxnos.size() >= perCount) {
                        sbList = taxnos.subList(0, perCount);
                        // 汇总税号的采集数量
                        BlocNumModel model = getTaxnoMonthTotal(sbList, beginDate, endDate, year, confirmType);
                        if (model != null) {
                            totalModel.setCount(
                                new BigDecimal(totalModel.getCount()).add(new BigDecimal(model.getCount())).toString());
                        }
                        taxnos.removeAll(sbList);
                    } else {
                        if (taxnos.size() != 0) {
                            sbList = taxnos.subList(0, taxnos.size());
                            // 汇总税号的采集数量
                            BlocNumModel model = getTaxnoMonthTotal(sbList, beginDate, endDate, year, confirmType);
                            if (model != null) {
                                totalModel.setCount(new BigDecimal(totalModel.getCount())
                                    .add(new BigDecimal(model.getCount())).toString());
                            }
                            taxnos.removeAll(sbList);
                        }
                    }
                }
            }

            totalList.add(totalModel);
        }
        return new PageUtils(totalList, totalList.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    private BlocNumModel getTaxnoMonthTotal(List<String> sbList, String beginDate, String endDate, String month,
        String confirmType) {

        // 判断confirmType是否有值， 有的话查询认证的，没有的话查询采集的
        if (StringUtils.isNotBlank(confirmType)) {
            // 认证属期 转换字符串
            beginDate = getExchangeDate(beginDate);
            endDate = getExchangeDate(endDate);
            month = getExchangeDate(month);
            return baseMapper.getTaxnoMonthConfirmTotalByBelong(sbList, beginDate, endDate, month);

        } else {
            return baseMapper.getTaxnoMonthTotal(sbList, beginDate, endDate, month);
        }
    }

    private String getExchangeDate(String dateStr) {
        return dateStr.replace("-", "").substring(0, 6);
    }

    @Override
    public JSONObject getYearTitle() {
        JSONObject json = new JSONObject();
        String[] titlelist = {"序号", "集团编码", "集团名称", "年份", "票量"};
        String[] titleprop = {"order", "company", "taxname", "yearDate", "count"};
        // 需要设置返回列表标题时调用
        json = super.setTitleList(titlelist, titleprop);
        return json;
    }

    @Override
    public JSONObject getMonthTitle() {
        JSONObject json = new JSONObject();
        String[] titlelist = {"序号", "集团编码", "集团名称", "月份", "票量"};
        String[] titleprop = {"order", "company", "taxname", "yearDate", "count"};
        // 需要设置返回列表标题时调用
        json = super.setTitleList(titlelist, titleprop);
        return json;
    }

    /**
     * 认证量查询方法
     *
     * @param sbList
     * @param beginDate
     * @param endDate
     * @param confirmType
     * @return
     */
    private List<CollectNumModel> getTaxnoConfirmTotal(List<SysDeptEntity> sbList, String beginDate, String endDate,
        String confirmType) {
        List<CollectNumModel> confirmList = new ArrayList<>();
        beginDate = getExchangeDate(beginDate);
        endDate = getExchangeDate(endDate);
        for (SysDeptEntity s : sbList) {
            CollectNumModel model = baseMapper.getConfirmTotalByDateTaxno(s, beginDate, endDate);
            if (model == null) {
                model = new CollectNumModel();
                model.setTaxno(s.getTaxno());
                model.setNum("0");
            }
            confirmList.add(model);
        }
        return confirmList;

    }

    /**
     * 根据税号分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryResultPage(Map<String, String> params) {

        // 根据集团id和税号
        String company = params.get("company");
        String taxno = params.get("taxno");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        int pageSize = Integer.parseInt(params.get("size"));
        int curr = Integer.parseInt(params.get("curr"));
        List<CollectNumModel> totalList = new ArrayList<>();
        List<SysDeptEntity> taxnos = null;
        List<SysDeptEntity> sbList = new ArrayList<>();
        // 通过deptid获取分库信息
        if (taxno.length() > 0 && !"99".equals(taxno)) {
            // 单独查询一个税号的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String database = baseMapper.getDataBase(company);
            SysDeptEntity entity = baseMapper.getTaxNameByTaxno(taxno);
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            taxnos = new ArrayList<>();
            sbList.add(entity);
            taxnos.add(entity);
            totalList = getTaxnoTotal(taxnos, beginDate, endDate);

        } else if ("99".equals(taxno)) {
            // 查询一个集团的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 查询集团所属分库
            String database = baseMapper.getDataBase(company);
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 对于税号需要拆分
            taxnos = baseMapper.getSysDept(company);
            // 设置每次多少条数据
            int perCount = Integer.parseInt(params.get("size"));
            // 默认0
            int index = (curr - 1) * pageSize;
            //为防止分页从整个集团切换到单个集团，判断一下
            if(index>=taxnos.size()){
                index =0;
                curr = 1;
                params.put("curr","1");
            }
            int totalSize = perCount * curr;
            perCount = Math.min(totalSize, taxnos.size());
            if (taxnos.size() >= perCount) {
                sbList = taxnos.subList(index, perCount);
                // 汇总税号的采集数量
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                totalList.addAll(list);
            } else {
                if (taxnos.size() != 0) {
                    sbList = taxnos.subList(0, taxnos.size());
                    // 汇总税号的采集数量
                    DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                    List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                    totalList.addAll(list);
                }
            }
        }
        List<CollectNumModel> lastList = new ArrayList<>();
        int order = 1;
        // 拼凑需要返回的字段 税号，企业名称，采集数量
        for (SysDeptEntity model : sbList) {
            CollectNumModel collectNumModel = new CollectNumModel();
            collectNumModel.setTaxno(model.getTaxno());
            collectNumModel.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(model.getCreateDate()));
            collectNumModel.setTaxname(model.getTaxname());
            String num = "0";
            for (CollectNumModel collect : totalList) {
                if (model.getTaxno().equals(collect.getTaxno())) {
                    num = collect.getNum();
                }
            }
            collectNumModel.setNum(num);
            collectNumModel.setOrder(order + "");
            lastList.add(collectNumModel);
            order = order + 1;
        }

        return new PageUtils(lastList, taxnos.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));

    }

    /**
     * 调整分页
     */
    @Override
    public PageUtils queryYearPage(Map<String, String> params) {
        String taxname = params.get("taxname");
        String company = params.get("company");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String confirmType = params.get("confirmType");
        // 年度，分年合计 --由于需要拆分税号合计，所以不能一次性查出结果，需要进行拼接
        List<String> years = getYearDate(beginDate, endDate, "yyyy");
        List<BlocNumModel> totalList = new ArrayList<>();
        // 查询一个集团的
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 查询集团所属分库
        String database = baseMapper.getDataBase(company);
        List<String> dept = baseMapper.queryAllTable(company);
        List<String> sbYearList = setPageList(years, params);
        int order = 1;
        // 根据年度进行汇总合计
        for (String year : sbYearList) {

            BlocNumModel totalModel = new BlocNumModel();
            totalModel.setYearDate(year);
            totalModel.setCount("0");
            totalModel.setCompany(company);
            totalModel.setTaxname(taxname);
            totalModel.setOrder(order + "");
            order = order + 1;
            // 遍历集团分表情况
            for (String table : dept) {
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                // 对于税号需要拆分 根据集团下不同分表取税号
                List<String> taxnos = baseMapper.getTaxnoes(company, table);
                // 设置每次多少条数据
                int perCount = 100;
                // 默认0
                int index = 0;
                // 遍历次数
                int times = taxnos.size() / perCount;
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                for (index = 0; index <= times; index++) {
                    List<String> sbList = null;
                    if (taxnos.size() >= perCount) {
                        sbList = taxnos.subList(0, perCount);
                        // 汇总税号的采集数量
                        BlocNumModel model = getTaxnoYearTotal(sbList, beginDate, endDate, year, confirmType);
                        if (model != null) {
                            totalModel.setCount(
                                new BigDecimal(totalModel.getCount()).add(new BigDecimal(model.getCount())).toString());
                        }
                        taxnos.removeAll(sbList);
                    } else {
                        if (taxnos.size() != 0) {
                            sbList = taxnos.subList(0, taxnos.size());
                            // 汇总税号的采集数量
                            BlocNumModel model = getTaxnoYearTotal(sbList, beginDate, endDate, year, confirmType);
                            if (model != null) {
                                totalModel.setCount(new BigDecimal(totalModel.getCount())
                                    .add(new BigDecimal(model.getCount())).toString());
                            }
                            taxnos.removeAll(sbList);
                        }
                    }
                }
            }

            totalList.add(totalModel);
        }
        return new PageUtils(totalList, years.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    /**
     * 设置分页
     *
     * @param years
     * @param params
     * @return
     */
    private List<String> setPageList(List<String> years, Map<String, String> params) {
        int curr = Integer.parseInt(params.get("curr"));
        int size = Integer.parseInt(params.get("size"));
        // 设置每次多少条数据
        int perCount = size;
        int index = (curr - 1) * size;
        int totalSize = perCount * curr;
        perCount = Math.min(totalSize, years.size());
        List<String> sbList = null;
        if (years.size() >= perCount) {
            sbList = years.subList(index, perCount);
        } else {
            if (years.size() != 0) {
                sbList = years.subList(0, years.size());
            }
        }
        return sbList;
    }

    /**
     * 认证票量查询 认证属期， 认证时间
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryConfirmTotalPage(Map<String, String> params) {

        // 根据集团id和税号
        String company = params.get("company");
        String taxno = params.get("taxno");
        String beginDate = params.get("beginDate");
        String confirmType = params.get("confirmType");
        String endDate = params.get("endDate");
        int pageSize = Integer.parseInt(params.get("size"));
        int curr = Integer.parseInt(params.get("curr"));
        List<CollectNumModel> totalList = new ArrayList<>();
        List<SysDeptEntity> taxnos = null;
        List<SysDeptEntity> sbList = new ArrayList<>();
        // 通过deptid获取分库信息
        if (taxno.length() > 0 && !"99".equals(taxno)) {
            // 单独查询一个税号的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String database = baseMapper.getDataBase(company);
            SysDeptEntity entity = baseMapper.getTaxNameByTaxno(taxno);
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            taxnos = new ArrayList<>();
            sbList.add(entity);
            taxnos.add(entity);
            totalList = getTaxnoConfirmTotal(taxnos, beginDate, endDate, confirmType);

        } else if ("99".equals(taxno)) {
            // 查询一个集团的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 查询集团所属分库
            String database = baseMapper.getDataBase(company);
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 对于税号需要拆分
            taxnos = baseMapper.getSysDept(company);
            // 设置每次多少条数据
            int perCount = Integer.parseInt(params.get("size"));
            // 默认0
            int index = (curr - 1) * pageSize;
            int totalSize = perCount * curr;
            perCount = Math.min(totalSize, taxnos.size());
            if (taxnos.size() >= perCount) {
                sbList = taxnos.subList(index, perCount);
                // 汇总税号的采集数量
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                totalList.addAll(list);
            } else {
                if (taxnos.size() != 0) {
                    sbList = taxnos.subList(0, taxnos.size());
                    // 汇总税号的采集数量
                    DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                    List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                    totalList.addAll(list);
                }
            }
        }
        List<CollectNumModel> lastList = new ArrayList<>();
        int order = 1;
        // 拼凑需要返回的字段 税号，企业名称，采集数量
        for (SysDeptEntity model : sbList) {
            CollectNumModel collectNumModel = new CollectNumModel();
            collectNumModel.setTaxno(model.getTaxno());
            collectNumModel.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(model.getCreateDate()));
            collectNumModel.setTaxname(model.getTaxname());
            String num = "0";
            for (CollectNumModel collect : totalList) {
                if (model.getTaxno().equals(collect.getTaxno())) {
                    num = collect.getNum();
                }
            }
            collectNumModel.setNum(num);
            collectNumModel.setOrder(order + "");
            lastList.add(collectNumModel);
            order = order + 1;
        }

        return new PageUtils(lastList, taxnos.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    @Override
    public PageUtils queryConfirmTotal(Map<String, String> params) {
        // 根据集团id和税号
        String company = params.get("company");
        String taxno = params.get("taxno");
        String beginDate = params.get("beginDate");
        String confirmType = params.get("confirmType");
        String endDate = params.get("endDate");
        List<CollectNumModel> totalList = new ArrayList<>();
        List<SysDeptEntity> taxnos;
        List<SysDeptEntity> lastTaxnos = null;
        List<SysDeptEntity> sbList = new ArrayList<>();
        // 通过deptid获取分库信息
        if (taxno.length() > 0 && !"99".equals(taxno)) {
            // 单独查询一个税号的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String database = baseMapper.getDataBase(company);
            SysDeptEntity entity = baseMapper.getTaxNameByTaxno(taxno);
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            taxnos = new ArrayList<>();
            lastTaxnos = new ArrayList<>();
            lastTaxnos.add(entity);
            sbList.add(entity);
            taxnos.add(entity);
            totalList = getTaxnoConfirmTotal(taxnos, beginDate, endDate, confirmType);

        } else if ("99".equals(taxno)) {
            // 查询一个集团的
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            // 查询集团所属分库
            String database = baseMapper.getDataBase(company);
            // 对于税号需要拆分
            taxnos = baseMapper.getSysDept(company);
            lastTaxnos = baseMapper.getSysDept(company);
            // 设置每次多少条数据
            int perCount = 100;
            // 默认0
            int index = 0;
            // 遍历次数
            int times = taxnos.size() / perCount;
            DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
            for (index = 0; index <= times; index++) {
                if (taxnos.size() >= perCount) {
                    sbList = taxnos.subList(0, perCount);
                    // 汇总税号的采集数量
                    DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                    List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                    totalList.addAll(list);
                    taxnos.removeAll(sbList);
                } else {
                    if (taxnos.size() != 0) {
                        sbList = taxnos.subList(0, taxnos.size());
                        // 汇总税号的采集数量
                        DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                        List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                        totalList.addAll(list);
                        taxnos.removeAll(sbList);
                    }
                }
            }
        }
        List<CollectNumModel> lastList = new ArrayList<>();
        int order = 1;
        // 拼凑需要返回的字段 税号，企业名称，采集数量
        assert lastTaxnos != null;
        for (SysDeptEntity model : lastTaxnos) {
            CollectNumModel collectNumModel = new CollectNumModel();
            collectNumModel.setTaxno(model.getTaxno());
            collectNumModel.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(model.getCreateDate()));
            collectNumModel.setTaxname(model.getTaxname());
            String num = "0";
            for (CollectNumModel collect : totalList) {
                if (model.getTaxno().equals(collect.getTaxno())) {
                    num = collect.getNum();
                }
            }
            collectNumModel.setNum(num);
            collectNumModel.setOrder(order + "");
            lastList.add(collectNumModel);
            order = order + 1;
        }

        return new PageUtils(lastList, lastTaxnos.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    /**
     * 统计集团按月份汇总
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryMonthPage(Map<String, String> params) {
        String taxname = params.get("taxname");
        String company = params.get("company");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String confirmType = params.get("confirmType");
        // 年度，分年合计 --由于需要拆分税号合计，所以不能一次性查出结果，需要进行拼接
        List<String> years = getMonthDate(beginDate, endDate, "yyyy-MM");

        List<BlocNumModel> totalList = new ArrayList<>();
        // 查询一个集团的
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 查询集团所属分库
        String database = baseMapper.getDataBase(company);
        List<String> dept = baseMapper.queryAllTable(company);
        // 根据年度进行汇总合计
        int order = 1;
        List<String> monthList = setPageList(years, params);
        for (String year : monthList) {
            BlocNumModel totalModel = new BlocNumModel();
            totalModel.setYearDate(year);
            totalModel.setCount("0");
            totalModel.setCompany(company);
            totalModel.setOrder(order + "");
            totalModel.setTaxname(taxname);
            order = order + 1;
            // 遍历集团分表情况
            for (String table : dept) {
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                // 对于税号需要拆分 根据集团下不同分表取税号
                List<String> taxnos = baseMapper.getTaxnoes(company, table);
                // 设置每次多少条数据
                int perCount = 100;
                // 默认0
                int index = 0;
                // 遍历次数
                int times = taxnos.size() / perCount;
                DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
                for (index = 0; index <= times; index++) {
                    List<String> sbList = null;
                    if (taxnos.size() >= perCount) {
                        sbList = taxnos.subList(0, perCount);
                        // 汇总税号的采集数量
                        BlocNumModel model = getTaxnoMonthTotal(sbList, beginDate, endDate, year, confirmType);
                        if (model != null) {
                            totalModel.setCount(
                                new BigDecimal(totalModel.getCount()).add(new BigDecimal(model.getCount())).toString());
                        }
                        taxnos.removeAll(sbList);
                    } else {
                        if (taxnos.size() != 0) {
                            sbList = taxnos.subList(0, taxnos.size());
                            // 汇总税号的采集数量
                            BlocNumModel model = getTaxnoMonthTotal(sbList, beginDate, endDate, year, confirmType);
                            if (model != null) {
                                totalModel.setCount(new BigDecimal(totalModel.getCount())
                                    .add(new BigDecimal(model.getCount())).toString());
                            }
                            taxnos.removeAll(sbList);
                        }
                    }
                }
            }

            totalList.add(totalModel);
        }
        return new PageUtils(totalList, years.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
    }

    /**
     * 每个集团汇总采集发票总量，税号数量
     *
     * @param sysDeptEntity
     * @param params
     * @return
     */
    @Override
    public BlocDataModel getBlocData(SysDeptEntity sysDeptEntity, Map<String, String> params) {
        BlocDataModel model = new BlocDataModel();
        List<CollectNumModel> totalList = new ArrayList<>();
        List<SysDeptEntity> taxnos;
        List<SysDeptEntity> sbList = new ArrayList<>();
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String confirmType = params.get("confirmType");
        model.setCompany(sysDeptEntity.getCompany());
        model.setTaxname(sysDeptEntity.getTaxname());
        // 获取该集团下税号数量
        // 查询一个集团的
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        int taxnoCount = baseMapper.getTaxnoesCount(sysDeptEntity.getCompany());
        model.setTaxnoCount(taxnoCount + "");

        // 获取集团采集总数量 根据集团company获取税号
        String company = sysDeptEntity.getCompany();
        // 查询集团所属分库
        String database = baseMapper.getDataBase(company);
        // 对于税号需要拆分
        taxnos = baseMapper.getSysDept(company);
        // 设置每次多少条数据
        int perCount = 100;
        // 默认0
        int index = 0;
        // 遍历次数
        int times = taxnos.size() / perCount;
        DynamicContextHolder.push(database + DbConstant.BUSINESS_READ);
        for (index = 0; index <= times; index++) {
            if (taxnos.size() >= perCount) {
                sbList = taxnos.subList(0, perCount);
                if ("".equals(confirmType)) {
                    List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                    totalList.addAll(list);
                    taxnos.removeAll(sbList);
                }
                if ("1".equals(confirmType)) {
                    List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                    totalList.addAll(list);
                    taxnos.removeAll(sbList);
                }

            } else {
                if (taxnos.size() != 0) {
                    sbList = taxnos.subList(0, taxnos.size());
                    if ("".equals(confirmType)) {
                        List<CollectNumModel> list = getTaxnoTotal(sbList, beginDate, endDate);
                        totalList.addAll(list);
                        taxnos.removeAll(sbList);
                    }
                    if ("1".equals(confirmType)) {
                        List<CollectNumModel> list = getTaxnoConfirmTotal(sbList, beginDate, endDate, confirmType);
                        totalList.addAll(list);
                        taxnos.removeAll(sbList);
                    }
                }
            }
        }
        int count = 0;
        for (CollectNumModel collectNumModel : totalList) {
            if (StringUtils.isNotEmpty(collectNumModel.getNum())) {
                count = count + Integer.parseInt(collectNumModel.getNum());
            }
        }
        model.setCount(count + "");
        return model;
    }

    @Override
    public JSONObject getBlocTitle() {
        JSONObject json = new JSONObject();
        String[] titlelist = {"序号", "集团编码", "集团名称", "税号数量", "票量"};
        String[] titleprop = {"order", "company", "taxname", "taxnoCount", "count"};
        // 需要设置返回列表标题时调用
        json = super.setTitleList(titlelist, titleprop);
        return json;
    }
}
