package com.dxhy.extend.service.bb.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.extend.dao.ExtIndexStatisticsMapper;
import com.dxhy.extend.entity.*;
import com.dxhy.extend.service.bb.ExtIndexStatisticsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.IntStream;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @author Bobby
 * @date 2018/4/16 首页-业务
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("indexStatisticsService")
@Slf4j

public class ExtIndexStatisticsServiceImpl implements ExtIndexStatisticsService {

    @Resource
    private ExtIndexStatisticsMapper indexStatisticsMapper;

    @Override
    public Integer getOrgType(List<String> orgs) {
        return indexStatisticsMapper.getOrgType(orgs);
    }

    @Override
    public List<ExtIndexInvoiceCollectionCountModel> getInvoiceCollectionSituationMap(Map<String, Object> pramsMap) {
        log.info("获取今日采集情况,params:{}", pramsMap);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        Map<String, BigDecimal> map = indexStatisticsMapper.getInvoiceCollectionSituationMap(pramsMap);
        final List<ExtIndexInvoiceCollectionCountModel> modelList = newArrayList();
        if (map == null) {
            final Map<String, BigDecimal> enMap = Maps.newHashMapWithExpectedSize(6);
            //01专票
            enMap.put("zpInvoiceCount", new BigDecimal("0"));
            // 03机动车
            enMap.put("jdcInvoiceCount", new BigDecimal("0"));
            //14通行费
            enMap.put("txfInvoiceCount", new BigDecimal("0"));
            //未补明细
            enMap.put("wbmxInvoiceCount", new BigDecimal("0"));
            //08电专
            enMap.put("dzzpInvoiceCount", new BigDecimal("0"));
            //31全电专
            enMap.put("qdzInvoiceCount", new BigDecimal("0"));
            //// 32全电普
            //enMap.put("qdpInvoiceCount", new BigDecimal("0"));
            //283电子客票
            enMap.put("dzkpInvoiceCount", new BigDecimal("0"));
            // 161行程单
            enMap.put("xcdInvoiceCount", new BigDecimal("0"));
            // 183机动车(电)
            enMap.put("jdcdzInvoiceCount", new BigDecimal("0"));
            // 185全电纸专
            enMap.put("qdzzInvoiceCount", new BigDecimal("0"));
            map = enMap;
        }

        Map<String, BigDecimal> customsMap = indexStatisticsMapper.getCustomsCollectionSituationMap(pramsMap);
        if (customsMap == null) {
            map.put("jksInvoiceCount", new BigDecimal("0"));
        } else {
            map.put("jksInvoiceCount", customsMap.get("jksInvoiceCount"));
        }
        Map<String, BigDecimal> finalMap = map;
        finalMap.keySet().forEach(key -> {
            final ExtIndexInvoiceCollectionCountModel model = new ExtIndexInvoiceCollectionCountModel();
            model.setInvoiceType(key);
            model.setCountNum(finalMap.get(key).intValue());
            modelList.add(model);
        });

        return modelList;
    }

