package com.xintong.visualinspection.visuallnspection_fjq.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xintong.visualinspection.bean.CheckTaskPeriod;
import com.xintong.visualinspection.bean.FeeStation;
import com.xintong.visualinspection.bean.FwqDeptStatistic;
import com.xintong.visualinspection.bean.FwqStatisticsBean;
import com.xintong.visualinspection.bean.Item;
import com.xintong.visualinspection.bean.Organ;
import com.xintong.visualinspection.service.CommonService;
import com.xintong.visualinspection.visuallnspection_fjq.dao.FwqCheckDeptStatisticsDao;
import com.xintong.visualinspection.visuallnspection_fjq.dao.FwqStatisticsDao;
import com.xintong.visualinspection.visuallnspection_fjq.service.StatisticsService_F;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文件名：StatisticsService_FImpl
 * 版本信息：日期：2017/4/7 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 *
 * @author wenhongquan
 * @date 2018/05/02
 */

@Service
public class StatisticsService_FImpl implements StatisticsService_F {

    private static final Logger logger = LoggerFactory.getLogger(StatisticsService_FImpl.class);

    @Autowired
    private FwqStatisticsDao fwqStatisticsDao;
    @Autowired
    private FwqCheckDeptStatisticsDao fwqCheckDeptStatisticsDao;

    @Reference(version = "1.0.0",
            application = "${dubbo.application.id}",
            registry = "${dubbo.registry.address}")
    private CommonService commonService;

    public List<FwqStatisticsBean> getOperationInfo(FwqStatisticsBean obj) {

        // 获得所有服务区数据
        List<FeeStation> saList = commonService.getAllDeptByLayer("SA");
        Map<Long, FwqStatisticsBean> mapStationInfos = new HashMap<>();
        for (FeeStation sta : saList) {
            FwqStatisticsBean obj2 = new FwqStatisticsBean();
            obj2.setDept_id(Long.valueOf(sta.getDeptid()));
            obj2.setName(sta.getName());
            mapStationInfos.put(Long.valueOf(sta.getDeptid()), obj2);
        }

        // 获取公司检查的某个收费站的受检次数和扣分合计
        List<FwqStatisticsBean> company_beans =  getFeeStationCheckItemScore(obj);
        // 获取第三方暗访稽查的某个服务区的受检次数和扣分合计
        obj.setCheck_type(8);
        List<FwqStatisticsBean> third_beans = fwqStatisticsDao.getselectFeeStationOperationScoreDetail(obj);
        // 获取现场稽查的某个服务区的受检次数和扣分合计
        obj.setCheck_type(9);
        List<FwqStatisticsBean> onsite_beans = fwqStatisticsDao.getselectFeeStationOperationScoreDetail(obj);

        for (FwqStatisticsBean company_bean : company_beans) {
            mapStationInfos.get(company_bean.getDept_id()).setCompany_check_num(company_bean.getChecked_num());
            mapStationInfos.get(company_bean.getDept_id()).setCompany_total_score(company_bean.getAll_check_score());
        }
        for (FwqStatisticsBean third_bean : third_beans) {
            mapStationInfos.get(third_bean.getDept_id()).setThird_check_num(third_bean.getChecked_num() > 1 ? 1 : third_bean.getChecked_num());
            mapStationInfos.get(third_bean.getDept_id()).setThird_total_score(third_bean.getCheck_total_score());
        }

        for (FwqStatisticsBean onsite_bean : onsite_beans) {
            mapStationInfos.get(onsite_bean.getDept_id()).setOnsite_check_num(onsite_bean.getChecked_num() > 1 ? 1 : onsite_bean.getChecked_num());
            mapStationInfos.get(onsite_bean.getDept_id()).setOnsite_total_score(onsite_bean.getCheck_total_score());
        }
        // 计算出每个收费站的总平均扣分和平均得分
        Set<Map.Entry<Long, FwqStatisticsBean>> stationInfos = mapStationInfos.entrySet();
        // 保留二位小数
        DecimalFormat df = new DecimalFormat("0.00");
        for (Map.Entry<Long, FwqStatisticsBean> station : stationInfos) {
            float avg = 0;
            FwqStatisticsBean value = station.getValue();
            value.setThird_check_num(1);
            value.setOnsite_check_num(1);
            // 设置总平均扣分
            if (value.getCompany_check_num() > 0 || value.getThird_check_num() > 0) {
                avg += (value.getCompany_total_score() + value.getThird_total_score()) / 2.0 / (value.getCompany_check_num() + value.getThird_check_num());
            }
            if (value.getOnsite_check_num() > 0) {
                avg += value.getOnsite_total_score() / 2.0 / value.getOnsite_check_num();
            }
            value.setCheck_total_avg(df.format(avg));
            // 设置平均得分
            Float score_avg = (1000 - Float.valueOf(df.format(avg)));
            value.setScore_avg(score_avg.toString());
        }
        List<FwqStatisticsBean> sortList = new ArrayList<>(mapStationInfos.values());
        sortList.sort(new Comparator<FwqStatisticsBean>() {
            @Override
            public int compare(FwqStatisticsBean o1, FwqStatisticsBean o2) {
                return o1.compare3To(o2);
            }
        });

        List<FwqStatisticsBean> temp = new ArrayList<>();
        temp.addAll(sortList);
        Map<Long, Organ> deptMap = commonService.getDeptMap();
        for (FwqStatisticsBean aSortList : sortList) {
            if (deptMap.get(aSortList.getDept_id()) != null) {
                if (deptMap.get(aSortList.getDept_id()).getCreattime().getTime() > obj.getEnd_date().getTime()) {
                    temp.remove(aSortList);
                }
            }

        }
        sortList = temp;

        for (int j = 0; j < sortList.size(); j++) {
            FwqStatisticsBean statisticsBean = sortList.get(j);
            // 公司排名
            if (j == 0) {
                statisticsBean.setCompany_ranking2(1);
            } else {
                FwqStatisticsBean bean = sortList.get(j - 1);
                if (statisticsBean.compare3To(bean) == 0) {
                    statisticsBean.setCompany_ranking2(bean.getCompany_ranking2());
                } else {
                    statisticsBean.setCompany_ranking2(j + 1);
                }
            }
        }

        return sortList;
    }

