package com.engine.matfron.service.impl;

import com.engine.core.impl.Service;
import com.engine.matfron.entity.*;
import com.engine.matfron.exception.CustomizeRunTimeException;
import com.engine.matfron.service.StatisticsPortalService;
import com.engine.matfron.util.CommonDateUtil;
import com.engine.matfron.util.CommonUtils;
import com.weaver.general.BaseBean;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.YearMonth;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @Author liang.cheng
 * @Date 2023/9/26 5:52 PM
 * @Description:
 * @Version 1.0
 */
public class StatisticsPortalServiceImpl extends Service implements StatisticsPortalService {


    private final DecimalFormat df = new DecimalFormat("#.00");

    @Override
    public LinkedList<PortalTopVO> getPortalTop() {
        RecordSet rs = new RecordSet();
        LinkedList<PortalTopVO> portalTopVOList = new LinkedList<>();

        rs.executeQuery("select count(1) as count from hrmresource where status < 4");
        rs.next();
        Integer count = Util.getIntValue(rs.getString("count"), 0);
        portalTopVOList.add(PortalTopVO.builder().title("在职人数总数").count(count).build());

        rs.executeQuery("select count(1) as sum from hrsa_insurance_base_info where run_status in (2,3) and delete_type = 0");
        rs.next();
        portalTopVOList.add(PortalTopVO.builder().title("社保缴纳人数").count(Util.getIntValue(rs.getString("sum"), 0)).build());

        List<String> birthdayList = new ArrayList<>();
        rs.executeQuery("select birthday from hrmresource where status < 4 and birthday is not null and birthday <> ''");
        while (rs.next()) {
            birthdayList.add(Util.null2String(rs.getString("birthday")));
        }

        double averageAge = birthdayList.stream()
                .map(CommonUtils::parseLocalDate)
                .mapToInt(CommonUtils::calculateAge)
                .average()
                .orElse(0);
        String avgAge = df.format(averageAge);
        portalTopVOList.add(PortalTopVO.builder().title("平均年龄").count(avgAge).build());

        String startMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateStartOfMonth(YearMonth.now()));
        String endMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateEndOfMonth(YearMonth.now()));
        rs.executeQuery("select count(1) as sum from hrmresource where status < 4 and companystartdate >= ? and companystartdate <= ？",startMonth,endMonth);
        rs.next();
        Integer sum = Util.getIntValue(rs.getString("sum"),0);
        portalTopVOList.add(PortalTopVO.builder().title("本月新入职人员").count(sum).build());

        return portalTopVOList;
    }

    @SneakyThrows
    @Override
    public OptionVO getPortalDepartment()  {
        RecordSet rs = new RecordSet();
        LinkedList<String> xData = new LinkedList<>();
        LinkedList<Integer> yData = new LinkedList<>();
        DepartmentComInfo comInfo = new DepartmentComInfo();

        List<Integer> ids = new ArrayList<>();
        rs.executeQuery("select id,departmentname from hrmdepartment where supdepid = 0 and (canceled = 0 or canceled is null)");
        while (rs.next()) {
            xData.add(Util.null2String(rs.getString("departmentname")));
            ids.add(Util.getIntValue(rs.getString("id")));
        }

        List<DepartmentParam> deptList = new ArrayList<>();
        rs.executeQuery("SELECT d.id, CASE WHEN t.count IS NULL THEN 0 ELSE t.count END AS num \n" +
                " FROM hrmdepartment d left join (SELECT departmentid, COUNT(1) AS count FROM hrmresource where status < 4 GROUP BY departmentid) t  ON d.id = t.departmentid \n" +
                " where d.id in ("+StringUtils.join(ids,",")+")");
        while (rs.next()) {
            int deptid = Util.getIntValue(rs.getString("id"));
            int num = Util.getIntValue(rs.getString("num"));

            ArrayList<String> allSubDepartment = new ArrayList<>();
            comInfo.getAllChildDeptByDepId(allSubDepartment, String.valueOf(deptid));
            if (CollectionUtils.isNotEmpty(allSubDepartment)) {
                int count = countBydeptIds(StringUtils.join(allSubDepartment,","));
                num = num + count;
            }

            yData.add(num);
            deptList.add(DepartmentParam.builder().departmentId(deptid).count(num).build());
        }


        int max = Collections.max(yData);
        int ceil =(int) Math.ceil((double) max / 5);
        ceil = CommonUtils.roundUpToNearestTen(ceil);
        int roundedMax = CommonUtils.roundedMax(ceil, 5);

        return OptionVO.builder()
                .titleText("一级部门人数统计")
                .xData(xData)
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .yData(yData)
                .build();
    }

    @Override
    public OptionVO getPortalSubCompany() {
        RecordSet rs = new RecordSet();
        LinkedList<Integer> yData = new LinkedList<>();

        List<YearMonth> yearMonths = CommonDateUtil.getYearMonths(LocalDate.now());
        yearMonths.forEach(yearMonth -> {
            String startMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateStartOfMonth(yearMonth));
            String endMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateEndOfMonth(yearMonth));
            rs.executeQuery("select count(1) as sum from hrmresource where status < 4  and companystartdate <= ?",endMonth);
            if (rs.next()) {
                Integer sum = Util.getIntValue(rs.getString("sum"),0);
                yData.add(sum);
            }

        });

        int max = Collections.max(yData);
        int ceil =(int) Math.ceil((double) max / 5);
        ceil = CommonUtils.roundUpToNearestTen(ceil);
        int roundedMax = CommonUtils.roundedMax(ceil, 5);

        return OptionVO.builder()
                .titleText("各月份分部总人数")
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .yData(yData)
                .build();
    }

    @Override
    public OptionVO getPortalEthnic() {
        RecordSet rs = new RecordSet();
        List<String> colorList = Arrays.asList("#6e94f3","#faf0e6","#7cfc00","#ao20f0","#00ced1","#83d8ae","#697695","#8ac9e9","#9933fa","#c0ff3e","#ffe4c4","#cd6090");
        LinkedList<SeriesParam> seriesData = new LinkedList<>();
        LinkedList<String> nameSet = new LinkedList<>();

        rs.executeQuery("select distinct folk,count(1) as sums from hrmresource where status < 4 \n" +
                " and folk is not null group by folk");
        while (rs.next()) {
            Random random = new Random();
            String color = colorList.get(random.nextInt(colorList.size()));
            String name = Util.null2String(rs.getString("folk"));
            seriesData.add(SeriesParam.builder().value(Util.getDoubleValue(rs.getString("sums")))
                    .name(name).color(color).build());
            nameSet.add(name);
        }

        double percentage = seriesData.stream().mapToDouble(SeriesParam::getValue).sum();
        seriesData.forEach(item -> item.setValue(Double.valueOf(df.format((item.getValue() * 100) / percentage))));

//        LinkedList<String> legendDataFirst = null;
//        if (nameSet.size() > 2) {
//            int splitSize = nameSet.size() / 2;
//            legendDataFirst = nameSet.stream()
//                    .collect(Collectors.partitioningBy(e -> nameSet.indexOf(e) < splitSize,
//                            Collectors.toCollection(LinkedList::new)))
//                    .get(false);
//            nameSet.removeAll(legendDataFirst);
//        }

        return OptionVO.builder()
                .titleText("民族分析")
                .legendDataTwo(nameSet)
                .seriesData(seriesData)
                .build();
    }

    @Override
    public OptionVO getHomePlace() {
        RecordSet rs = new RecordSet();
        List<String> colorList = Arrays.asList("#ao20f0","#8ac9e9","#697695","#83d8ae","#faf0e6","#7cfc00","#6e94f3","#9933fa","#c0ff3e","#00ced1","#ffe4c4","#cd6090");
        LinkedList<SeriesParam> seriesData = new LinkedList<>();
        LinkedList<String> legendData = new LinkedList<>();

        rs.executeQuery("select h.locationid,l.locationname,count(1) as num  from hrmresource h\n" +
                " left join hrmlocations l on h.locationid = l.id\n" +
                " where h.status < 4 and h.locationid is not null group by h.locationid,l.locationname");
        while (rs.next()) {
            String locationname = Util.null2String(rs.getString("locationname"));
            legendData.add(locationname);
            Random random = new Random();
            String color = colorList.get(random.nextInt(colorList.size()));
            seriesData.add(SeriesParam.builder().value(Util.getDoubleValue(rs.getString("num"))).name(locationname).color(color).build());
        }

        List<Double>  values = seriesData.stream().map(SeriesParam :: getValue).collect(Collectors.toList());
        double percentage = values.stream().mapToDouble(Double::doubleValue).sum();
        seriesData.forEach(item -> item.setValue(Double.valueOf(df.format((item.getValue() * 100) / percentage))));

        return OptionVO.builder()
                .titleText("归属地分析")
                .legendDataFirst(legendData)
                .seriesData(seriesData)
                .build();
    }

    @Override
    public OptionVO getEducational() {
        RecordSet rs = new RecordSet();
        List<String> colorList = Arrays.asList("#faf0e6","#7cfc00","#ee8164","#9933fa","#f19c45","#6fcecf","#507ef7","#ao20f0");
        LinkedList<SeriesParam> seriesData = new LinkedList<>();
        LinkedList<String> nameSet = new LinkedList<>();


        rs.executeQuery("select distinct h.educationlevel,count(1) as sum,d.name from hrmresource h\n" +
                "left join hrmeducationlevel d on h.educationlevel = d.id where status < 4 \n" +
                "and h.educationlevel is not null and d.name is not null group by h.educationlevel,d.name ");
        int index = 0;
        while (rs.next()) {
            if (index > colorList.size()){
                index = 0;
            }
            index++;
            String name = Util.formatMultiLang (Util.null2String(rs.getString("name")));

            seriesData.add(SeriesParam.builder().value(Util.getDoubleValue(rs.getString("sum")))
                    .name(name).color(colorList.get(index)).build());
            nameSet.add(name);
        }

        double percentage = seriesData.stream().mapToDouble(SeriesParam::getValue).sum();
        seriesData.forEach(item -> item.setValue(Double.valueOf(df.format((item.getValue() * 100) / percentage))));

        LinkedList<String> legendDataFirst = new LinkedList<>();

        if (nameSet.size() > 2) {
            legendDataFirst = treeSetSplitExample(nameSet);
        }

        return OptionVO.builder()
                .titleText("学历分析")
                .legendDataFirst(legendDataFirst)
                .legendDataTwo(nameSet)
                .seriesData(seriesData)
                .build();
    }

    @Override
    public OptionVO getSurname() {
        RecordSet rs = new RecordSet();
        LinkedList<SeriesParam> seriesData = new LinkedList<>();

        List<SurnameParam> surnameList = new ArrayList<>();
        rs.executeQuery("select companyworkyear,count(1) as sum from hrmresource where status < 4 " +
                " and companyworkyear is not null  group by companyworkyear ");
        while (rs.next()) {
            surnameList.add(SurnameParam.builder().companyworkyear(Util.getDoubleValue(rs.getString("companyworkyear"))).count(Util.getIntValue(rs.getString("sum"))).build());
        }

        List<Integer> statisticsArr = Arrays.asList(0,1,3,5,10,100);
        List<Double> statisticsList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            double count = statisticsSurname(statisticsArr.get(i), statisticsArr.get(i+1), surnameList);
            statisticsList.add(count);
        }

        double percentage = statisticsList.stream().mapToDouble(Double::doubleValue).sum();
        List<Double> newList = statisticsList.stream()
                .map(num -> Double.valueOf (df.format((num * 100 ) / percentage)))
                .collect(Collectors.toList());

        newList.forEach(count -> seriesData.add(SeriesParam.builder().value(count).build()));

        return OptionVO.builder()
                .titleText("司龄统计")
                .seriesData(seriesData)
                .build();
    }

    @Override
    public OptionVO getAgeAndSex() {
        RecordSet rs = new RecordSet();
        LinkedList<Integer> barSeriesData = new LinkedList<>();
        LinkedList<Integer> barSeriesDataTwo = new LinkedList<>();
        List<String> ageArr = Arrays.asList("16~20","21~25","26~30","31~35","36~40","41~45","46~50","51~55","56~60","61~65","66~70");

        List<String> birthdayListMen = new ArrayList<>();
        rs.executeQuery("select birthday from hrmresource where status < 4 and sex is not null and birthday is not null and birthday <> '' and sex = 0");
        while (rs.next()) {
            birthdayListMen.add(Util.null2String(rs.getString("birthday")));
        }
        List<Integer> menAge = birthdayListMen.stream()
                .map(birthday -> {
                    LocalDate birthdate = LocalDate.parse(birthday);
                    LocalDate now = LocalDate.now();
                    return Period.between(birthdate, now).getYears();
                })
                .collect(Collectors.toList());



        for (int i = 0; i < ageArr.size(); i++) {
            String[] split = ageArr.get(i).split("~");
            List<Integer> collect = menAge.stream().filter(item -> item > Integer.parseInt(split[0]) && item <= Integer.parseInt(split[1])).collect(Collectors.toList());
            barSeriesData.add(collect.size());
        }

        int yMax = barSeriesData.stream().max(Integer::compare).orElse(0);



        List<String> birthdayListWomen = new ArrayList<>();
        rs.executeQuery("select birthday from hrmresource where status < 4 and sex is not null and birthday is not null and sex = 1");
        while (rs.next()) {
            birthdayListWomen.add(Util.null2String(rs.getString("birthday")));
        }
        List<Integer> womenAge = birthdayListWomen.stream()
                .map(birthday -> {
                    LocalDate birthdate = LocalDate.parse(birthday);
                    LocalDate now = LocalDate.now();
                    return Period.between(birthdate, now).getYears();
                })
                .collect(Collectors.toList());


        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 0; i < ageArr.size(); i++) {
            String[] split = ageArr.get(i).split("~");
            List<Integer> collect = womenAge.stream().filter(item -> item > Integer.parseInt(split[0]) && item <= Integer.parseInt(split[1])).collect(Collectors.toList());
            barSeriesDataTwo.add(-collect.size());
            list.add(collect.size());
        }

        int yMin = -(list.stream().max(Integer::compare).orElse(0));
        int sum = yMax > Math.abs(yMin) ? yMax  : yMin ;

        int divisor = sum % 6;
        sum = sum + (6 - divisor) + 12;
        int ceil =(int) Math.ceil((double) sum / 3);

        return OptionVO.builder()
                .titleText("年龄与性别分析")
                .yMin(-sum)
                .yMax(sum)
                .yInterval(ceil)
                .barSeriesData(barSeriesData)
                .barSeriesDataTwo(barSeriesDataTwo)
                .build();
    }

    @Override
    public OptionVO getJobType() {
        RecordSet rs = new RecordSet();
        LinkedList<String> xData = new LinkedList<>();
        LinkedList<Integer> barSeriesData = new LinkedList<>();

        rs.executeQuery("select a.*,b.jobgroupname from (select g.id as jobgroupid,count(1) as sum from hrmresource h \n" +
                " left join hrmjobtitles j on h.jobtitle = j.id\n" +
                " left join hrmjobactivities c on j.jobactivityid = c.id\n" +
                " left join hrmjobgroups g on c.jobgroupid = g.id\n" +
                " where h.status < 4 and g.id is not null group by g.id) as a left join hrmjobgroups b on a.jobgroupid = b.id");

        while (rs.next()) {
            xData.add(Util.null2String(rs.getString("jobgroupname")));
            barSeriesData.add(Util.getIntValue(rs.getString("sum")));
        }

        int max = Collections.max(barSeriesData);
        int ceil =(int) Math.ceil((double) max / 4);
        ceil = CommonUtils.roundUpToNearestTen(ceil);
        int roundedMax = CommonUtils.roundedMax(ceil, 4);

        return OptionVO.builder()
                .titleText("职务类别统计")
                .xData(xData)
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .barSeriesData(barSeriesData)
                .build();
    }

    @Override
    public Map<String,Object> getLeaveMonth(String departmentIds) {
        Map<String,Object> data = new HashMap<>(4);
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        String startMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateStartOfMonth(YearMonth.now()));
        String endMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateEndOfMonth(YearMonth.now()));
        LinkedList<String> xData = new LinkedList<>();
        LinkedList<Integer> barSeriesData = new LinkedList<>();
        LinkedList<BrowserParam> browser = new LinkedList<>();

        StringBuilder sql = new StringBuilder();
        sql.append("select t.departmentname, t.id,CASE \n" +
                "        WHEN a.sum IS NULL THEN 0 \n" +
                "        ELSE a.sum \n" +
                "    END AS num from hrmdepartment t \n" +
                " left join (select s.departmentid,count(1) as sum from  hrmstatushistory h left join hrmresource s on h.resourceid = s.id " +
                " where h.type_n = 5 and  h.changedate >= ? and h.changedate <= ? group by s.departmentid ) a\n" +
                " on t.id = a.departmentid ");

        sql.append(" where (t.canceled = 0 or t.canceled is null)");

        if(StringUtils.isNotEmpty(departmentIds)) {
            sql.append(" and t.id in (").append(departmentIds).append(")");
        }

        bb.writeLog("sql2023"+sql.toString()+"->"+startMonth+endMonth);
        rs.executeQuery(sql.toString(),startMonth,endMonth);

        int i = 0;
        while (rs.next() && i < 5) {
            i++;
            Integer id = Util.getIntValue(rs.getString("id"));
            String name = Util.null2String(rs.getString("departmentname"));
            int num = Util.getIntValue(rs.getString("num"));
            xData.add(name);
            int countBydeptId = countBydeptId(id, endMonth) + num;
            barSeriesData.add( countBydeptId == 0 ? 0 : (num * 100) / countBydeptId);
            browser.add(BrowserParam.builder().id(id).name(name).build());
        }

        int max = Collections.max(barSeriesData);
        max = max < 80 ? max + 20 : 100;
        int ceil =(int) Math.ceil((double) max / 4);
        int roundedMax = CommonUtils.roundedMax(ceil, 4);

        OptionVO optionVo = OptionVO.builder().titleText("当月多部门离职率统计")
                .xData(xData)
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .barSeriesData(barSeriesData)
                .build();


        data.put("replaceDatas",browser);
        data.put("optionVo",optionVo);

        return data;
    }

    @Override
    public Map<String,Object> getLeaveYear(String departmentIds) {
        Map<String,Object> data = new HashMap<>(4);
        RecordSet rs = new RecordSet();
        LinkedList<String> legendDataFirst = new LinkedList<>();
        LinkedList<Integer> barSeriesData = new LinkedList<>();
        LinkedList<Integer> barSeriesDataTwo = new LinkedList<>();
        LinkedList<Integer> barSeriesDataThree = new LinkedList<>();
        DepartmentComInfo comInfo = new DepartmentComInfo();
        LinkedList<BrowserParam> browser = new LinkedList<>();
        List<Integer> deptList = new ArrayList<>();

        if(StringUtils.isNotEmpty(departmentIds)) {
            deptList = Arrays.stream(departmentIds.split(",")).map(Integer::parseInt)
                    .collect(Collectors.toList());

        }else {
//            rs.executeQuery("select distinct t.id from hrmdepartment t \n" +
//                    " left join hrmresource h on t.id = h.departmentid\n" +
//                    " left join hrmstatushistory s on h.id = s.resourceid where s.type_n = 5 ");
            rs.executeQuery("select id from hrmdepartment where canceled = 0 or canceled is null");
            while (rs.next()) {
                deptList.add(Util.getIntValue(rs.getString("id")));
            }

        }

        deptList = deptList.stream().limit(3).collect(Collectors.toList());

        deptList.forEach(dept -> {
            try {
                String departmentName = comInfo.getDepartmentName(String.valueOf(dept));
                legendDataFirst.add(departmentName);
                browser.add(BrowserParam.builder().id(dept).name(departmentName).build());
            } catch (Exception e) {
                throw new CustomizeRunTimeException("所选部门不存在");
            }
        });

        List<YearMonth> yearMonths = CommonDateUtil.getYearMonths(LocalDate.now());
        List<Integer> finalDeptList = deptList;
        yearMonths.forEach(yearMonth -> {
            String startMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateStartOfMonth(yearMonth));
            String endMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateEndOfMonth(yearMonth));
            for (int i = 0; i < 3; i++) {
                Integer value = calculateLeave(finalDeptList.get(i), startMonth, endMonth);
                switch (i) {
                    case 0:
                        barSeriesData.add(value);
                        break;
                    case 1:
                        barSeriesDataTwo.add(value);
                        break;
                    case 2:
                        barSeriesDataThree.add(value);
                        break;
                    default:
                        break;

                }
            }

        });

        LinkedList<Integer> sumData = new LinkedList<>();
        sumData.addAll(barSeriesData);
        sumData.addAll(barSeriesDataTwo);
        sumData.addAll(barSeriesDataThree);

        int max = Collections.max(sumData);
        max = max < 80 ? max + 20 : 100;
        int ceil =(int) Math.ceil((double) max / 4);
        int roundedMax = CommonUtils.roundedMax(ceil, 4);

        OptionVO optionVo = OptionVO.builder().titleText("年度离职率统计")
                .legendDataFirst(legendDataFirst)
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .barSeriesData(barSeriesData)
                .barSeriesDataTwo(barSeriesDataTwo)
                .barSeriesDataThree(barSeriesDataThree)
                .build();

        data.put("replaceDatas",browser);
        data.put("optionVo",optionVo);

        return data;
    }

    private Integer calculateLeave(Integer id,String startMonth,String endMonth) {
        RecordSet rs = new RecordSet();
        String sql = ("select t.departmentname, t.id,CASE \n" +
                "        WHEN a.sum IS NULL THEN 0 \n" +
                "        ELSE a.sum \n" +
                "    END AS num from hrmdepartment t \n" +
                " left join (select s.departmentid,count(1) as sum from  hrmstatushistory h left join hrmresource s on h.resourceid = s.id " +
                " where type_n = 5 and  changedate >= ? and changedate <= ? group by s.departmentid ) a\n" +
                " on t.id = a.departmentid where t.id = ? and (t.canceled = 0 or t.canceled is null)");
        BaseBean bb = new BaseBean();
        bb.writeLog("calculateLeave "+sql);
        rs.executeQuery(sql,startMonth,endMonth,id);
        rs.next();
        int num = Util.getIntValue(rs.getString("num"));
        int countBydeptId = countBydeptId(id, endMonth) + num;
        return countBydeptId == 0 ? 0 : ((num * 100) / countBydeptId);
    }



    /**
     * 根据日期部门人数统计
     * @param  departmentId
     * @return
     */
    private int countBydeptId(Integer departmentId,String endMonth) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select count(1) as sum from hrmresource where departmentId = ? and status < 4 and companystartdate <= ? ",departmentId,endMonth);
        rs.next();
        return Util.getIntValue(rs.getString("sum"));
    }


    /**
     * 子部门日数统计
     * @param deptIds
     * @return
     */
    private int countBydeptIds(String deptIds) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select count(1) as sum from hrmresource where departmentId in ("+deptIds+")");
        rs.next();
        return Util.getIntValue(rs.getString("sum"));
    }

    /**
     * 根据范围统计司龄的个数
     * @return
     */
    private Double statisticsSurname(Integer min,Integer max,List<SurnameParam> surnameList) {
        return surnameList.stream().filter(item -> item.getCompanyworkyear() > min && item.getCompanyworkyear() <= max)
                .mapToDouble(SurnameParam::getCount).sum();
    }

    /**
     * 平分legendData
     * @param nameSet
     */
    private LinkedList<String> treeSetSplitExample(LinkedList<String> nameSet) {
        int splitSize = nameSet.size() / 2;
        LinkedList<String> legendDataFirst = nameSet.stream()
                .collect(Collectors.partitioningBy(e -> nameSet.indexOf(e) < splitSize,
                        Collectors.toCollection(LinkedList::new)))
                .get(false);
        nameSet.removeAll(legendDataFirst);
        return legendDataFirst;
    }

    /**
     * 多语言匹配中文
     * @param input
     * @return
     */
    private String chineseSubstringExample(String input) {

        String r = "7.*`~`8";
        Pattern pattern1 = Pattern.compile(r);
        Matcher matcher = pattern1.matcher(input);

        while (matcher.find()) {
            input = matcher.group(0);
        }

        // 使用正则表达式匹配中文
        String pattern = "[\u4E00-\u9FA5\u8FBD-\u9FBB\uFA0E-\uFA29]+";
        Pattern s = Pattern.compile(pattern);
        Matcher m = s.matcher(input);
        while (m.find()) {
            input = m.group(0);
        }
        return input;
    }

}