    @Override
    public Map<String, Object> getInvoiceScanningSituation(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        log.info("今日发票扫描情况,params {}", pramsMap);
        List<ExtIndexInvoiceScanningCountModel> list = indexStatisticsMapper.getInvoiceScanningSituation(pramsMap);
        log.info("今日缴款书扫描情况,params {}", pramsMap);
        List<ExtIndexInvoiceScanningCountModel> list1 = indexStatisticsMapper.getCustomsScanningSituation(pramsMap);
        int wqsNum = 0;
        int yqsNum = 0;
        int totalNum = 0;
        for (ExtIndexInvoiceScanningCountModel model : list) {
            if ("wqsCount".equals(model.getQsType())) {
                wqsNum = wqsNum + model.getCountNum();
            }
            if ("yqsCount".equals(model.getQsType())) {
                yqsNum = yqsNum + model.getCountNum();
            }
            if ("totalCount".equals(model.getQsType())) {
                totalNum = totalNum + model.getCountNum();
            }
        }
        for (ExtIndexInvoiceScanningCountModel model : list1) {
            if ("wqsCount".equals(model.getQsType())) {
                wqsNum = wqsNum + model.getCountNum();
            }
            if ("yqsCount".equals(model.getQsType())) {
                yqsNum = yqsNum + model.getCountNum();
            }
            if ("totalCount".equals(model.getQsType())) {
                totalNum = totalNum + model.getCountNum();
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("wqsCount", wqsNum);
        map.put("yqsCount", yqsNum);
        map.put("totalCount", totalNum);
        return map;
    }

    public String responseResult(JSONObject json) {
        String jsonString = null;
        if (json != null) {
            jsonString = Base64.encode(json.toJSONString());
        }
        return jsonString;
    }

    public JSONObject setTitleList(String[] titlelist, String[] titleprop) {
        JSONObject titleList = new JSONObject();
        if (titlelist != null) {
            titleList.put("titlelist", titlelist);
        }
        if (titleprop != null) {
            titleList.put("titleprop", titleprop);
        }

        JSONObject returnJson = new JSONObject();
        returnJson.put("titlelist", titleList);
        return returnJson;
    }

    /**
     * 今日退税认证情况
     *
     * @param pramsMap
     *            {start:当天0点时间，end:当前时间}
     * @return 返回
     */
    @Override
    public Map<String, Object> getDrawbackAuthenticationSituation(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 认证抵扣
        List<ExtIndexInvoiceAuthenticationCountModel> list =
            indexStatisticsMapper.getDrawbackAuthenticationSituation(pramsMap);

        int rzcgType = 0;
        Integer rzsbType = 0;
        Integer fsrzType = 0;
        for (ExtIndexInvoiceAuthenticationCountModel model : list) {
            if ("rzcgType".equals(model.getAuthenticationType())) {
                rzcgType = rzcgType + model.getCountNum();
            }
            if ("rzsbType".equals(model.getAuthenticationType())) {
                rzsbType += model.getCountNum();
            }
            if ("fsrzType".equals(model.getAuthenticationType())) {
                fsrzType += model.getCountNum();
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("rzcgType", rzcgType);
        map.put("rzsbType", rzsbType);
        map.put("fsrzType", fsrzType);

        return map;
    }

    /**
     * 今日发票认证情况
     *
     * @param pramsMap
     *            {start:当天0点时间，end:当前时间}
     * @return 返回
     */
    @Override
    public Map<String, Object> getInvoiceAuthenticationSituation(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 认证抵扣
        List<ExtIndexInvoiceAuthenticationCountModel> list =
            indexStatisticsMapper.getInvoiceAuthenticationSituation(pramsMap);

        int rzcgType = 0;
        Integer rzsbType = 0;
        Integer fsrzType = 0;
        for (ExtIndexInvoiceAuthenticationCountModel model : list) {
            if ("rzcgType".equals(model.getAuthenticationType())) {
                rzcgType = rzcgType + model.getCountNum();
            }
            if ("rzsbType".equals(model.getAuthenticationType())) {
                rzsbType += model.getCountNum();
            }
            if ("fsrzType".equals(model.getAuthenticationType())) {
                fsrzType += model.getCountNum();
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("rzcgType", rzcgType);
        map.put("rzsbType", rzsbType);
        map.put("fsrzType", fsrzType);

        return map;
    }

    @Override
    public String getInvoiceCollectionSituationList(Map<String, Object> pramsMap, int curr, int size) {
        String invoiceType = (String)pramsMap.get("invoiceType");
        log.info("获取今日采集列表,params:{}", pramsMap);
        String[] titlelist = {"序号", "采集日期", "发票代码", "发票号码", "开票日期", "购方名称", "销方名称", "金额", "税额", "抵扣税额"};
        String[] titleprop = {"xh", "createDate", "invoiceCode", "invoiceNo", "invoiceDate", "gfName", "xfName",
            "invoiceAmount", "taxAmount", "dkse"};
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceCollectionModel> listVO = indexStatisticsMapper.getInvoiceCollectionSituationList(pramsMap);
        PageInfo<ExtIndexInvoiceCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getCreateDate())) {
                    resultList.get(i).setCreateDate((resultList.get(i).getCreateDate().substring(0, 10)));
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getDkse())) {
                    resultList.get(i)
                        .setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkse())));
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);

    }