    @Override
    public void getOperationInfo(FwqStatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
        List<FwqStatisticsBean> lists = getOperationInfo(obj);
        Map<String, Object> map = new HashMap<>(1);
        map.put("list", lists);
        exportExcel("运营管理综合检查情况统计表", "fwq_operation_info", map, resp);
    }

    public Map<String, List<FwqDeptStatistic>> getDeptStatistic(FwqDeptStatistic obj) {

        List<CheckTaskPeriod> checkTaskPeriods = commonService.getAllCheckTaskPeriod();
        SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat ff1 = new SimpleDateFormat("MM月");

        for (CheckTaskPeriod p : checkTaskPeriods) {
            if (obj.getStart_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
                obj.setStartperiod_id(p.getId());
            }
            if (obj.getEnd_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
                obj.setEndperiod_id(p.getId());
            }
        }
        if (obj.getStart_date() > (checkTaskPeriods.get(checkTaskPeriods.size() - 1).getEndtime().getTime() - 1 * 1000 * 60 * 60)) {
            return null;
        }
        if (obj.getEnd_date() < (checkTaskPeriods.get(0).getEndtime().getTime() - 1 * 1000 * 60 * 60)) {
            return null;
        }
        if (obj.getStart_date() < (checkTaskPeriods.get(0).getEndtime().getTime() - 1 * 1000 * 60 * 60)) {
            obj.setStartperiod_id(checkTaskPeriods.get(0).getId());
        }
        if (obj.getEnd_date() > (checkTaskPeriods.get(checkTaskPeriods.size() - 1).getEndtime().getTime() - 1 * 1000 * 60 * 60)) {
            obj.setEndperiod_id(checkTaskPeriods.get(checkTaskPeriods.size() - 1).getId());
        }

        List<FwqDeptStatistic> deptStatistics = fwqCheckDeptStatisticsDao.selectdepts(obj);
        Map<String, List<FwqDeptStatistic>> listMap = new HashMap<>();
        Map<Long, List<FwqDeptStatistic>> listMap1 = new HashMap<>();
        if (deptStatistics.size() > 0) {
            Map<Long, Organ> deptMap = commonService.getDeptMap();
            for (FwqDeptStatistic s : deptStatistics) {
                //按月统计
                if (listMap.get(s.getPeriod_id() + "") == null) {
                    List<FwqDeptStatistic> t = new ArrayList<>();
                    t.add(s);
                    listMap.put(s.getPeriod_id() + "", t);
                } else {
                    List<FwqDeptStatistic> t = listMap.get(s.getPeriod_id() + "");
                    t.add(s);
                    listMap.put(s.getPeriod_id() + "", t);
                }


                //按部门统计
                if (listMap1.get(s.getDept_id()) == null) {
                    List<FwqDeptStatistic> t = new ArrayList<>();
                    t.add(s);
                    listMap1.put(s.getDept_id(), t);
                } else {
                    List<FwqDeptStatistic> t = listMap1.get(s.getDept_id());
                    t.add(s);
                    listMap1.put(s.getDept_id(), t);
                }
            }

            //按月划分
            for (CheckTaskPeriod p : checkTaskPeriods) {
                if (p.getId() >= obj.getStartperiod_id() && p.getId() <= obj.getEndperiod_id()) {
                    //符合要求的周期 计算得分
                    for (Long tp : listMap1.keySet()
                            ) {
                        List<FwqDeptStatistic> deptStatistics1 = listMap1.get(tp);
                        //该周期每一个部门
                        //计算累计
                        Integer s = 0;
                        for (FwqDeptStatistic ss : deptStatistics1
                                ) {
                            if (ss.getPeriod_id() <= p.getId()) {
                                s += ss.getIntegral();
                            }
                        }

                        //赋值
                        for (FwqDeptStatistic ss : deptStatistics1
                                ) {
                            if (ss.getPeriod_id().equals(p.getId())) {
                                ss.setTotal_integral(s);
                                ss.setDept_name(deptMap.get(ss.getDept_id()).getOrganname());
                                ss.setTime(ff.format(p.getEndtime()));
                            }
                        }
                    }

                    //计算排名
                    List<FwqDeptStatistic> deptStatistics1 = listMap.get(p.getId() + "");
                    if (deptStatistics1 != null) {
                        deptStatistics1.sort(new Comparator<FwqDeptStatistic>() {
                            @Override
                            public int compare(FwqDeptStatistic o1, FwqDeptStatistic o2) {
                                return o1.getTotal_integral() > o2.getTotal_integral() ? -1 : 1;
                            }
                        });
                        for (int j = 0; j < deptStatistics1.size(); j++) {
                            FwqDeptStatistic statisticsBean = deptStatistics1.get(j);
                            // 排名
                            if (j == 0) {
                                statisticsBean.setTotal_ranking(1);
                            } else {
                                FwqDeptStatistic bean = deptStatistics1.get(j - 1);
                                if (statisticsBean.getTotal_integral().equals(bean.getTotal_integral())) {
                                    statisticsBean.setTotal_ranking(bean.getTotal_ranking());
                                } else {
                                    statisticsBean.setTotal_ranking(j + 1);
                                }
                            }
                        }
                    }

                }
            }

            //排序
            for (String i : listMap.keySet()
                    ) {
                listMap.get(i).sort(new Comparator<FwqDeptStatistic>() {
                    @Override
                    public int compare(FwqDeptStatistic o1, FwqDeptStatistic o2) {
                        return o1.getDept_id() > o2.getDept_id() ? 1 : -1;
                    }
                });
            }
            listMap.clear();
            for (Long s : listMap1.keySet()
                    ) {
                List<FwqDeptStatistic> l = listMap1.get(s);
                l.sort(new Comparator<FwqDeptStatistic>() {
                    @Override
                    public int compare(FwqDeptStatistic o1, FwqDeptStatistic o2) {
                        return o1.getPeriod_id() > o2.getPeriod_id() ? 1 : -1;
                    }
                });
                listMap.put(l.get(0).getDept_id() + "", l);
            }

            if (obj.getType() != null && obj.getType().equals(1)) {
                //excel数据
                for (CheckTaskPeriod p : checkTaskPeriods) {
                    if (p.getId() >= obj.getStartperiod_id() && p.getId() <= obj.getEndperiod_id()) {
                        //符合要求的周期 计算得分
                        for (String i : listMap.keySet()
                                ) {
                            //单个部门的
                            List<FwqDeptStatistic> l = listMap.get(i);
                            FwqDeptStatistic temp = null;
                            if (l.size() < 1) {
                                continue;
                            }
                            boolean isin = false;
                            for (FwqDeptStatistic s : l
                                    ) {
                                if (s.getPeriod_id().equals(p.getId())) {
                                    isin = true;
                                    temp = s;
                                    break;
                                }
                            }
                            //不在里面
                            if (!isin) {
                                FwqDeptStatistic s = l.get(0).clone();
                                s.setScore((double) -1);
                                s.setPeriod_id(p.getId());
                                s.setIntegral(-1);
                                s.setTotal_integral(-1);
                                s.setTotal_ranking(-1);
                                temp = s;
                                l.add(s);
                            }

                            temp.setMString(ff1.format(p.getEndtime()));
                            listMap.put(i, l);

                        }
                    }
                }
                //再次排序
                for (String s : listMap.keySet()
                        ) {
                    List<FwqDeptStatistic> l = listMap.get(s);
                    l.sort(new Comparator<FwqDeptStatistic>() {
                        @Override
                        public int compare(FwqDeptStatistic o1, FwqDeptStatistic o2) {
                            return o1.getPeriod_id() > o2.getPeriod_id() ? 1 : -1;
                        }
                    });
                    listMap.put(l.get(0).getDept_id() + "", l);
                }
            }
        }


        return listMap;
    }

