package com.tofly.watermeter.custom.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.custom.entity.meterRead.ReadSearch;
import com.tofly.watermeter.custom.entity.meterRead.ReadStatisticsDetail;
import com.tofly.watermeter.custom.entity.meterRead.readstatic.AllocationSta;
import com.tofly.watermeter.custom.entity.meterRead.readstatic.ReadOverTime;
import com.tofly.watermeter.custom.entity.meterRead.readstatic.ReadOverTimeDetail;
import com.tofly.watermeter.custom.service.ReadStatisticService;
import com.tofly.watermeter.em.Constant;
import com.tofly.watermeter.em.ExcelExportFileTypeEnum;
import com.tofly.watermeter.em.ReadStatiscEnum;
import com.tofly.watermeter.entity.Readmeterhis;
import com.tofly.watermeter.mapper.QfcbqfmxMapper;
import com.tofly.watermeter.mapper.ReadmeterMapper;
import com.tofly.watermeter.mapper.ReadmeterhisMapper;
import com.tofly.watermeter.service.ReadmeterhisService;
import com.tofly.watermeter.strategy.ExcelStrategyContext;
import com.tofly.watermeter.util.ExcelUtil;
import com.tofly.watermeter.util.JxlsUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author FlashWJL
 * @date 2021/6/12 17:22
 */
@Service
@AllArgsConstructor
public class ReadStatisticServiceImpl implements ReadStatisticService {

    private final QfcbqfmxMapper qfcbqfmxMapper;
    private final ExcelStrategyContext excelStrategyContext;
    private final ReadmeterhisMapper readmeterhisMapper;
    private final ReadmeterMapper readmeterMapper;
    private final ReadmeterhisService readmeterhisService;

    /**
     * SELECT a.* , trunc(a.READNUM/a.ALLNUM , 3)*100 ALLPERCENT ,
     * trunc(a.APPCB/a.ALLNUM, 3)*100 APPPERCENT, trunc(a.WEBCB/a.ALLNUM, 3)*100 WEBPERCENT
     * FROM (SELECT CBQY_MC ,
     * COUNT(1) ALLNUM,
     * SUM(DECODE(CBBZ, '1' , 1 , 0)) READNUM,
     * SUM(DECODE(CBBZ, '0' , 1 , 0)) NONUM,
     * SUM(DECODE(IS_OFFLINE, '0', 1 , 0)) APPCB,
     * SUM(DECODE(IS_OFFLINE, '1', 1 , 0)) WEBCB
     * FROM TF_YWPN_READMETERHIS_W
     * WHERE MONTH_PLAN = '202111'
     * GROUP BY CBQY_MC) a
     *
     * @param search
     * @param response
     * @return
     */
    @Override
    public List<Map> getReadPercent(ReadSearch search, HttpServletResponse response) {
        String qybm = search.getSspq();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择财务月份");
        }
        List<String> qybmList = null;
        if (StringUtil.isNotEmpty(qybm)) {
            qybmList = Arrays.asList(qybm.split(","));
        }
        //查看分配了的区域总的应抄表数
        List<Map> listShouldRead = readmeterhisMapper.getReadPercent(cwyf, qybmList, isGeneral);