    @Override
    public String getCustomsCollectionSituationList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("获取今日采集列表,params:{}", pramsMap);
        String[] titlelist = {"序号", "采集日期", "海关缴款书号码", "缴款单位", "填发日期", "税款金额", "管理状态", "是否录入不符项"};
        String[] titleprop =
            {"xh", "createDate", "customsNo", "gfName", "fillInDate", "taxAmount", "glzt", "entryDiscrepancy"};
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexCustomsCollectionModel> listVO = indexStatisticsMapper.getCustomsCollectionSituationList(pramsMap);
        PageInfo<ExtIndexCustomsCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexCustomsCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));

                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);

    }

    @Override
    public String getInvoiceScanningSituationList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("今日发票扫描列表,params {}", pramsMap);
        String[] titlelist = {"序号", "扫描日期", "发票代码", "发票号码", "开票日期", "购方名称", "销方名称", "金额", "税额",};
        String[] titleprop = {"xh", "qsDate", "invoiceCode", "invoiceNo", "invoiceDate", "gfName", "xfName",
            "invoiceAmount", "taxAmount", "dkse"};
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceScanningModel> listVO = indexStatisticsMapper.getInvoiceScanningSituationList(pramsMap);
        PageInfo<ExtIndexInvoiceScanningModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceScanningModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getQsDate())) {
                    resultList.get(i).setQsDate((resultList.get(i).getQsDate().substring(0, 10)));
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);
    }

    /**
     * 今日发票认证列表
     *
     * @param pramsMap
     *            {start:当天0点时间，end:当前时间}
     * @return @
     */

    @Override
    public String getInvoiceAuthenticationSituationList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("今日发票认证列表,params {}", pramsMap);
        String[] titlelist = {"序号", "认证时间", "认证类型", "发票代码", "发票号码", "开票日期", "购方名称", "销方名称", "金额", "税额", "抵扣税额"};
        String[] titleprop = {"xh", "rzhDate", "bdkStatus", "invoiceCode", "invoiceNo", "invoiceDate", "gfName",
            "xfName", "invoiceAmount", "taxAmount", "dkse"};
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceCollectionModel> listVO =
            indexStatisticsMapper.getInvoiceAuthenticationSituationList(pramsMap);
        PageInfo<ExtIndexInvoiceCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getRzhDate())) {
                    resultList.get(i).setRzhDate((resultList.get(i).getRzhDate().substring(0, 10)));
                }
                if (!StringHelper.isBlank(resultList.get(i).getBdkStatus())) {
                    if ("1".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证抵扣");
                    } else if ("2".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证不抵扣");
                    }
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getDkse())) {
                    resultList.get(i)
                        .setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkse())));
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);
    }

    @Override
    public String getCurrentMonthAuthList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("今日发票认证列表,params {}", pramsMap);
        String[] titlelist =
            {"序号", "认证日期", "认证类型", "税款所属期", "发票代码", "发票号码", "开票日期", "购方名称", "销方名称", "金额", "税额", "抵扣税额"};
        String[] titleprop = {"xh", "rzhDate", "bdkStatus", "rzhBelongDate", "invoiceCode", "invoiceNo", "invoiceDate",
            "gfName", "xfName", "invoiceAmount", "taxAmount", "dkse"};
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceCollectionModel> listVO = indexStatisticsMapper.getCurrentMonthAuthList(pramsMap);
        PageInfo<ExtIndexInvoiceCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getCreateDate())) {
                    resultList.get(i).setCreateDate((resultList.get(i).getCreateDate().substring(0, 10)));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getRzhDate())) {
                    resultList.get(i).setRzhDate(resultList.get(i).getRzhDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getBdkStatus())) {
                    if ("1".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证抵扣");
                    } else if ("2".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证不抵扣");
                    }
                }
                if (StringUtils.isNotBlank(resultList.get(i).getRzhBelongDate())) {
                    resultList.get(i).setRzhBelongDate(resultList.get(i).getRzhBelongDate());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getDkse())) {
                    resultList.get(i)
                        .setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkse())));
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);
    }

    /**
     * 本月新增发票信息（新增、认证、发票金额（未税）、发票税额）
     *
     * @param pramsMap
     *            {start:当天0点时间，end:当前时间}
     * @return 返回
     */

    @Override
    public ExtIndexInvoiceMonthInformationModel getInvoiceInformationOfMonth(Map<String, Object> pramsMap) {
        log.info("本月新增发票信息（新增、认证、发票金额（未税）、发票税额）,params {}", pramsMap);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        // 本月新增发票统计
        Integer xzInvoice = 0;
        // 本月已认证发票统计
        Integer yrzInvoice = 0;
        // 本月已认证发票金额（未税）
        String taxAmountCount = "0.00";
        // 本月已认证发票税额
        String invoiceAmountCount = "0.00";
        // 本月已认证退税税额
        String drawbackAmountCount = "0.00";
        // 本月新增发票数量
        ExtIndexInvoiceMonthInformationModel invoiceInformationOfMonthCj =
            indexStatisticsMapper.getInvoiceInformationOfMonthCj(pramsMap);
        ExtIndexInvoiceMonthInformationModel invoiceInformationOfMonthRz =
            indexStatisticsMapper.getInvoiceInformationOfMonthRz(pramsMap);
        ExtIndexInvoiceMonthInformationModel drawbackInformationOfMonthRz =
            indexStatisticsMapper.getDrawbackInformationOfMonthRz(pramsMap);
        if (invoiceInformationOfMonthCj != null) {
            xzInvoice = invoiceInformationOfMonthCj.getXzInvoice();
        }
        if (invoiceInformationOfMonthRz != null) {
            if (invoiceInformationOfMonthRz.getYrzInvoice() != null) {
                yrzInvoice = invoiceInformationOfMonthRz.getYrzInvoice();
            }
            if (StringUtils.isNotBlank(invoiceInformationOfMonthRz.getTaxAmountCount())) {
                taxAmountCount = invoiceInformationOfMonthRz.getTaxAmountCount();
            }
            if (StringUtils.isNotBlank(invoiceInformationOfMonthRz.getInvoiceAmountCount())) {
                invoiceAmountCount = invoiceInformationOfMonthRz.getInvoiceAmountCount();
            }
        }
        if (drawbackInformationOfMonthRz != null) {
            if (drawbackInformationOfMonthRz.getYrzInvoice() != null) {
                yrzInvoice = yrzInvoice + drawbackInformationOfMonthRz.getYrzInvoice();
            }
            if (StringUtils.isNotBlank(drawbackInformationOfMonthRz.getTaxAmountCount())) {
                drawbackAmountCount = drawbackInformationOfMonthRz.getTaxAmountCount();
            }

        }
        ExtIndexInvoiceMonthInformationModel model = new ExtIndexInvoiceMonthInformationModel();
        model.setInvoiceAmountCount(invoiceAmountCount);
        model.setTaxAmountCount(taxAmountCount);
        model.setXzInvoice(xzInvoice);
        model.setYrzInvoice(yrzInvoice);
        model.setDrawbackAmountCount(drawbackAmountCount);
        return model;
    }

    /**
     * 本月发票新增、认证成功、认证失败图表
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */

    @Override
    public List<ExtIndexInvoiceChartStatisticsModel> getInvoiceChartStatistics(Map<String, Object> pramsMap) {
        log.info("本月发票新增、认证成功、认证失败图表,params {}", pramsMap);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        List<ExtIndexInvoiceChartStatisticsModel> chartStatisticsModelList =
            indexStatisticsMapper.getInvoiceChartStatistics(pramsMap);
        if (chartStatisticsModelList == null) {
            return newArrayList();
        }

        chartStatisticsModelList.forEach(indexInvoiceChartStatisticsModel -> {
            if (StringUtils.isNotEmpty(indexInvoiceChartStatisticsModel.getRzcgDayOfMonthInYear())) {
                indexInvoiceChartStatisticsModel
                    .setDayOfMonthInYear(indexInvoiceChartStatisticsModel.getRzcgDayOfMonthInYear());
            }
            if (StringUtils.isNotEmpty(indexInvoiceChartStatisticsModel.getRzsbDayOfMonthInYear())) {
                indexInvoiceChartStatisticsModel
                    .setDayOfMonthInYear(indexInvoiceChartStatisticsModel.getRzsbDayOfMonthInYear());
            }
        });

        for (int i = 0; i < chartStatisticsModelList.size() - 1; i++) {
            for (int j = chartStatisticsModelList.size() - 1; j > i; j--) {
                if (chartStatisticsModelList.get(j).getDayOfMonthInYear()
                    .equals(chartStatisticsModelList.get(i).getDayOfMonthInYear())) {
                    // 删除重复元素
                    chartStatisticsModelList.remove(j);
                }
            }
        }

        final List<ExtIndexInvoiceChartStatisticsModel> modelList = complementingDayList(chartStatisticsModelList);
        modelList.sort(Comparator.comparing(ExtIndexInvoiceChartStatisticsModel::getDayOfMonthInYear));
        return modelList;
    }

    /**
     * 任务提醒
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */

    @Override
    public List<ExtIndexInvoiceTaskRemindingModel> getInvoiceTaskReminding(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        List<ExtIndexInvoiceTaskRemindingModel> list = new ArrayList<>();
        ExtIndexInvoiceTaskRemindingModel model = null;
        ExtIndexInvoiceTaskRemindingModel invoiceTaskRemindingYq =
            indexStatisticsMapper.getInvoiceTaskRemindingYq(pramsMap);
        ExtIndexInvoiceTaskRemindingModel invoiceTaskRemindingYc =
            indexStatisticsMapper.getInvoiceTaskRemindingYc(pramsMap);
        ExtIndexInvoiceTaskRemindingModel invoiceTaskRemindingPpknd =
            indexStatisticsMapper.getInvoiceTaskRemindingPpknd(pramsMap);
        ExtIndexInvoiceTaskRemindingModel invoiceTaskRemindingRzyc =
            indexStatisticsMapper.getInvoiceTaskRemindingRzyc(pramsMap);
        ExtIndexInvoiceTaskRemindingModel invoiceTaskRemindingQsyc =
            indexStatisticsMapper.getInvoiceTaskRemindingQsyc(pramsMap);
        if (invoiceTaskRemindingYq != null) {
            if (invoiceTaskRemindingYq.getCountNum() == null) {
                invoiceTaskRemindingYq.setCountNum(0);
            }
            list.add(invoiceTaskRemindingYq);
        } else {
            model = new ExtIndexInvoiceTaskRemindingModel();
            model.setCountNum(0);
            model.setWarningType("yqWarning");
            list.add(model);
        }
        if (invoiceTaskRemindingYc != null) {
            if (invoiceTaskRemindingYc.getCountNum() == null) {
                invoiceTaskRemindingYc.setCountNum(0);
            }
            list.add(invoiceTaskRemindingYc);
        } else {
            model = new ExtIndexInvoiceTaskRemindingModel();
            model.setCountNum(0);
            model.setWarningType("ycfpWarning");
            list.add(model);
        }
        if (invoiceTaskRemindingPpknd != null) {
            if (invoiceTaskRemindingPpknd.getCountNum() == null) {
                invoiceTaskRemindingPpknd.setCountNum(0);
            }
            list.add(invoiceTaskRemindingPpknd);
        } else {
            model = new ExtIndexInvoiceTaskRemindingModel();
            model.setCountNum(0);
            model.setWarningType("ptkndWarning");
            list.add(model);
        }
        if (invoiceTaskRemindingRzyc != null) {
            if (invoiceTaskRemindingRzyc.getCountNum() == null) {
                invoiceTaskRemindingRzyc.setCountNum(0);
            }
            list.add(invoiceTaskRemindingRzyc);
        } else {
            model = new ExtIndexInvoiceTaskRemindingModel();
            model.setCountNum(0);
            model.setWarningType("rzhyc");
            list.add(model);
        }
        if (invoiceTaskRemindingQsyc != null) {
            if (invoiceTaskRemindingQsyc.getCountNum() == null) {
                invoiceTaskRemindingQsyc.setCountNum(0);
            }
            list.add(invoiceTaskRemindingQsyc);
        } else {
            model = new ExtIndexInvoiceTaskRemindingModel();
            model.setCountNum(0);
            model.setWarningType("qshyc");
            list.add(model);
        }

        return list;
    }

    /**
     * 本月发票新增、认证成功、认证失败图表
     *
     * @param pramsMap
     *            查询条件
     * @return 返回
     */
    @Override
    public List<ExtIndexInvoiceChartStatisticsModel> getInvoiceChartStatisticsYear(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        log.info("本年发票新增、认证成功、认证失败图表,params {}", pramsMap);
        final List<ExtIndexInvoiceChartStatisticsModel> modelList =
            indexStatisticsMapper.getInvoiceChartStatisticsYear(pramsMap);
        if (modelList == null) {
            return newArrayList();
        }
        final List<ExtIndexInvoiceChartStatisticsModel> chartStatisticsModelList =
            complementingMonthList(modelList, pramsMap.get("endDate").toString());
        chartStatisticsModelList.sort(Comparator.comparing(ExtIndexInvoiceChartStatisticsModel::getDayOfMonthInYear));
        return chartStatisticsModelList;
    }

    /**
     * 补全没有数据的月份
     *
     * @param list
     *            年度统计数据
     * @return 补全后的年度统计数据
     */
    private List<ExtIndexInvoiceChartStatisticsModel>
        complementingMonthList(List<ExtIndexInvoiceChartStatisticsModel> list, String endDate) {
        // 12个月
        final String[] monthArray =
            new String[] {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
        // 12个月集合
        final List<String> arrayList = Arrays.asList(monthArray);
        final List<String> monthList = new ArrayList<>(arrayList);
        // 移除存在数据的月份
        list.forEach(indexInvoiceChartStatisticsModel -> {
            String month;
            if (indexInvoiceChartStatisticsModel.getDayOfMonthInYear() != null) {
                month = indexInvoiceChartStatisticsModel.getDayOfMonthInYear().substring(5, 7);
            } else {
                month = indexInvoiceChartStatisticsModel.getRzcgDayOfMonthInYear().substring(5, 7);
                indexInvoiceChartStatisticsModel
                    .setDayOfMonthInYear(indexInvoiceChartStatisticsModel.getRzcgDayOfMonthInYear());
            }
            monthList.remove(month);
        });
        if (monthList.size() > 0) {
            // 补全不存在数据的月份
            monthList.forEach(monthStr -> {
                final ExtIndexInvoiceChartStatisticsModel model = new ExtIndexInvoiceChartStatisticsModel();
                // 年-月
                if (!StringUtils.isBlank(endDate)) {
                    model.setDayOfMonthInYear(endDate.substring(0, 4) + "-" + monthStr);
                }
                // 新增数量默认为0
                model.setXzInvoiceCount(0);
                // 认证成功数量默认为0
                model.setRzcgInvoiceCount(0);
                // 认证失败数量默认为0
                model.setRzsbInvoiceCount(0);
                list.add(model);
            });
        }
        return list;
    }

    /**
     * 补全当月没有数据的天 数据默认0
     *
     * @param list
     *            当月统计数据（日报）
     * @return 补全后的月度统计数据
     */
    private List<ExtIndexInvoiceChartStatisticsModel>
        complementingDayList(List<ExtIndexInvoiceChartStatisticsModel> list) {
        // 当前时间所在月的天
        final int day = new DateTime().dayOfMonth().getMaximumValue();

        final List<String> dayList = newArrayList();
        IntStream.range(1, day + 1).forEach(i -> {
            if (i < 10) {
                dayList.add("0" + i);
            } else {
                dayList.add(String.valueOf(i));
            }
        });

        list.forEach(indexInvoiceChartStatisticsModel -> {
            String dayStr;
            if (indexInvoiceChartStatisticsModel.getDayOfMonthInYear() != null) {
                dayStr = indexInvoiceChartStatisticsModel.getDayOfMonthInYear().substring(8, 10);
            } else {
                dayStr = indexInvoiceChartStatisticsModel.getRzcgDayOfMonthInYear().substring(8, 10);
            }
            dayList.remove(dayStr);
        });

        if (dayList.size() > 0) {
            // 补全不存在数据的天
            dayList.forEach(dayStr -> {
                final ExtIndexInvoiceChartStatisticsModel model = new ExtIndexInvoiceChartStatisticsModel();
                // 年-月
                model.setDayOfMonthInYear(new DateTime().toString("yyyy-MM") + "-" + dayStr);
                // 新增数量默认为0
                model.setXzInvoiceCount(0);
                // 认证成功数量默认为0
                model.setRzcgInvoiceCount(0);
                // 认证失败数量默认为0
                model.setRzsbInvoiceCount(0);
                list.add(model);
            });
        }

        return list;
    }

    @Override
    public String getRzhycList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("今日发票认证列表,params {}", pramsMap);
        String[] titlelist = {"序号", "认证时间", "认证类型", "发票代码", "发票号码", "发票状态", "开票日期", "购方名称", "销方名称", "金额", "税额", "抵扣税额"};
        String[] titleprop = {"xh", "rzhDate", "bdkStatus", "invoiceCode", "invoiceNo", "invoiceStatus", "invoiceDate",
            "gfName", "xfName", "invoiceAmount", "taxAmount", "dkse"};
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceCollectionModel> listVO = indexStatisticsMapper.getRzhycList(pramsMap);
        PageInfo<ExtIndexInvoiceCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getRzhDate())) {
                    resultList.get(i).setRzhDate((resultList.get(i).getRzhDate().substring(0, 10)));
                }
                if (!StringHelper.isBlank(resultList.get(i).getBdkStatus())) {
                    if ("1".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证抵扣");
                    } else if ("2".equals(resultList.get(i).getBdkStatus())) {
                        resultList.get(i).setBdkStatus("认证不抵扣");
                    }
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getDkse())) {
                    resultList.get(i)
                        .setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDkse())));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceStatus())) {
                    String invoiceStatus = resultList.get(i).getInvoiceStatus();
                    resultList.get(i).setInvoiceStatus(
                        "0".equals(invoiceStatus) ? "正常" : "1".equals(invoiceStatus) ? "失控" : "2".equals(invoiceStatus)
                            ? "作废" : "3".equals(invoiceStatus) ? "红冲" : "4".equals(invoiceStatus) ? "异常" : "");
                }
            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);
    }

    @Override
    public String getQshycList(Map<String, Object> pramsMap, int curr, int size) {
        log.info("今日发票认证列表,params {}", pramsMap);
        String[] titlelist = {"序号", "签收时间", "发票代码", "发票号码", "发票状态", "开票日期", "购方名称", "销方名称", "金额", "税额"};
        String[] titleprop = {"xh", "qsDate", "invoiceCode", "invoiceNo", "invoiceStatus", "invoiceDate", "gfName",
            "xfName", "invoiceAmount", "taxAmount"};
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = this.setTitleList(titlelist, titleprop);

        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<ExtIndexInvoiceCollectionModel> listVO = indexStatisticsMapper.getQshycList(pramsMap);
        PageInfo<ExtIndexInvoiceCollectionModel> pageInfo = new PageInfo<>(listVO);
        List<ExtIndexInvoiceCollectionModel> resultList = pageInfo.getList();

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

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh((curr - 1) * size + (i + 1));
                if (!StringHelper.isBlank(resultList.get(i).getQsDate())) {
                    resultList.get(i).setQsDate((resultList.get(i).getQsDate().substring(0, 10)));
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceCode())) {
                    resultList.get(i).setInvoiceCode(resultList.get(i).getInvoiceCode());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceNo())) {
                    resultList.get(i).setInvoiceNo(resultList.get(i).getInvoiceNo());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceDate())) {
                    resultList.get(i).setInvoiceDate(resultList.get(i).getInvoiceDate().substring(0, 10));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getGfName())) {
                    resultList.get(i).setGfName(resultList.get(i).getGfName());
                }
                if (StringUtils.isNotBlank(resultList.get(i).getXfName())) {
                    resultList.get(i).setXfName(resultList.get(i).getXfName());
                }
                if (!StringHelper.isBlank(resultList.get(i).getInvoiceAmount())) {
                    resultList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount())));
                }
                if (!StringHelper.isBlank(resultList.get(i).getTaxAmount())) {
                    resultList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount())));
                }
                if (StringUtils.isNotBlank(resultList.get(i).getInvoiceStatus())) {
                    String invoiceStatus = resultList.get(i).getInvoiceStatus();
                    resultList.get(i).setInvoiceStatus(
                        "0".equals(invoiceStatus) ? "正常" : "1".equals(invoiceStatus) ? "失控" : "2".equals(invoiceStatus)
                            ? "作废" : "3".equals(invoiceStatus) ? "红冲" : "4".equals(invoiceStatus) ? "异常" : "");
                }

            }
        }
        json.put("datalist", resultList);
        return this.responseResult(json);
    }

}