    @Override
    public void getDeptStatisticExcel(FwqDeptStatistic obj, HttpServletRequest req, HttpServletResponse resp) {
        obj.setType(1);
        Map<String, List<FwqDeptStatistic>> listMap = this.getDeptStatistic(obj);
        SimpleDateFormat d = new SimpleDateFormat("yyyy/MM");
        List<Integer> temp = new ArrayList<>();
        for (int i = 1; i <= listMap.keySet().size(); i++) {
            temp.add(i);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("datas", listMap);
        map.put("list", temp);
        map.put("title", "服务区-营运管理提升综合成绩汇总表" + "(" + d.format(obj.getStart_date()) + "---" + d.format(obj.getEnd_date()) + ")");
        exportExcel("服务区-营运管理提升综合成绩汇总表", "fwq_dept_statistic", map, resp);
    }

    public List<FwqStatisticsBean> getFeeStationCheckItemScore(FwqStatisticsBean obj) {

        // 获得所有服务区数据
        List<FeeStation> saList = commonService.getAllDeptByLayer("SA");
        Map<Long, Item> itemMap = commonService.getItemMap();
        Map<Long, FwqStatisticsBean> mapStationInfos = new HashMap<>();
        for (FeeStation sta : saList) {
            FwqStatisticsBean obj2 = new FwqStatisticsBean();
            obj2.setDept_id(Long.valueOf(sta.getDeptid()));
            obj2.setName(sta.getName());
            // 30:连云港道管;31:盐城道管;32:南通道管
            if ("30".equals(sta.getParentid())) {
                obj2.setId(1);
            } else if ("31".equals(sta.getParentid())) {
                obj2.setId(2);
            } else if ("32".equals(sta.getParentid())) {
                obj2.setId(3);
            }
            mapStationInfos.put(Long.valueOf(sta.getDeptid()), obj2);
        }

        if (obj.getStart_date() != null && obj.getEnd_date() != null) {
            CheckTaskPeriod p = commonService.getCheckTaskPeriod(obj.getStart_date().getTime()+1 * 1000 * 60 * 60, obj.getEnd_date().getTime()+1 * 1000 * 60 * 60);
            if (p != null) {
                obj.setPeriod_id(p.getId());
            }
        }

        //服务区检查次数
        List<FwqStatisticsBean> listCheckNum = fwqStatisticsDao.selectFeeStationCheckNum(obj);
        for (FwqStatisticsBean sta : listCheckNum) {
            if (mapStationInfos.containsKey(sta.getDept_id())) {
                mapStationInfos.get(sta.getDept_id()).setChecked_num(sta.getChecked_num());
//                mapStationInfos.get(sta.getDept_id()).setChecked_people_num(sta.getChecked_people_num());
            }
        }

        List<FwqStatisticsBean> listCheckedScore = fwqStatisticsDao.selectFeeStationCheckedPersonScoreDetail(obj);

        // 处理同一个服务区中,如果item的parent_id是一样的话,将这些数据结合在一起
        for (FwqStatisticsBean sta : listCheckedScore) {
            sta.setItem_id(itemMap.get(sta.getCheck_item_id().longValue()).getParent_id().intValue());
        }
        for (int i = 0; i < listCheckedScore.size(); i++) {
            for (int j = listCheckedScore.size() - 1; j > i; j--) {
                if (listCheckedScore.get(j).getDept_id().equals(listCheckedScore.get(i).getDept_id()) && listCheckedScore.get(j).getItem_id().equals(listCheckedScore.get(i).getItem_id())) {
                    listCheckedScore.get(i).setScore(listCheckedScore.get(i).getScore() + listCheckedScore.get(j).getScore());
                    listCheckedScore.remove(j);
                }
            }
        }

        for (FwqStatisticsBean sta : listCheckedScore) {
            if (mapStationInfos.containsKey(sta.getDept_id())) {
                FwqStatisticsBean statis = mapStationInfos.get(sta.getDept_id());
                statis.setAll_check_score(statis.getAll_check_score() + sta.getScore());
                // 组装扣分类型内容
                if (itemMap.get(sta.getCheck_item_id().longValue()).getParent_id() != null) {
                    sta.setId(itemMap.get(sta.getCheck_item_id().longValue()).getParent_id().intValue());
                    if (itemMap.get(sta.getCheck_item_id().longValue()).getScore() == null) {
                        sta.setName(itemMap.get(sta.getCheck_item_id().longValue()).getName());
                    } else {
                        sta.setName(itemMap.get(itemMap.get(sta.getCheck_item_id().longValue()).getParent_id()).getName());
                    }
                }
                statis.getChecked_socre_name().add(sta.getName());
                statis.getChecked_score().add(sta.getScore());
                statis.getChecked_score_ids().add(sta.getId());
            }
        }

        List<FwqStatisticsBean> sortList = new ArrayList<>(mapStationInfos.values());

        sortList.sort(new Comparator<FwqStatisticsBean>() {
            @Override
            public int compare(FwqStatisticsBean o1, FwqStatisticsBean o2) {
                if (o1.getId() > o2.getId()) {
                    return 1;
                } else if (o1.getId().equals(o2.getId())) {
                    if (o1.getChecked_num() != 0 && o2.getChecked_num() != 0) {
                        if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) > o2.getAll_check_score()
                                / (o2.getChecked_num() + 0.0)) {
                            return 1;
                        } else if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) < o2.getAll_check_score()
                                / (o2.getChecked_num() + 0.0)) {
                            return -1;
                        } else {
                            return 0;
                        }
                    } else {
                        if (o1.getChecked_num() == 0) {
                            return -1;
                        } else if (o2.getChecked_num() == 0) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                } else {
                    return -1;
                }
            }
        });

        return sortList;

    }

    @Override
    public void getFeeStationCheckItemScore(FwqStatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
        List<FwqStatisticsBean> list = getFeeStationCheckItemScore(obj);
        int totalcheckedCount = 0, totalAll = 0;
        float lygScore = 0.00f, ycScore = 0.00f, ntScore = 0.00f;
        int lygCheckNum = 0, ycCheckNum = 0, ntCheckNum = 0;
        Map<String, Integer> scoreTypeMap = new HashMap<>();
        List<String> itemAll = commonService.getCheckItemName(28L);
        Map<Long, Organ> deptMap = commonService.getDeptMap();
        // 处理数据
        for (FwqStatisticsBean st : list) {
            // id值设置 seq_checked_score
            // 平均值
            st.setCheck_score_avg(
                    (st.getChecked_num() != 0) ? st.getAll_check_score() / (st.getChecked_num() + 0.00f) : 0.00f);
            for (String i : itemAll) {
                st.getSeq_checked_score().add(getItemScore2(st, i));
            }
            st.setParent_dept_id(deptMap.get(st.getDept_id()).getParentid().longValue());
            totalcheckedCount += st.getChecked_num();
            totalAll += st.getAll_check_score();
            if (st.getParent_dept_id() == 30) {
                lygScore += st.getAll_check_score();
                lygCheckNum += st.getChecked_num();
            }
            if (st.getParent_dept_id() == 31) {
                ycScore += st.getAll_check_score();
                ycCheckNum += st.getChecked_num();
            }
            if (st.getParent_dept_id() == 32) {
                ntScore += st.getAll_check_score();
                ntCheckNum += st.getChecked_num();
            }
            st.setCheck_total_avg("");
            st.setParent_name("");
            List<String> names = st.getChecked_socre_name();
            List<Integer> scores = st.getChecked_score();
            for (int j = 0; j < names.size(); j++) {
                Integer score = scoreTypeMap.get(names.get(j));
                if (score == null) {
                    score = 0;
                }
                score += scores.get(j);
                scoreTypeMap.put(names.get(j), score);
            }
        }
        boolean lyg = false, yc = false, nt = false;
        float lygTemp = 0.00f, ycTemp = 0.00f, ntTemp = 0.00f;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getParent_dept_id() == 30 && !lyg) {
                list.get(i).setParent_name(deptMap.get(deptMap.get(list.get(i).getDept_id()).getParentid().longValue()).getOrganname());
                list.get(i).setCheck_total_avg(String.format("%.2f", lygCheckNum != 0 ? lygScore / (lygCheckNum + 0.00f) : 0.00));
                lygTemp = lygCheckNum != 0 ? lygScore / (lygCheckNum + 0.00f) : 0.00f;
                lyg = true;
            } else if (list.get(i).getParent_dept_id() == 31 && !yc) {
                list.get(i).setParent_name(deptMap.get(deptMap.get(list.get(i).getDept_id()).getParentid().longValue()).getOrganname());
                list.get(i).setCheck_total_avg(String.format("%.2f", ycCheckNum != 0 ? ycScore / (ycCheckNum + 0.00f) : 0.00));
                ycTemp = ycCheckNum != 0 ? ycScore / (ycCheckNum + 0.00f) : 0.00f;
                yc = true;
            } else if (list.get(i).getParent_dept_id() == 32 && !nt) {
                list.get(i).setParent_name(deptMap.get(deptMap.get(list.get(i).getDept_id()).getParentid().longValue()).getOrganname());
                list.get(i).setCheck_total_avg(String.format("%.2f", ntCheckNum != 0 ? ntScore / (ntCheckNum + 0.00f) : 0.00));
                ntTemp = ntCheckNum != 0 ? ntScore / (ntCheckNum + 0.00f) : 0.00f;
                nt = true;
            }
        }
        int lygOrder = 1, ycOrder = 1, ntOrder = 1;
        for (int i = 0; i < list.size(); i++) {
            if (!"".equals(list.get(i).getParent_name()) && list.get(i).getParent_dept_id() == 30) {
                if (lygTemp > ycTemp) {
                    lygOrder += 1;
                }
                if (lygTemp > ntTemp) {
                    lygOrder += 1;
                }
                list.get(i).setFee_station_ranking2(lygOrder);
            }
            if (!"".equals(list.get(i).getParent_name()) && list.get(i).getParent_dept_id() == 31) {
                if (ycTemp > lygTemp) {
                    ycOrder += 1;
                }
                if (ycTemp > ntTemp) {
                    ycOrder += 1;
                }
                list.get(i).setFee_station_ranking2(ycOrder);
            }
            if (!"".equals(list.get(i).getParent_name()) && list.get(i).getParent_dept_id() == 32) {
                if (ntTemp > lygTemp) {
                    ntOrder += 1;
                }
                if (ntTemp > ycTemp) {
                    ntOrder += 1;
                }
                list.get(i).setFee_station_ranking2(ntOrder);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("itemList", itemAll);
        exportExcel("温馨服务检查情况统计表", "fwq_checked_item_info", map, resp);
    }

    private void exportExcel(String fileName, String excelTemplateName, Map<String, Object> map,
                             HttpServletResponse resp) {
        String path = "./" + fileName + ".xls";
        try (InputStream is = this.getClass().getResourceAsStream("/" + excelTemplateName + ".xls")) {
            try (OutputStream os = new FileOutputStream(path)) {
                Context context = new Context();
                // context.putVar("list", map.get("list"));
                // context.putVar("totalMan", map.get("totalMan"));
                for (String key : map.keySet()) {
                    context.putVar(key, map.get(key));
                }
                JxlsHelper.getInstance().processTemplate(is, os, context);
            }
            Thread.sleep(1000);
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[bis.available()];
            bis.read(buffer);
            bis.close();
            // 清空response
            resp.reset();
            // 设置response的Header
            resp.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1"));
            resp.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(resp.getOutputStream());
            resp.setContentType("application/vnd.ms-excel;charset=gb2312");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            // 删除生成的临时文件
            if (file.exists()) {
                file.delete();
            }

        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    private Integer getItemScore2(FwqStatisticsBean obj, String name) {
        List<String> names = obj.getChecked_socre_name();
        List<Integer> scores = obj.getChecked_score();
        for (int i = 0; i < names.size(); i++) {
            if (names.get(i) == null) {
                continue;
            }
            if (names.get(i).contains(name)) {
                return scores.get(i);
            }
        }
        return 0;
    }
}