        //如果传的是 1，则代表导出Excel数据
        if ("1".equals(search.getTemplateFlag())) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum =
                    ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("QyReadPecentService", search.getTemplateFlag());
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(listShouldRead);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList =
                    excelStrategyContext.getExportData("QyReadPecentService", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return listShouldRead;
        }
    }

    @Override
    public List<Map> getReadPercentByQy(ReadSearch search, HttpServletResponse response) {
        String qybm = search.getSspq();
        String qydbm = search.getCbb();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择财务月份");
        }
        List<String> qybmList = null;
        List<String> cbbList = null;
        if (StringUtil.isNotEmpty(qybm)) {
            qybmList = Arrays.asList(qybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            cbbList = Arrays.asList(qydbm.split(","));
        }
        List<Map> listShouldRead = readmeterhisMapper.getReadPercentByQy(cwyf, qybmList, cbbList, isGeneral);
        if (StringUtil.isNotNull(listShouldRead)) {
            //分组数据
            Map<String, List<Map>> groupByQymc = listShouldRead.stream().collect(Collectors.groupingBy(v -> v.get("cbqyMc").toString()));
            List<Map> mapList = new ArrayList<>();

            groupByQymc.forEach((k, v) -> {
                Map map = new HashMap(10);
                map.put("qymc", k);
                map.put("resultList", v);
                mapList.add(map);
            });
            //如果传的是 1，则代表导出Excel数据
            if ("1".equals(search.getTemplateFlag())) {
                // 根据templateServiceType,templateFlag获取对应模板数据
                ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("QydReadPecentService", search.getTemplateFlag());
                if (null == excelExportFileTypeEnum) {
                    return null;
                }
                Map<String, Object> model = new HashMap<>(10);
                model.put("dataMap", mapList);
                // 从模型类型枚举根据templateServiceType获取策略对应模板数据
                JxlsUtils.exportExcel(excelExportFileTypeEnum, model, response, Constant.FILE_PATH_TEST_EXPORT_EXCEL);
                return null;
            } else {
                return listShouldRead;
            }
        } else {
            throw new ToflyDeniedException("暂无数据");
        }

    }

    @Override
    public List<Map> getReadPercentByCbry(ReadSearch search, HttpServletResponse response) {
        String cbry = search.getCbryName();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择财务月份");
        }
        List<String> cbryList = null;
        if (StringUtil.isNotEmpty(cbry)) {
            cbryList = Arrays.asList(cbry.split(","));
        }
        List<Map> listShreadmeterhisMapper = readmeterhisMapper.getReadPercentByCbry(cwyf, cbryList, isGeneral);

        //如果传的是 1，则代表导出Excel数据
        if ("1".equals(search.getTemplateFlag())) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("cbryReadPercentService", search.getTemplateFlag());
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(listShreadmeterhisMapper);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("cbryReadPercentService", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return listShreadmeterhisMapper;
        }
    }

    @Override
    public List<Map> getReadPercentDay(ReadSearch search, HttpServletResponse response) {
        String cbry = search.getCbryName();
        String template = search.getTemplateFlag();
        List<String> cbryList = null;
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";

        if (StringUtil.isNotEmpty(cbry)) {
            cbryList = Arrays.asList(cbry.split(","));
        }
        List<Map> mapList = readmeterhisMapper.getReadPercentDay(cbryList, search, isGeneral);
        if ("1".equals(template)) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("readPercentDayService", search.getTemplateFlag());
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(mapList);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("readPercentDayService", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return mapList;
        }


    }

    /**
     * 能够满足80%抄表统计中的详情列表
     *
     * @param page     分页参数
     * @param search   搜索条件
     * @param response 响应
     * @return 抄表列表详情数据
     */
    @Override
    public IPage<Readmeterhis> getReadDayInfo(Page page, ReadSearch search, HttpServletResponse response) {
        String inputcontent = search.getInputContent();
        String template = search.getTemplateFlag();
        String cbryName = search.getCbryName();
        String cbqybm = search.getSspq();
        String qydbm = search.getCbb();
        Date startDate = search.getStartDate();
        Date endDate = search.getEndDate();
        String queryState = search.getState();
        String queryType = search.getQueryType();
        String cwyf = search.getCwyf();
        String cbfs = search.getCbfs();
        String issyn = search.getIssyn();
        String isPx = search.getIsPx();
        List<String> cbryList = null;
        List<String> cbqyList = null;
        List<String> qydList = null;
        List<String> cbfsList = null;
//        String isGeneral = "1".equals(search.getIsGeneral()) ? "1":"0";
        String isGeneral = search.getIsGeneral();
        if (StringUtil.isNotEmpty(cbryName)) {
            cbryList = Arrays.asList(cbryName.split(","));
        }
        if (StringUtil.isNotEmpty(cbqybm)) {
            cbqyList = Arrays.asList(cbqybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            qydList = Arrays.asList(qydbm.split(","));
        }
        if (StringUtil.isNotEmpty(cbfs)) {
            cbfsList = Arrays.asList(cbfs.split(","));
        }

        LambdaQueryWrapper<Readmeterhis> queryWrapper = new LambdaQueryWrapper<Readmeterhis>();
        queryWrapper.in(StringUtil.isNotNull(cbryList), Readmeterhis::getCbry, cbryList)
                .and(StringUtil.isNotEmpty(inputcontent), v -> v.like(Readmeterhis::getYhbh, inputcontent).or()
                        .like(Readmeterhis::getYhxm, inputcontent).or().like(Readmeterhis::getYhdz, inputcontent).or()
                        .like(Readmeterhis::getLxdh, inputcontent))
                .eq(StringUtil.isNotEmpty(isGeneral), Readmeterhis::getIsGeneral, isGeneral)
                .in(StringUtil.isNotNull(cbqyList), Readmeterhis::getCbqyBm, cbqyList)
                .in(StringUtil.isNotNull(qydList), Readmeterhis::getCbqydBm, qydList)
                .in(StringUtil.isNotNull(cbfsList), Readmeterhis::getCbfsCode, cbfsList)
                .eq(StringUtil.isNotEmpty(issyn), Readmeterhis::getIssyn, issyn)
                //用于日抄表率查询列表
                .between(StringUtil.isNotNull(endDate) && StringUtil.isNotNull(startDate) && "2".equals(queryType),
                        Readmeterhis::getStartRq, startDate, endDate)
                //这里只用于卡表数据分析详情列表
                .between(StringUtil.isNotNull(endDate) && StringUtil.isNotNull(startDate) && "1".equals(isGeneral),
                        Readmeterhis::getCbrq, startDate, endDate)
                //月抄表率查询列表
                .eq(StringUtil.isNotEmpty(cwyf) && "1".equals(queryType), Readmeterhis::getMonthPlan, cwyf)
                //普通查询列表根据月份查询的
                .eq(StringUtil.isNotEmpty(cwyf) && StringUtil.isEmpty(queryType), Readmeterhis::getMonthPlan, cwyf)
                //以下枚举类的查询，是涉及到0：未抄表，1：已抄表(实抄，已抄总数)，2：应抄(应抄表总数)，3：在线抄表，4：离线抄表，5：按时抄表，6：超时抄表，7：故障抄表，8：准确抄表，9：正值；10：负值；11：等值
                .eq(ReadStatiscEnum.NO_READ.getCode().equals(queryState), Readmeterhis::getCbbz, "0")
                .eq(ReadStatiscEnum.YET_READ.getCode().equals(queryState), Readmeterhis::getCbbz, "1")
                .eq(ReadStatiscEnum.ON_READ.getCode().equals(queryState), Readmeterhis::getIsOffline, "0")
                .eq(ReadStatiscEnum.OFFINE_READ.getCode().equals(queryState), Readmeterhis::getIsOffline, "1")
                .apply(ReadStatiscEnum.TIME_READ.getCode().equals(queryState), "CBBZ = '1' AND CBRQ <=  END_RQ")
                .and(ReadStatiscEnum.OVER_READ.getCode().equals(queryState), v -> v.apply("(CBBZ = '1' AND CBRQ >  END_RQ) OR (CBBZ = '0' AND SYSDATE >  END_RQ)"))
                .gt(ReadStatiscEnum.POSITIVE_READ.getCode().equals(queryState), Readmeterhis::getDiffValue, 0)
                .lt(ReadStatiscEnum.MINUX_READ.getCode().equals(queryState), Readmeterhis::getDiffValue, 0)
                .eq(ReadStatiscEnum.EQUAL_READ.getCode().equals(queryState), Readmeterhis::getDiffValue, 0)
                .orderByAsc(!"1".equals(isPx), Readmeterhis::getCbryName, Readmeterhis::getCbqyMc, Readmeterhis::getQydmc, Readmeterhis::getCbrq)
                .orderByAsc("1".equals(isPx), Readmeterhis::getCbxh)
                .select(Readmeterhis::getCbry, Readmeterhis::getCbryName, Readmeterhis::getCbqyBm, Readmeterhis::getCbqydBm, Readmeterhis::getCbqyMc,
                        Readmeterhis::getQydmc, Readmeterhis::getYhbh, Readmeterhis::getYhxm, Readmeterhis::getYhdz, Readmeterhis::getScds, Readmeterhis::getSoleSign,
                        Readmeterhis::getBcds, Readmeterhis::getCbsl, Readmeterhis::getIssyn, Readmeterhis::getCbbz, Readmeterhis::getCbfsCode, Readmeterhis::getSxjmessage,
                        Readmeterhis::getCbrq, Readmeterhis::getMonthPlan, Readmeterhis::getDiffTime, Readmeterhis::getAbnomalId, Readmeterhis::getAuditReason,
                        Readmeterhis::getZgl, Readmeterhis::getDiffValue, Readmeterhis::getCbxh, Readmeterhis::getCbpq, Readmeterhis::getCbb,
                        Readmeterhis::getYsxz, Readmeterhis::getSbbh,Readmeterhis::getUpdateUser,Readmeterhis::getUpdateDate);
        if ("1".equals(template)) {
            List<Readmeterhis> mapperReadDayInfo = readmeterhisService.list(queryWrapper);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = null;

            if ("0".equals(isGeneral)) {
                excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("readDayInfoService", "1");
            } else {
                excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("readDayInfoService", "2");
            }
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONStringWithDateFormat(mapperReadDayInfo, "yyyy-MM-dd HH:mm:ss");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("readDayInfoService", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return readmeterhisService.page(page, queryWrapper);
        }
    }


    @Override
    public List<Map> getReadTimeDeatil(ReadSearch search, HttpServletResponse response) {
        String qydbm = search.getCbb();
        String qybm = search.getSspq();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择财务月份");
        }
        List<String> qybmList = null;
        List<String> cbbList = null;
        if (StringUtil.isNotEmpty(qybm)) {
            qybmList = Arrays.asList(qybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            cbbList = Arrays.asList(qydbm.split(","));
        }
        List<Map> mapList = readmeterhisMapper.getReadTimeDeatil(qybmList, cbbList, cwyf, isGeneral);
        //如果传的是 1，则代表导出Excel数据
        if ("1".equals(search.getTemplateFlag())) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("QydReadTimeInfoService", search.getTemplateFlag());
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONStringWithDateFormat(mapList, "yyyy-MM-dd HH:mm:ss");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("QydReadTimeInfoService", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return mapList;
        }

    }


    @Override
    public IPage<ReadStatisticsDetail> getReadQuery(Page page, ReadSearch search, HttpServletResponse response) {
        String qybm = search.getSspq();
        String qydbm = search.getCbb();
        String cbState = search.getState();
        String auditState = search.getAuditState();
        String input = search.getInputContent();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择财务月份");
        }
        IPage<ReadStatisticsDetail> mapIPage = qfcbqfmxMapper.getReadQuery(page, qybm, qydbm, cbState, auditState, input, cwyf, isGeneral);
        //如果传的是 1，则代表导出Excel数据
        if ("1".equals(search.getTemplateFlag())) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("ReadQueryServcie", search.getTemplateFlag());
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(mapIPage.getRecords());
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("ReadQueryServcie", search.getTemplateFlag(), resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            return mapIPage;
        }

    }

    @Override
    public List<AllocationSta> allocationClloect(ReadSearch search, HttpServletResponse response) {
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        search.setIsGeneral(isGeneral);
        String template = search.getTemplateFlag();
        List<AllocationSta> allocationClloectList = readmeterhisMapper.allocationClloect(search);
        Integer qyNum = 0;
        Integer qydNum = 0;
        Integer allYhNum = 0;
        int i = 1;
        for (AllocationSta allocationSta : allocationClloectList) {
            allocationSta.setXh(i++);
            qyNum = qyNum + allocationSta.getQyNum();
            qydNum = qydNum + allocationSta.getQydNum();
            allYhNum = allYhNum + allocationSta.getAllYhNum();
        }
//        AllocationSta allocationSta = new AllocationSta();
//        allocationSta.setCbryName("合计");
//        allocationSta.setAllYhNum(allYhNum);
//        allocationSta.setQyNum(qyNum);
//        allocationSta.setQydNum(qydNum);
//        allocationSta.setXh(allocationClloectList.size() + 1);
//        allocationClloectList.add(allocationSta);
        if ("1".equals(template)) {
            // 根据templateServiceType,templateFlag获取对应模板数据，找到枚举中相应的Excel文件名、路径等信息
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("allcationCollect", template);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            Map<String, Object> model = new HashMap<>(10);
            model.put("dataMap", allocationClloectList);
            JxlsUtils.exportExcel(excelExportFileTypeEnum, model, response, Constant.FILE_PATH_TEST_EXPORT_EXCEL);
            return null;
        } else {
            return allocationClloectList;
        }
    }

    @Override
    public IPage<Map> allocationInfo(Page page, ReadSearch search, HttpServletResponse response) {
        Long cbry = search.getCbry();
        String cwyf = search.getCwyf();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        search.setIsGeneral(isGeneral);
        String template = search.getTemplateFlag();
        if (StringUtil.isNull(cbry)) {
            throw new ToflyDeniedException("抄表人员ID必传");
        } else if (StringUtil.isEmpty(cwyf)) {
            throw new ToflyDeniedException("请选择月份");
        } else if (StringUtil.isEmpty(isGeneral)) {
            throw new ToflyDeniedException("请选择查询类型");
        }

        String qybm = search.getSspq();
        String qydbm = search.getCbb();
        List<String> qybmList = null;
        List<String> cbbList = null;
        if (StringUtil.isNotEmpty(qybm)) {
            qybmList = Arrays.asList(qybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            cbbList = Arrays.asList(qydbm.split(","));
        }
        int i = 1;
        if ("1".equals(template)) {
            List<Map> readmeterList = readmeterMapper.allocationInfo(search, qybmList, cbbList);
            //抄表序号
            for (Map map : readmeterList) {
                map.put("xh", i++);
            }
            // 根据templateServiceType,templateFlag获取对应模板数据，找到枚举中相应的Excel文件名、路径等信息
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum
                    .getExcelExportFileTypeEnum("allcationInfo", template);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            Map<String, Object> model = new HashMap<>(10);
            model.put("dataMap", readmeterList);
            JxlsUtils.exportExcel(excelExportFileTypeEnum, model, response, Constant.FILE_PATH_TEST_EXPORT_EXCEL);
            return null;
        } else {
            IPage<Map> readmeterIPage = readmeterMapper.allocationInfoPage(page, search, qybmList, cbbList);

            //抄表序号
            for (Map map : readmeterIPage.getRecords()) {
                map.put("xh", i++);
            }
            return readmeterIPage;
        }
    }

    @Override
    public List<ReadOverTime> getOvertimeCollect(ReadSearch search, HttpServletResponse response) {
        String template = search.getTemplateFlag();
        List<String> cbryList = null;
        String cbryName = search.getCbryName();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        if (StringUtil.isNotEmpty(cbryName)) {
            cbryList = Arrays.asList(cbryName.split(","));
        }
        String yearMonth = search.getCwyf();
        List<ReadOverTime> readOverTimes = readmeterhisMapper.getOvertimeCollect(cbryList, yearMonth, isGeneral);
        //计算合计
        ReadOverTime readOverTotal = new ReadOverTime();
        readOverTotal.setCbryName("合计");
        readOverTotal.setOverCount(0);
        readOverTotal.setAllCount(0);
        readOverTotal.setOverTimeCount(0);
        for (ReadOverTime readOverTime : readOverTimes) {
            readOverTotal.setOverCount(readOverTime.getOverCount() + readOverTotal.getOverCount());
            readOverTotal.setAllCount(readOverTime.getAllCount() + readOverTotal.getAllCount());
            readOverTotal.setOverTimeCount(readOverTime.getOverTimeCount() + readOverTotal.getOverTimeCount());
        }
        Float overCount = Float.valueOf(readOverTotal.getOverCount());
        Float allCount = Float.valueOf(readOverTotal.getAllCount());
        if (!allCount.equals(0.0F)) {
            //计算超时率
            readOverTotal.setOverTimeRatio(NumberUtil.round((overCount / allCount) * 100, 1).floatValue());
        } else {
            //计算超时率
            readOverTotal.setOverTimeRatio(0F);
        }
        readOverTimes.add(readOverTotal);
        return readOverTimes;
    }

    @Override
    public List<ReadOverTimeDetail> getOvertimeCollectDeatil(ReadSearch search, HttpServletResponse response, Float overTimeRatio) {
        Long cbry = search.getCbry();
        String yearMonth = search.getCwyf();
        String template = search.getTemplateFlag();
        String isGeneral = "1".equals(search.getIsGeneral()) ? "1" : "0";
        List<ReadOverTimeDetail> readOverTimeDetails = readmeterhisMapper.getOvertimeCollectDeatil(cbry, yearMonth, isGeneral);
        for (ReadOverTimeDetail readOverTimeDetail : readOverTimeDetails) {
            readOverTimeDetail.setAllOverTimeRatio(overTimeRatio);
        }
        return readOverTimeDetails;
    }

    @Override
    public IPage<Readmeterhis> getClient(Page page, ReadSearch search, HttpServletResponse response) {
        String template = search.getTemplateFlag();
        String inputContent = search.getInputContent();
        String isGeneral = search.getIsGeneral();
        if ("1".equals(template)) {
            //如果是导出，必须要条件，否则所有抄表历史数据都会导出
            if (StringUtil.isNotEmpty(inputContent)) {
                List<Readmeterhis> mapperReadDayInfo = readmeterhisMapper.getClient(search);
                // 根据templateServiceType,templateFlag获取对应模板数据
                ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("readDayInfoService", search.getTemplateFlag());
                if (null == excelExportFileTypeEnum) {
                    return null;
                }
                //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
                String resultListToString = JSONArray.toJSONStringWithDateFormat(mapperReadDayInfo, "yyyy-MM-dd HH:mm:ss");
                // 从模型类型枚举根据templateServiceType获取策略对应模板数据
                List<Map<String, Object>> dataList = excelStrategyContext.getExportData("readDayInfoService", search.getTemplateFlag(), resultListToString);
                ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            }
            return null;
        } else {
            //查询视图，同时查询TF_YWPN_READMETEREASHIS_W（同步远传表）、TF_YWPN_READMETERHIS_W（机械表卡表）两表数据
            return readmeterhisMapper.getClient(page, search);
        }
    }

    @Override
    public List<ReadOverTime> getTimeAbnormalCollect(String cbry, String yearMonth, Integer overDiffTime, HttpServletResponse response, String isGeneral) {
        isGeneral = "1".equals(isGeneral) ? "1" : "0";
        if (StringUtil.isEmpty(yearMonth)) {
            throw new ToflyDeniedException("请选择月份");
        }
        if (StringUtil.isNull(overDiffTime)) {
            throw new ToflyDeniedException("请选择间隔时长");
        }
        List<String> cbryList = null;
        if (StringUtil.isNotEmpty(cbry)) {
            cbryList = Arrays.asList(cbry.split(","));
        }
        overDiffTime = overDiffTime * 60;
        List<ReadOverTime> readOverTimes = readmeterhisMapper.getTimeAbnormalCollect(cbryList, yearMonth, overDiffTime, isGeneral);
        if (StringUtil.isNotNull(readOverTimes) && !readOverTimes.isEmpty()) {
            ReadOverTime readOver = new ReadOverTime();
            readOver.setCbryName("合计");
            Integer allCount = 0;
            Float allTime = 0.0f;
            for (ReadOverTime readOverTime : readOverTimes) {
                allCount = allCount + readOverTime.getOverTimeCount();
                allTime = allCount * readOverTime.getAverageDiffTime();
            }
            Float averageTime = new BigDecimal(allTime).divide(new BigDecimal(allCount), 2, BigDecimal.ROUND_HALF_UP).floatValue();
            readOver.setOverTimeCount(allCount);
            readOver.setAverageDiffTime(averageTime);
            readOverTimes.add(readOver);
        }
        return readOverTimes;
    }

    @Override
    public IPage<ReadOverTimeDetail> getTimeAbnormalTwo(Page page, String cbry, String yearMonth, Integer overDiffTime, HttpServletResponse response, String isGeneral) {
        isGeneral = "1".equals(isGeneral) ? "1" : "0";
        if (StringUtil.isEmpty(yearMonth)) {
            throw new ToflyDeniedException("请选择月份");
        }
        if (StringUtil.isNull(overDiffTime)) {
            throw new ToflyDeniedException("请选择间隔时长");
        }
        List<String> cbryList = null;
        overDiffTime = overDiffTime * 60;
        if (StringUtil.isNotEmpty(cbry)) {
            cbryList = Arrays.asList(cbry.split(","));
        }
        return readmeterhisMapper.getTimeAbnormalTwo(page, cbryList, yearMonth, overDiffTime, isGeneral);
    }

}
