package cn.com.countrygarden.bi.main.service.microSatisfy.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageRowBounds;
import cn.com.countrygarden.bi.main.controller.microSatisfy.vo.UpdateQualityVO;
import cn.com.countrygarden.bi.main.dao.dup.TbHsprContractMapper;
import cn.com.countrygarden.bi.main.dao.hmWygl.TbHSPRRegionAvatarInfoMapper;
import cn.com.countrygarden.bi.main.dao.microSatisfy.MicroSatisfyMapper;
import cn.com.countrygarden.bi.main.dao.sys.RoleMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.wcx.WcxRegionProjectDto;
import cn.com.countrygarden.bi.main.model.dup.DupComm;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.dup.ManagerData;
import cn.com.countrygarden.bi.main.model.hmWygl.TbHSPRRegionAvatarInfo;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyAnswerCodeModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyCommModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyOrganDetailModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyOrginModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyPointModel;
import cn.com.countrygarden.bi.main.model.microSatisfy.MicroSatisfyRankModel;
import cn.com.countrygarden.bi.main.model.sys.Role;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.service.microSatisfy.MicroSatisfyService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.NumberUtil;
import cn.com.countrygarden.bi.main.util.UploadUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import cn.com.countrygarden.bi.main.util.wcx.DateUtil;

/**
 * 小业主满意度
 * @author shitong
 *
 */                          
@Service
@Transactional
public class MicroSatisfyServiceImpl implements MicroSatisfyService {
    
    private static final Logger logger = LoggerFactory.getLogger(MicroSatisfyServiceImpl.class);
    
    public static final String[] JOB01 = {"1","2","3","4","5","0"};
    
    public static final String[] JOB02 = {"0","1"};
    
    @Autowired
    private DupCommService dupCommService;
    @Autowired
    private MicroSatisfyMapper microSatisfMapper;
    
    @Autowired
    private TbSysUserMapper  tbSysUserMapper;
    
    @Autowired
    private TbSysUserService tbSysUserService;
    
    @Autowired
    private UserRolesMapper userRolesMapper;
    
    @Autowired
    private TbSysOrganService tbSysOrganService;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private TbHsprContractMapper tbHsprContractMapper;
    
    @Autowired
    private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;
    
    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;
    
    @Autowired
    private  TbHsprCommunityMapper tbHsprCommunityMapper;
    
    /**
     * @描述 批量导入原始调研数据
     * @作者 张世通
     * @时间 2018年6月21日
     * @version 
     * @param list
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String,Object> addSatisfyListOrgin(MultipartFile multipartFile,String fileName,String identifierId,String identifying,HttpServletResponse response) {
        List<MicroSatisfyOrginModel> list = new ArrayList<MicroSatisfyOrginModel>();
        //Map<String,String> resultMap = new HashMap<String,String>();
        Map<String,Object> returnMap = readExcelOrgin(multipartFile,fileName,identifierId,identifying);
        if(returnMap!=null&&returnMap.size()>0){
            Boolean flag = getMsg(returnMap);
            if(!flag){ 
                return returnMap;
            }else{
                list = (List<MicroSatisfyOrginModel>) returnMap.get("data"); 
            }
        }
    
        //将要返回的excel路径
        //String returnPath = "";
        try {
            if(null != list && list.size()>0){
                microSatisfMapper.deleteSatisfyQuestionnaire(identifierId,identifying);
                
                //批量导入基础数据，500条导入一次
                int limit = 500;
                int num = list.size() / limit;
                if(num > 0){
                    for(int i=0;i<num;i++){
                        List<MicroSatisfyOrginModel> tempList = list.subList(0, limit);
                        microSatisfMapper.addSatisfyListOrgin(tempList);
                        list.subList(0, limit).clear();
                    }
                    if(list.size() > 0){
                        microSatisfMapper.addSatisfyListOrgin(list);
                        list.clear();
                    }
                }else{
                    microSatisfMapper.addSatisfyListOrgin(list);
                    list.clear();
                }

            }
        } catch (Exception e) {
            List<String> mList=new ArrayList<>();
            mList.add("CRM数据插入异常");
            returnMap.put("data",mList);
            returnMap.put("flag",false);
            e.printStackTrace();
        }
    
        return returnMap;
    }
    
    
    
       /**
     * @描述 导出CRM的转换后的数据
     * @作者 张世通
     * @时间 2018年6月21日
     * @version 
     * @param list
     */
    @SuppressWarnings("unchecked")
    public Boolean exportCrmData(String identifierId,HttpServletResponse response,HttpServletRequest request) {
        Boolean flag=true;
        //将要返回的excel路径
        //String returnPath = "";
        try {
            
            
           // List<MicroSatisfyOrginModel> list = new ArrayList<MicroSatisfyOrginModel>();
            //Map<String,String> resultMap = new HashMap<String,String>();
     
            List<MicroSatisfyOrginModel> questionnaire = microSatisfMapper.querySatisfyQuestionnaire(identifierId);
            if(null != questionnaire && questionnaire.size()>0){
                
                Set<String> collect = questionnaire.stream().map(MicroSatisfyOrginModel::getBussinessId).collect(Collectors.toSet());
                
                List<MicroSatisfyOrginModel> satisfyOrginModels=new ArrayList<>();
                for (String string : collect) {
                    int i=0;
                    MicroSatisfyOrginModel mOrginModel=new MicroSatisfyOrginModel();
                    Map<String,String> map=new HashMap<>();
                    for (MicroSatisfyOrginModel model : questionnaire) {
                        if(string.equals(model.getBussinessId())){
                            if(i==0){
                                try {
                                    BeanUtils.copyProperties(mOrginModel, model);
                                } catch (Exception e) {
                                      
                                    // TODO Auto-generated catch block  
                                    e.printStackTrace();  
                                    
                                } 
                               
                            }
                            if(StringUtils.isNotBlank(model.getAnswer())){
                                map.put(model.getQuestion(),model.getAnswer());
                            }
           /*                 else if(StringUtils.isNotBlank(model.getAnswerContent())){
                                map.put(model.getQuestion(),model.getAnswerContent());
                            }*/
                            
                            i++;
                        }
                        
                    }

                    mOrginModel.setMap(map);
                    satisfyOrginModels.add(mOrginModel);
                }
                
                
                
                String fileNames = "小业主CRM数据模板.xlsx";
                Workbook wb = exportOrganizationList(fileNames,satisfyOrginModels);
                
                int i = microSatisfMapper.deleteSatisfyQuestionnaire(identifierId,null);
                
                System.out.println("---删除数据库中crm转换的数据--- "+i);
                
                downLoad(response, wb, fileNames,request);
                
            }else{
                System.out.println("---查询不到数据----");
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }
    
       return flag;
    }
    
       /**
     * 设置excel表头
     * @param wb
     * @param sheet
     * @param beginRow
     * @param fixedTitleValue
     */
    public static void setInfoTitle(final XSSFWorkbook wb, final XSSFSheet sheet, final XSSFRow beginRow,final String[] fixedTitleValue){
        final XSSFCellStyle headerStyle = wb.createCellStyle();
        //设置边框
        headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //蓝色背景
        headerStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //管理单元特殊处理
        final XSSFFont titleFont = wb.createFont();

        //字体
        titleFont.setFontHeightInPoints((short) 12);
        titleFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(titleFont);
        //居中
        headerStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        headerStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        XSSFCell cell = null;
        for(int i=0;i< fixedTitleValue.length ;i++){
            sheet.setColumnWidth((short)i,(short)6000);
            cell = createCellAndSetValue(beginRow, i, fixedTitleValue[i]);
            cell.setCellStyle(headerStyle);
        }
    }

    /**
     * 表格赋值
     */
    public static XSSFCell createCellAndSetValue(XSSFRow row,int i,Object object){
        XSSFCell cell;
        String value;
        if(object != null){
            value = String.valueOf(object);
        }else{
            value = "";
        }
        cell = row.createCell(i);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(value);
        return cell;
    }

    public static Cell createCellAndSetValue(Row row,int i,Object object){
        Cell cell;
        String value;
        if(object != null){
            value = String.valueOf(object);
        }else{
            value = "";
        }
        cell = row.createCell(i);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(value);
        return cell;
    }


    /**
     * 设置组织列表数据
     * @param wb
     * @param sheet
     * @param beginRowNumber
     * @param list
     */
    public void setOrganizationInfo(final Workbook wb, Sheet sheet, int beginRowNumber, List<MicroSatisfyOrginModel> list){
        final CellStyle bodyStyle = wb.createCellStyle();
        bodyStyle.setBorderBottom(CellStyle.BORDER_THIN);
        bodyStyle.setBorderLeft(CellStyle.BORDER_THIN);
        bodyStyle.setBorderRight(CellStyle.BORDER_THIN);
        bodyStyle.setBorderTop(CellStyle.BORDER_THIN);
        bodyStyle.setWrapText(false);
        Cell cell;
        Row row;
        //查询字典
   
        String[] keys = new String[] {  "Q1",
                "B1","B2_1",
                "B2_2",
                "B2_3",
                "B2_4",
                "B2_5",
                "B2_6",
                "B2_7",
                "B2_8",
                "B2_9",
                "B2_10",
                "B2_11",
                "B2_12",
                "B2_13",
                "B2_14",
                "B2_15",
                "B2_16",
                "B2_17",
                "B2_18",
                "B2_19",
                "B2_20",
                "B2_21",
                "B2_22",
                "B2_98","B3",
                "B4",
                "B5","F1",
                "F2",
                "F3",
                "F4",
                "F5","管家认知","B2_11","客户电话原声","B2"};
        
        for (int i = 0; i < list.size(); i++){
            
        /*    
            private String bussinessId;             //工单号
            private String paperName;               //问卷名
            private String finishTime;              //完成时间
            private String organId;                 //区域ID
            private String commId;                  //项目ID
            private String organName;               //区域名
            private String commName;                //项目名
            private String status;                  //是否有效 1 有效
            private String roomName;                //房间名
            private String custName;                //客户名
            private String receiveName;             //受理人
            private String mobile;                  //电话
            private String questionId;              //问题ID
            private String question;                //问题描述
            private String answer;                  //数值答案
            private String answerContent;           //答案内容
*/            MicroSatisfyOrginModel  dto = list.get(i);
               
                Map<String, String> map = dto.getMap();
                
            //外呼工单ID
            row = sheet.createRow(beginRowNumber);
            cell = createCellAndSetValue(row, 0, dto.getBussinessId());
            cell.setCellStyle(bodyStyle);
            //问卷问卷名称
            cell = createCellAndSetValue(row, 1,dto.getPaperName());
            cell.setCellStyle(bodyStyle);
            //完成时间
            cell = createCellAndSetValue(row, 2, dto.getFinishTime());
            cell.setCellStyle(bodyStyle);
            //区域ID
            cell = createCellAndSetValue(row, 3, dto.getOrganId());
            cell.setCellStyle(bodyStyle);
            //是否有效
            cell = createCellAndSetValue(row, 4, dto.getStatus());
            cell.setCellStyle(bodyStyle);
            //房屋名称
            cell = createCellAndSetValue(row, 5, dto.getRoomName());
            cell.setCellStyle(bodyStyle);
            //客户名称
            cell = createCellAndSetValue(row, 6, dto.getCustName());
            cell.setCellStyle(bodyStyle);
            //处理人全名
            cell = createCellAndSetValue(row, 7, dto.getReceiveName());
            cell.setCellStyle(bodyStyle);
            //电话
            cell = createCellAndSetValue(row, 8,dto.getMobile());
            cell.setCellStyle(bodyStyle);
            //项目ID
            cell = createCellAndSetValue(row, 9,dto.getCommId());
            cell.setCellStyle(bodyStyle);
            
            //区域
            cell = createCellAndSetValue(row, 10,dto.getOrganName());
            cell.setCellStyle(bodyStyle);
            
            
            //项目名称
            cell = createCellAndSetValue(row, 11,dto.getCommName());
            cell.setCellStyle(bodyStyle);

                 // n1    Q1. 请问您本人目前在本楼盘居住吗？【单选】
            cell = createCellAndSetValue(row, 12,getDefaultValue(map.get(keys[0])));
            cell.setCellStyle(bodyStyle);
                  
                  //n2  B1. 请您综合考虑小区的管家服务、安全管理、环境清洁、物业人员的服务态度四大方面。您对上个月 ______________（读出楼盘名称）的物业管理...
            cell = createCellAndSetValue(row, 13,getDefaultValue(map.get(keys[1])));
            cell.setCellStyle(bodyStyle);   
                      
                      
                      
                //  nn3_1   不满意方面-B2_1客服-文明养宠
            cell = createCellAndSetValue(row, 14,getDefaultValue(map.get(keys[2])));
            cell.setCellStyle(bodyStyle);      
                 // nn3_2   不满意方面-B2_2客服-管家更换频繁
            cell = createCellAndSetValue(row, 15,getDefaultValue(map.get(keys[3])));
            cell.setCellStyle(bodyStyle);        
                 // nn3_3   不满意方面-B2_3工程-电梯相关
            cell = createCellAndSetValue(row, 16,getDefaultValue(map.get(keys[4])));
            cell.setCellStyle(bodyStyle);          
                  //nn3_4   不满意方面-B2_4工程-维修效率及质量
            cell = createCellAndSetValue(row, 17,getDefaultValue(map.get(keys[5])));
            cell.setCellStyle(bodyStyle);        
                //  nn3_5   不满意方面-B2_5工程-设施维护（公共照明、道路、休闲娱乐设施等）
            cell = createCellAndSetValue(row, 18,getDefaultValue(map.get(keys[6])));
            cell.setCellStyle(bodyStyle);    
                //  nn3_6   不满意方面-B2_6绿化-绿化养护
            cell = createCellAndSetValue(row, 19,getDefaultValue(map.get(keys[7])));
            cell.setCellStyle(bodyStyle);      
                 // nn3_7   不满意方面-B2_7绿化-绿植品类少
            cell = createCellAndSetValue(row,20,getDefaultValue(map.get(keys[8])));
            cell.setCellStyle(bodyStyle);       
                  //nn3_8   不满意方面-B2_8安保-停车管理
            cell = createCellAndSetValue(row,21,getDefaultValue(map.get(keys[9])));
            cell.setCellStyle(bodyStyle);       
                //  nn3_9   不满意方面-B2_9安保-噪音管理
            cell = createCellAndSetValue(row,22,getDefaultValue(map.get(keys[10])));
            cell.setCellStyle(bodyStyle);        
                 // nn3_10  不满意方面-B2_10安保-门岗通行管理
            cell = createCellAndSetValue(row,23,getDefaultValue(map.get(keys[11])));
            cell.setCellStyle(bodyStyle);       
                 // nn3_11  不满意方面-B2_11安保-违章搭建
            cell = createCellAndSetValue(row,24,getDefaultValue(map.get(keys[12])));
            cell.setCellStyle(bodyStyle);       
                //  nn3_12  不满意方面-B2_12环境-垃圾清运
            cell = createCellAndSetValue(row,25,getDefaultValue(map.get(keys[13])));
            cell.setCellStyle(bodyStyle);        
                 // nn3_13  不满意方面-B2_13环境-环境清洁
            cell = createCellAndSetValue(row, 26,getDefaultValue(map.get(keys[14])));
            cell.setCellStyle(bodyStyle);        
                //  nn3_14  不满意方面-B2_14环境-四害消杀
            cell = createCellAndSetValue(row,27,getDefaultValue(map.get(keys[15])));
            cell.setCellStyle(bodyStyle);       
                //  nn3_15  不满意方面-B2_15环境-园区积水清理
            cell = createCellAndSetValue(row, 28,getDefaultValue(map.get(keys[16])));
            cell.setCellStyle(bodyStyle);        
                 // nn3_16  不满意方面-B2_16房产相关-房屋质量
            cell = createCellAndSetValue(row, 29,getDefaultValue(map.get(keys[17])));
            cell.setCellStyle(bodyStyle);      
                 // nn3_17  不满意方面-B2_17房产相关-销售承诺
            cell = createCellAndSetValue(row,30,getDefaultValue(map.get(keys[18])));
            cell.setCellStyle(bodyStyle);      
                 // nn3_18  不满意方面-B2_18收费问题（费用高、乱收费等）
            cell = createCellAndSetValue(row, 31,getDefaultValue(map.get(keys[19])));
            cell.setCellStyle(bodyStyle);      
               //   nn3_19  不满意方面-B2_19人员态度
            cell = createCellAndSetValue(row, 32,getDefaultValue(map.get(keys[20])));
            cell.setCellStyle(bodyStyle);        
                 // nn3_20  不满意方面-B2_20周边配套及市政规划
            cell = createCellAndSetValue(row, 33,getDefaultValue(map.get(keys[21])));
            cell.setCellStyle(bodyStyle);      
                //  nn3_21  不满意方面-B2_21停水电气
            cell = createCellAndSetValue(row, 34,getDefaultValue(map.get(keys[22])));
            cell.setCellStyle(bodyStyle);      
                 // nn3_22  不满意方面-B2_22对物业整体不满
            cell = createCellAndSetValue(row, 35,getDefaultValue(map.get(keys[23])));
            cell.setCellStyle(bodyStyle);      
                //  nn3_98  不满意方面-B2_98其他
            cell = createCellAndSetValue(row,36,getDefaultValue(map.get(keys[24])));
            cell.setCellStyle(bodyStyle);      
                //  n5  B3. 请问您或家人知道您的片区凤凰管家吗？
            cell = createCellAndSetValue(row,37,getDefaultValue(map.get(keys[25])));
            cell.setCellStyle(bodyStyle);      
                //  n6  B4. 【访问员：B4只提问B3回答2的被访者】管家是否有主动联系或拜访过您或家人？
            cell = createCellAndSetValue(row, 38,getDefaultValue(map.get(keys[26])));
            cell.setCellStyle(bodyStyle);        
                      
                //  n7  B5. 【访问员：B5只提问B3回答1的被访者】您对现在的管家服务满意吗？请用1-5分评价，5分表示非常满意， 4表示比较满意，3 表示一般，2表示比...
            cell = createCellAndSetValue(row, 39,getDefaultValue(map.get(keys[27])));
            cell.setCellStyle(bodyStyle);       
                      
                      
                      
                //  f1  F1.您觉得居住在我们小区还安全吗？请用1-5分评价，5分表示非常满意， 4表示比较满意，3 表示一般，2表示比较不满意， 1 表示非常不满意（若被访...
            cell = createCellAndSetValue(row, 40,getDefaultValue(map.get(keys[28])));
            cell.setCellStyle(bodyStyle);      
                      
                      
                      
                //  f2  F2. 您觉得小区公共卫生干净吗？请用1-5分评价，5分表示非常满意， 4表示比较满意，3 表示一般，2表示比较不满意，1表示非常不满意（若被访者对指...
            cell = createCellAndSetValue(row, 41,getDefaultValue(map.get(keys[29])));
            cell.setCellStyle(bodyStyle);       
                      
                      
                      
                //  f3  F3.您觉得我们物业人员的服务态度好吗？请用1-5分评价，5分表示非常满意， 4表示比较满意，3 表示一般，2表示比较不满意， 1 表示非常不满意
                      
                      
            cell = createCellAndSetValue(row, 42,getDefaultValue(map.get(keys[30])));
            cell.setCellStyle(bodyStyle);        
                      
            //f4
            cell = createCellAndSetValue(row, 43,getDefaultValue(map.get(keys[31])));
            cell.setCellStyle(bodyStyle);   
            
            //f5
            cell = createCellAndSetValue(row, 44,getDefaultValue(map.get(keys[32])));
            cell.setCellStyle(bodyStyle);   
            
            //管家认知
            cell = createCellAndSetValue(row, 45,getDefaultValue(map.get(keys[33])));
            cell.setCellStyle(bodyStyle); 
            
            String b2 = map.get(keys[36]);
            
            String words = map.get(keys[34]);
            if(StringUtils.isEmpty(words)){
                words=b2;
            }
            //其他不满意原话
            cell = createCellAndSetValue(row, 46,words);
            cell.setCellStyle(bodyStyle);
            
            String sound = map.get(keys[35]);
            if(StringUtils.isEmpty(sound)){
                sound=b2;
            }
            //客户原声
            cell = createCellAndSetValue(row, 47,sound);
            cell.setCellStyle(bodyStyle);

            beginRowNumber++;
        }
    }
    
    public String getDefaultValue(String value){
        if(StringUtils.isEmpty(value)){
            return "0";
        }
        return value;
    }

    public static Workbook getWookbook(String fileName,ClassLoader loader){
        //resources/excel/performance
        //META-INF/downloads/template/
        String path = new StringBuilder().append("excel/performance/").append(fileName).toString();
        InputStream in = loader.getResourceAsStream(path);
        Workbook wb = null;
        try {
            wb = new SXSSFWorkbook(new XSSFWorkbook(in),500);
        } catch (IOException e) {
           logger.error("获取excel模板失败", e);
            
        }
        return wb;
    }

    /**
     * 导出组织列表
     * @param list
     * @return
     */
    public Workbook exportOrganizationList(String fileName,List<MicroSatisfyOrginModel> list){
        Workbook wb = getTemplate(fileName);
        Sheet sheet = wb.getSheetAt(0);
        this.setOrganizationInfo(wb,sheet,2,list);
        return wb;
    }



    public Workbook getTemplate(String fileName) {
        ClassLoader loader = getClass().getClassLoader();
        Workbook wb =  getWookbook(fileName, loader);
        return wb;
    }

    /**
     * 下载
     *
     */
    public boolean downLoad(HttpServletResponse response, Workbook wb, String fileName,HttpServletRequest request) {
        boolean flag=true;
        if(wb !=null){
            try
            {
                final String userAgent = request.getHeader("USER-AGENT");
                
                if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                    fileName = URLEncoder.encode(fileName,"UTF8");
                }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                }else{
                    fileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
                }
                
                
                String headStr = new StringBuilder().append("attachment;fileName=").append(fileName).toString();
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", headStr);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                wb.close();
                out.flush();
                out.close();  
               /*                                                           
                FileOutputStream output =  new FileOutputStream("D:\\数据文档\\测试转换数据\\qqqq.xlsx");
                wb.write(output);
                output.flush();*/
            }
            catch (Exception e)
            {
                flag=false;
                e.printStackTrace();
            }
        }
        return flag;
    }

    
    /**
     * @描述 批量导入调研数据
     * @作者 张世通
     * @时间 2018年6月21日
     * @version 
     * @param list
     */
    @Override
    public Map<String, Object> addSatisfyList(MultipartFile multipartFile,String fileName,String userCode,String timeStr) {
        Map<String, Object> msgMap =new HashMap<>();
        try {
            List<MicroSatisfyModel> list = readExcel(multipartFile,fileName,userCode,timeStr);
            //String finishTime = list.get(0).getFinishTime();
           if(list!=null&&list.size()>0){
               msgMap = list.get(0).getMsgMap();
                boolean msg = getMsg(msgMap);
                if(msg){
                //覆盖当月数据
                microSatisfMapper.deleteImport(timeStr);
                //String pid = list.get(0).getPid();
                if(null != list && list.size()>0){
                    int limit = 500;
                    int num = list.size() / limit;
                    int j =0;
                    if(num > 0){
                        
                        for(int i=0;i<num;i++){
                            List<MicroSatisfyModel> tempList = list.subList(0, limit);
                            j +=microSatisfMapper.addSatisfyList(tempList);
                            list.subList(0, limit).clear();
                        }
                        if(list.size() > 0){
                            j += microSatisfMapper.addSatisfyList(list);
                            list.clear();
                        }
                    }else{
                        j = microSatisfMapper.addSatisfyList(list);
                        list.clear();
                    }
                    
                /*  microSatisfMapper.deleteMicroOrganRank(finishTime);
                    microSatisfMapper.deleteMicroCommRank(finishTime);
                    microSatisfMapper.deleteMicroSatisfyRegionDetail(finishTime);*/
                    
                    //生成区域项目数据
                /*  this.queryOrganSatisfyDetail(finishTime, userCode,pid);
                    //生成区域排名数据
                    this.queryOrganRankImport(pid, finishTime,userCode);
                    //生成项目排名数据
                    this.queryCommRankImport(pid, finishTime,userCode);*/
                    msgMap.put("count", j);
                }
            }
         }
    
            
            
        } catch (Exception e) {
            msgMap.put("flag", false);
            List<String> mList=new ArrayList<>();
            mList.add("小业主数据插入异常");
            msgMap.put("data",mList);
            e.printStackTrace();
        }
        
    
        return msgMap;
    }

    
       public Boolean ImportAnswerCode(MultipartFile multipartFile,String fileName,String userCode) {
           Boolean flag=false;
            try {
                List<MicroSatisfyAnswerCodeModel> list = readExcelAnswerCode(multipartFile,fileName,userCode);
                //String finishTime = list.get(0).getFinishTime();
               if(list!=null&&list.size()>0){
                    //覆盖当月数据
                    microSatisfMapper.deleteAnswerCode();
                    //String pid = list.get(0).getPid();
                    if(null != list && list.size()>0){
                        int limit = 500;
                        int num = list.size() / limit;
                        int j =0;
                        if(num > 0){
                            
                            for(int i=0;i<num;i++){
                                List<MicroSatisfyAnswerCodeModel> tempList = list.subList(0, limit);
                                j +=microSatisfMapper.addAnswerCode(tempList);
                                list.subList(0, limit).clear();
                            }
                            if(list.size() > 0){
                                j += microSatisfMapper.addAnswerCode(list);
                                list.clear();
                            }
                        }else{
                            j = microSatisfMapper.addAnswerCode(list);
                            list.clear();
                        }
                        

                        flag=true;
                    }
             }
        
                
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        
            return flag;
        }
    
    public  boolean getMsg(Map<String, Object> msgMap) {
        boolean msg=false;
    
            if(msgMap!=null&&msgMap.size()>0){
                msg=(boolean) msgMap.get("flag");
            }
        
        return msg;
    }
    /**
     * @描述 读取原始数据excel文件
     * @作者 张世通
     * @时间 2018年6月21日
     * @版本 
     * @param mf
     * @param fileName
     * @param userCode
     * @return
     */
    @SuppressWarnings("deprecation")
    public Map<String,Object> readExcelOrgin(MultipartFile mf,String fileName,String identifierId,String identifying){
        //Map<String,Object> returnMap = new HashMap<String,Object>();
        //returnMap.put("MSG", "SUCCESS");
        
        Map<String,Object> hashMap=new HashMap<>();
        
        List<String> mList=new ArrayList<>();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Workbook xwb = null;
        BufferedInputStream bf = null;
        Sheet sheet = null;
        List<MicroSatisfyOrginModel> list = new ArrayList<MicroSatisfyOrginModel>();
        List<MicroSatisfyAnswerCodeModel> codeList = microSatisfMapper.queryAnswerCode();
        
        Boolean flag=true;
        try {
            //测试
            /*File file= new File("D:\\12.xlsx");
            bf = new BufferedInputStream(new FileInputStream(file));
            xwb = new XSSFWorkbook(bf);*/

            bf = new BufferedInputStream(mf.getInputStream());
            if (fileName.endsWith("xls")) { 
                // Excel 2003
                xwb = new HSSFWorkbook(bf);
            } else if (fileName.endsWith("xlsx")) { 
                // Excel 2007+
                xwb = new XSSFWorkbook(bf);
            }
            if(xwb!=null&&xwb.getSheetAt(0)!=null){
                
                 sheet = xwb.getSheetAt(0);//获取第几个页面0开始
                 
                 List<List<String>> transferBasicInfoList = UploadUtil.readOneSheetForList(sheet, 2,5, 0, -1);
                 if(transferBasicInfoList.size() == 0){
                     mList.add("不能上传空模板");
                     hashMap.put("data",mList);
                     hashMap.put("flag",false);
                     return hashMap;
                 }

                 int j=0;
                    for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
                        j=i+1;
                        Row row = sheet.getRow(i);
                        if (row != null){
                            MicroSatisfyOrginModel modelOrgin = new MicroSatisfyOrginModel();
                            String bussinessId = getValue(row.getCell(0));
                            if(StringUtil.isBlankOrEmpty(bussinessId)){
                                mList.add("第【"+j+"】行的第1列{外呼工单ID}不能为空");
                            }
                            modelOrgin.setBussinessId(bussinessId);
                            modelOrgin.setPaperName(getValue(row.getCell(1)));
                            
                            modelOrgin.setIdentifierId(identifierId);
                            
                            modelOrgin.setIdentifying(identifying);
                            
                            String timeStr = getValue(row.getCell(2));
                            if(StringUtil.isNotEmpty(timeStr)){
                                try {
                                    SimpleDateFormat math = new SimpleDateFormat("yyyy-MM-dd");
                                 // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                                    math.setLenient(false);
                                    math.parse(timeStr);
                                    
                                    Date fullDate = DateUtil.formatStrToDate(timeStr, DateUtil.COMMON_DATE_FORMAT);
                                    /*  Date formatDate = DateUtil.formatDate(fullDate, "yyyy-MM");
                //????????????????????
                                    Date tDate = DateUtil.formatStrToDate("2017-01-09", DateUtil.COMMON_DATE_FORMAT);
                                    Date date2 = DateUtil.formatDate(tDate, "yyyy-MM");
                                    
                                    if(!formatDate.equals(date2)){
                                        flag=false;
                                        mList.add("第【"+j+"】行的第3列{完成时间}与页面输入的时间不一致");
                                    }*/
                                    timeStr=format.format(fullDate);
                                } catch (Exception e) { 
                                    flag=false;
                                    mList.add("第【"+j+"】行的第3列{完成时间}格式不正确--->>>参考的时间格式例子(1995-2-01或者1997-11-22)");
                                    e.printStackTrace();
                                }

                            }else{
                                //timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
                                flag=false;
                                mList.add("第【"+j+"】行的第3列{完成时间}为空");
                            }
                            
                            System.out.println("----转换的时间03---"+timeStr);
                            modelOrgin.setFinishTime(timeStr);
                            
                            String organ="";
                            String organId = getValue(row.getCell(3));
                            if(StringUtil.isNotEmpty(organId)){
                                organ = tbHsprContractMapper.getOrgan(organId);
                                if(StringUtil.isBlankOrEmpty(organ)){
                                    flag=false;
                                    mList.add("第【"+j+"】行的第4列{区域Id}查找不到此区域Id");
                                }
                            }else{
                                flag=false;
                                mList.add("第【"+j+"】行的第4列{区域Id}为空");
                            }
                            
                            modelOrgin.setOrganId(organId);
                            
                            
                            String commId = getValue(row.getCell(4));
                            String community ="";
                             
                              if(StringUtil.isNotEmpty(commId)){
                                  if(isInteger(commId)){
                                      Map<String, Object> communityMap = tbHsprContractMapper.getCommunity(commId);
                                       if(communityMap!=null&&communityMap.size()>0){
                                           community=  (String) communityMap.get("CommName"); 
                                           String organCode=  (String) communityMap.get("OrganCode");
                                           if(StringUtil.isNoneBlank(organId)){
                                               if(!organId.equals(organCode)){
                                                   flag=false;
                                                   mList.add("第【"+j+"】行的第5列{项目Id}通过项目Id查找到的区域Id与该行的(区域Id不匹配)");
                                               }
                                           }
                                       }else{
                                           
                                           flag=false;
                                           mList.add("第【"+j+"】行的第5列{项目Id}查找不到此项目Id");
                                    
                                       }
                                  }else{
                                      flag=false;
                                      mList.add("第【"+j+"】行的第5列{项目Id}只能是整数");
                                  }
                                  
                                
                              }else{
                                  flag=false;
                                  mList.add("第【"+j+"】行的第5列{项目Id}为空");
                              }

                            modelOrgin.setCommId(commId);
                            
                            String organName = getValue(row.getCell(5));
                            if(StringUtil.isNotEmpty(organName)){
                                if(StringUtil.isNotBlankAndNotEmpty(organ)){
                                    if(!organName.equals(organ)){
                                        flag=false;
                                        mList.add("第【"+j+"】行的第6列{区域名称}通过区域Id查找到的区域名称与该行的(区域名称)不匹配"); 
                                    }
                                }
                            }else{
                                flag=false;
                                mList.add("第【"+j+"】行的第6列{区域名称}为空"); 
                            }
                            
                            modelOrgin.setOrganName(organName);
                            
                            String commName = getValue(row.getCell(6));
                            if(StringUtil.isNotEmpty(commName)){
                                if(StringUtil.isNotBlankAndNotEmpty(community)){
                                    if(!commName.equals(community)){
                                        flag=false;
                                        mList.add("第【"+j+"】行的第7列{项目名称}通过项目Id查找到的项目名称与该行的(项目名称)不匹配"); 
                                    }
                                }
                                 }else{
                                     flag=false;
                                     mList.add("第【"+j+"】行的第7列{项目名称}为空"); 
                                 }
                            
                            modelOrgin.setCommName(commName);
                            
                            String status = getValue(row.getCell(7));
                            if(StringUtil.isNotEmpty(status)){
                                 if(!ArrayUtils.contains(JOB02,status)){
                                     flag=false;
                                     mList.add("第【"+j+"】行的第8列{是否有效}值只能是1或0");
                                 }
                             }else{
                                 flag=false;
                                 mList.add("第【"+j+"】行的第8列{是否有效}为空");
                             }
                            modelOrgin.setStatus(status);
                            
                            modelOrgin.setRoomName(getValue(row.getCell(8)));
                            modelOrgin.setCustName(getValue(row.getCell(9)));
                            modelOrgin.setReceiveName(getValue(row.getCell(10)));
                            //电话
                            modelOrgin.setMobile(getValue(row.getCell(11)));
                            //问题名称
                            String question = getValue(row.getCell(12));
                            modelOrgin.setQuestion(question);
                            
                            
                            
                            //title
                            int e=0;
                            if(null != codeList && codeList.size()>0){
                                for(MicroSatisfyAnswerCodeModel item:codeList){
                                    //判断在表里--是否存在这个问题
                                    if(question.lastIndexOf(item.getAnswerKey())>-1){
                                        //判断是否是 带有  n1,f2,n3 ......   的 问题
                                        if(question.lastIndexOf(item.getAnswerKey()+".")>-1){
                                    /*        modelOrgin.setQuestionId(item.getAnswerKey());
                                            
                                            modelOrgin.setQuestion(item.getContentDescribe());*/
                                            
                                          modelOrgin.setQuestionId(item.getAnswerId());
                                            
                                            modelOrgin.setQuestion(item.getAnswerKey());
                                            
                                            modelOrgin.setRule(item.getRule());
                                            e++;
                                            break;
                                        }else if(question.equals(item.getAnswerKey())){
                                         /*   modelOrgin.setQuestionId(item.getAnswerKey());
                                            modelOrgin.setQuestion(item.getContentDescribe());*/
                                            
                                            modelOrgin.setQuestionId(item.getAnswerId());
                                            
                                            modelOrgin.setQuestion(item.getAnswerKey());
                                            e++;
                                            break;
                                        }
                                        
                                /*      else if("客户电话原声".equals(modelOrgin.getQuestion()) 
                                                || "其他不满意原话".equals(modelOrgin.getQuestion())){
                                            modelOrgin.setQuestionId(item.getAnswerId());
                                            break;
                                        }*/
                                        
                                        
                                    }
                                }
                                if(e==0){
                                 flag=false;
                                 mList.add("第【"+j+"】行的第13列{问题名称}未找到该问题");
                                }
                            }
                            //答案--需判断是否为电话原声
                            String answer = getValue(row.getCell(13));
                            System.out.println("----答案------ "+answer);
                            if(StringUtil.isEmpty(modelOrgin.getQuestionId())
                                    ||"客户电话原声".equals(question) 
                                    || "其他不满意原话".equals(question)
                                    || "B2".equals(modelOrgin.getQuestion())){
                                //modelOrgin.setAnswerContent(answer);
                                modelOrgin.setAnswer(answer);
                            }else{
                                if(StringUtil.isNotEmpty(answer)){
                                    String point = answer.substring(0,1);
                                    if(isInteger(point)){
                                        modelOrgin.setAnswer(point);
                                    }else{
                                        flag=false;
                                        mList.add("第【"+j+"】行的第14列{答案}只能是整型数字");
                                    }
                                }
                            }
                            //modelOrgin.setCreatedBy(userCode);
                            list.add(modelOrgin);
                        }else{
                            break;
                        }
                    }
                
                
            }
                    
            hashMap.put("flag",flag);
            if(flag){
                hashMap.put("data", list);  
            }else{
                hashMap.put("data",mList); 
            }
        }catch(Exception e){
            mList.add("转换数据出现异常");
            hashMap.put("data",mList);
            hashMap.put("flag",false);
            e.printStackTrace();
        }
        return hashMap;
    }
    /**
     * @描述 判断是否为数字
     * @作者 张世通
     * @时间 2018年6月29日
     * @版本 
     * @param str
     * @return
     */
    public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
    }
    
    @SuppressWarnings("deprecation")
    public List<MicroSatisfyAnswerCodeModel> readExcelAnswerCode(MultipartFile mf,String fileName,String userCode){
        Workbook xwb = null;
        BufferedInputStream bf = null;
        Sheet sheet = null;
        List<MicroSatisfyAnswerCodeModel> list = new ArrayList<MicroSatisfyAnswerCodeModel>();

        try {
            //测试
            /*File file= new File("D:\\1.xlsx");
            bf = new BufferedInputStream(new FileInputStream(file));
            xwb = new XSSFWorkbook(bf);*/
            bf = new BufferedInputStream(mf.getInputStream());
            if (fileName.endsWith("xls")) { 
                // Excel 2003
                xwb = new HSSFWorkbook(bf);
            } else if (fileName.endsWith("xlsx")) { 
                // Excel 2007+
                xwb = new XSSFWorkbook(bf);
            }

            if(xwb!=null&&xwb.getSheetAt(0)!=null){
            
            sheet = xwb.getSheetAt(0);//获取第几个页面0开始
     
            for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
                MicroSatisfyAnswerCodeModel modelOrgin = new MicroSatisfyAnswerCodeModel();
                Row row = sheet.getRow(i);
                if (row != null){

                    String answerId = getValue(row.getCell(0));
                    modelOrgin.setAnswerId(answerId);
                    
                    String answerKey = getValue(row.getCell(1));
                    modelOrgin.setAnswerKey(answerKey);
                    
                    String contentDescribe = getValue(row.getCell(2));//问题描述
                    modelOrgin.setContentDescribe(contentDescribe);
                    
                    String answerContent = getValue(row.getCell(3));//答案描述
                    modelOrgin.setAnswerContent(answerContent);
                    
                    String isDelete = getValue(row.getCell(4));
                    modelOrgin.setIsDelete(isDelete);
                    
                    modelOrgin.setCreatedBy(userCode);
                }else{
                    break;
                }
                list.add(modelOrgin);
            }
    }  
            
        }catch(Exception e){
           e.printStackTrace();
        }
        
        return list;
    }
    
    
    

    public Map<String,Object> ImportRegionalObjectives(MultipartFile multipartFile,String fileName,String userCode) {
        Map<String,Object> map=new HashMap<>();
        int a=0;
        int b=0;
        try {
             List<MicroSatisfyPointModel> list = regionalObjectives(multipartFile,fileName,userCode);
  
            if(list!=null&&list.size()>0){
                 if(null != list && list.size()>0){
                         for(int i=0;i<list.size();i++){
                             MicroSatisfyPointModel microSatisfyPointModel = list.get(i);
                             
                             MicroSatisfyPointModel model=  microSatisfMapper.queryOrganPointByOrganCode(microSatisfyPointModel.getOrganId());
                             if(model!=null){
                               a+=  microSatisfMapper.updateRegionalObjectives(microSatisfyPointModel);
                             }else{
                               b+=  microSatisfMapper.addRegionalObjectives(microSatisfyPointModel);
                             }
                         }
                 }
          }
     
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
        map.put("更新数量",a);
        map.put("新增数量",b);
     
         return map;
     }
    


    @Override
    public Map<String, Object> ImportCommObjectives(MultipartFile commonsMultipartFile,
            String fileName, String string) {
        Map<String,Object> map=new HashMap<>();
        int a=0;
        int b=0;
        try {
             List<MicroSatisfyCommModel> list = commObjectives(commonsMultipartFile,fileName,string);
  
            if(list!=null&&list.size()>0){
                 if(null != list && list.size()>0){
                         for(int i=0;i<list.size();i++){
                             MicroSatisfyCommModel microSatisfyPointModel = list.get(i);
                             
                             MicroSatisfyPointModel model=  microSatisfMapper.queryCommPointByCommCode(microSatisfyPointModel.getCommId());
                             if(model!=null){
                               a+=  microSatisfMapper.updateCommObjectives(microSatisfyPointModel);
                             }else{
                               b+=  microSatisfMapper.addCommObjectives(microSatisfyPointModel);
                             }
                         }
                 }
          }
     
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
        map.put("更新数量",a);
        map.put("新增数量",b);
     
         return map;
    }
   
    
    @SuppressWarnings("deprecation")
    public List<MicroSatisfyPointModel> regionalObjectives(MultipartFile mf,String fileName,String userCode){
        Workbook xwb = null;
        BufferedInputStream bf = null;
        Sheet sheet = null;
        List<MicroSatisfyPointModel> list = new ArrayList<MicroSatisfyPointModel>();

        try {
        
            bf = new BufferedInputStream(mf.getInputStream());
            if (fileName.endsWith("xls")) { 
                // Excel 2003
                xwb = new HSSFWorkbook(bf);
            } else if (fileName.endsWith("xlsx")) { 
                // Excel 2007+
                xwb = new XSSFWorkbook(bf);
            }

            if(xwb!=null&&xwb.getSheetAt(0)!=null){
            
            sheet = xwb.getSheetAt(0);//获取第几个页面0开始
     
            for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
                MicroSatisfyPointModel modelOrgin = new MicroSatisfyPointModel();
                Row row = sheet.getRow(i);
                if (row != null){

                    String organId = getValue(row.getCell(0));
                    modelOrgin.setOrganId(organId);
                    
                    String organName = getValue(row.getCell(1));
                    modelOrgin.setOrganName(organName);
                    
                    String basePoint = getValue(row.getCell(2));
                    modelOrgin.setBasePoint(basePoint);
                    
                    //门槛值
                    String  crossPoint= new BigDecimal(basePoint).multiply(new BigDecimal("0.8")).toString();
                    DecimalFormat df = new DecimalFormat("#.##");
                    crossPoint = String.valueOf(df.format(Double.parseDouble(crossPoint)));
                    
                    modelOrgin.setCrossPoint(crossPoint);
                    
                    String middePoint = getValue(row.getCell(3));
                    modelOrgin.setMiddePoint(middePoint);
                    
                    String highPoint = getValue(row.getCell(4));
                    modelOrgin.setHighPoint(highPoint);
                    
                    modelOrgin.setIsDelete("0");
                    
                    modelOrgin.setCreatedBy(userCode);
                }else{
                    break;
                }
                list.add(modelOrgin);
            }
    }  
            
        }catch(Exception e){
           e.printStackTrace();
        }
        
        return list;
    }
    
    @SuppressWarnings("deprecation")
    public List<MicroSatisfyCommModel> commObjectives(MultipartFile mf,String fileName,String userCode){
        Workbook xwb = null;
        BufferedInputStream bf = null;
        Sheet sheet = null;
        List<MicroSatisfyCommModel> list = new ArrayList<MicroSatisfyCommModel>();

        try {
        
            bf = new BufferedInputStream(mf.getInputStream());
            if (fileName.endsWith("xls")) { 
                // Excel 2003
                xwb = new HSSFWorkbook(bf);
            } else if (fileName.endsWith("xlsx")) { 
                // Excel 2007+
                xwb = new XSSFWorkbook(bf);
            }

            if(xwb!=null&&xwb.getSheetAt(0)!=null){
            
            sheet = xwb.getSheetAt(0);//获取第几个页面0开始
     
            for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
                MicroSatisfyCommModel modelOrgin = new MicroSatisfyCommModel();
                Row row = sheet.getRow(i);
                if (row != null){

                    String commId = getValue(row.getCell(0));
                    modelOrgin.setCommId(commId);
                    
                    String commName = getValue(row.getCell(1));
                    modelOrgin.setCommName(commName);
                    
                    String basePoint = getValue(row.getCell(2));
                    modelOrgin.setBasePoint(basePoint);
                    
                    //门槛值
                    String  crossPoint= new BigDecimal(basePoint).multiply(new BigDecimal("0.8")).toString();
                    
                    DecimalFormat df = new DecimalFormat("#.##");
                    crossPoint = String.valueOf(df.format(Double.parseDouble(crossPoint)));
                    modelOrgin.setCrossPoint(crossPoint);
                    
                    String middePoint = getValue(row.getCell(3));
                    modelOrgin.setMiddePoint(middePoint);
                    
                    String highPoint = getValue(row.getCell(4));
                    modelOrgin.setHighPoint(highPoint);
                    
                    modelOrgin.setIsDelete("0");
                    
                    modelOrgin.setCreatedBy(userCode);
                }else{
                    break;
                }
                list.add(modelOrgin);
            }
    }  
            
        }catch(Exception e){
           e.printStackTrace();
        }
        
        return list;
    }
    
    
    
    /**
     * @描述 读取数据excel文件
     * @作者 张世通
     * @时间 2018年6月21日
     * @版本 
     * @param mf
     * @param fileName
     * @param userCode
     * @return
     */
     @SuppressWarnings("deprecation")
        public List<MicroSatisfyModel> readExcel(MultipartFile mf,String fileName,String userCode,String date){
            //DateFormat format = new SimpleDateFormat("yyyy-MM-dd ahh:mm",Locale.CHINA);
            
            //DateFormat format = new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA);
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Workbook xwb = null;
            BufferedInputStream bf = null;
            Sheet sheet = null;
            String pid = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            List<MicroSatisfyModel> list = new ArrayList<MicroSatisfyModel>();
            //List<Map<String,Object>> mList=new ArrayList<>();
            Map<String,Object> hashMap=new HashMap<>();
            
            List<String> mList=new ArrayList<>();
        
            try {
                //测试
                /*File file= new File("D:\\1.xlsx");
                bf = new BufferedInputStream(new FileInputStream(file));
                xwb = new XSSFWorkbook(bf);*/
                bf = new BufferedInputStream(mf.getInputStream());
                if (fileName.endsWith("xls")) { 
                    // Excel 2003
                    xwb = new HSSFWorkbook(bf);
                } else if (fileName.endsWith("xlsx")) { 
                    // Excel 2007+
                    xwb = new XSSFWorkbook(bf);
                }
                Boolean flag=true;
                
                if(xwb!=null&&xwb.getSheetAt(0)!=null){
                
                sheet = xwb.getSheetAt(0);//获取第几个页面0开始
                 List<List<String>> transferBasicInfoList = UploadUtil.readOneSheetForList(sheet, 2,5, 0, -1);
                    if(transferBasicInfoList.size() == 0){
                        flag=false;
                        mList.add("不能上传空模板");
                        hashMap.put("data",mList);
                        hashMap.put("flag",false);
                        MicroSatisfyModel map=new MicroSatisfyModel();
                        map.setMsgMap(hashMap);
                        list.add(map);
                        return list;
                    }
                
                
                    
                    int j=3;
                for(int i=2;i<sheet.getPhysicalNumberOfRows();i++){
                    Row row = sheet.getRow(i);
                    if (row != null){
                        
                        MicroSatisfyModel model = new MicroSatisfyModel();
                        String bussinessId = getValue(row.getCell(0));
                        if(StringUtil.isBlankOrEmpty(bussinessId)){
                            mList.add("第【"+j+"】行的第1列{外呼工单ID}不能为空");
                        }
                        model.setBussinessId(bussinessId);
                        String questionNaire = getValue(row.getCell(1));
                        model.setQuestionNaire(questionNaire);
                        String timeStr = getValue(row.getCell(2));
                        if(StringUtil.isNotEmpty(timeStr)){
                            try {
                                Date fullDate = DateUtil.formatStrToDate(timeStr, DateUtil.COMMON_DATE_FORMAT);
                                timeStr =DateUtil.formatDateToStr(fullDate,DateUtil.COMMON_DATE_FORMAT);
                                Date formatDate = DateUtil.formatDate(fullDate, "yyyy-MM");
                       
                                Date tDate = DateUtil.formatStrToDate(date, DateUtil.COMMON_DATE_FORMAT);
                                Date date2 = DateUtil.formatDate(tDate, "yyyy-MM");

                                System.out.println(j+"----转换的时间---"+formatDate.toString());
                                System.out.println("----转换的时间02---"+date2.toString());
                                
                                if(!formatDate.equals(date2)){
                                    flag=false;
                                    mList.add("第【"+j+"】行的第3列{完成时间}与页面输入的时间不一致");
                                }
                                timeStr=format.format(fullDate);
                            } catch (Exception e) {
                                 flag=false;
                                 mList.add("第【"+j+"】行的第3列{完成时间}格式不正确--->>>参考的时间格式例子(1995-2-01或者1997-11-22)");
                                 e.printStackTrace();
                            }

                        }else{
                            //timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
                            flag=false;
                            mList.add("第【"+j+"】行的第3列{完成时间}为空");
                        }
                        
                        System.out.println("----转换的时间03---"+timeStr);
                        model.setFinishTime(timeStr);
                        
                        String organ="";
                        String organId = getValue(row.getCell(3));
                        if(StringUtil.isNotEmpty(organId)){
                            organ = tbHsprContractMapper.getOrgan(organId);
                            if(StringUtil.isBlankOrEmpty(organ)){
                                flag=false;
                                mList.add("第【"+j+"】行的第4列{区域Id}查找不到此区域Id");
                            }
                        }else{
                            flag=false;
                            mList.add("第【"+j+"】行的第4列{区域Id}为空");
                        }
                        model.setOrganId(organId);
                        String status = getValue(row.getCell(4));
                           if(StringUtil.isNotEmpty(status)){
                                if(!ArrayUtils.contains(JOB02,status)){
                                    flag=false;
                                    mList.add("第【"+j+"】行的第5列{是否有效}值只能是1或0");
                                }
                            }else{
                                flag=false;
                                mList.add("第【"+j+"】行的第5列{是否有效}为空");
                            }
                        model.setStatus(status);
                        model.setRoomName(getValue(row.getCell(5)));
                        model.setCustName(getValue(row.getCell(6)));
                        model.setReceiverName(getValue(row.getCell(7)));
                        model.setMobile(getValue(row.getCell(8)));
                        
                        String commId = getValue(row.getCell(9));
                        String community ="";
                         
                          if(StringUtil.isNotEmpty(commId)){
                              if(isInteger(commId)){
                                  Map<String, Object> communityMap = tbHsprContractMapper.getCommunity(commId);
                                   if(communityMap!=null&&communityMap.size()>0){
                                       community=  (String) communityMap.get("CommName"); 
                                       String organCode=  (String) communityMap.get("OrganCode");
                                       if(StringUtil.isNoneBlank(organId)){
                                           if(!organId.equals(organCode)){
                                               flag=false;
                                               mList.add("第【"+j+"】行的第10列{项目Id}通过项目Id查找到的区域Id与该行的(区域Id不匹配)");
                                           }
                                       }
                                   }else{
                                       
                                       flag=false;
                                       mList.add("第【"+j+"】行的第10列{项目Id}查找不到此项目Id");
                                
                                   }
                              }else{
                                  flag=false;
                                  mList.add("第【"+j+"】行的第10列{项目Id}只能是整数");
                              }
                              
                            
                          }else{
                              flag=false;
                              mList.add("第【"+j+"】行的第10列{项目Id}为空");
                          }
                        model.setCommId(commId);
                        String organName = getValue(row.getCell(10));
                         if(StringUtil.isNotEmpty(organName)){
                /*             if(StringUtil.isNotBlankAndNotEmpty(organ)){
                                 if(!organName.equals(organ)){
                                     flag=false;
                                     mList.add("第【"+j+"】行的第11列{区域名称}通过区域Id查找到的区域名称与该行的(区域名称)不匹配"); 
                                 }
                             }*/
                         }else{
                             flag=false;
                             mList.add("第【"+j+"】行的第11列{区域名称}为空"); 
                         }
                        model.setOrganName(organName);
                        String commName = getValue(row.getCell(11));
                    if(StringUtil.isNotEmpty(commName)){
                /*        if(StringUtil.isNotBlankAndNotEmpty(community)){
                            if(!commName.equals(community)){
                                flag=false;
                                mList.add("第【"+j+"】行的第12列{项目名称}通过项目Id查找到的项目名称与该行的(项目名称)不匹配"); 
                            }
                        }*/
                         }else{
                             flag=false;
                             mList.add("第【"+j+"】行的第12列{项目名称}为空"); 
                         }
                        model.setCommName(commName);
                        
                        flag=setErro(flag,mList,getValue(row.getCell(12)),"n",j,13,"n1");
                        model.setN1(getDefault(getValue(row.getCell(12))));
                        
                        flag=setErro(flag,mList,getValue(row.getCell(13)),"n",j,14,"f1");
                        model.setN2(getDefault(getValue(row.getCell(13))));
                        
                        flag=setErro(flag,mList,getValue(row.getCell(14)),"y",j,15,"n31");
                        model.setN31(getDefault(getValue(row.getCell(14))));
                        flag=setErro(flag,mList,getValue(row.getCell(15)),"y",j,16,"n32");
                        model.setN32(getDefault(getValue(row.getCell(15))));
                        flag= setErro(flag,mList,getValue(row.getCell(16)),"y",j,17,"n33");
                        model.setN33(getDefault(getValue(row.getCell(16))));
                        flag=setErro(flag,mList,getValue(row.getCell(17)),"y",j,18,"n34");
                        model.setN34(getDefault(getValue(row.getCell(17))));
                        flag=setErro(flag,mList,getValue(row.getCell(18)),"y",j,19,"n35");
                        model.setN35(getDefault(getValue(row.getCell(18))));
                        flag=setErro(flag,mList,getValue(row.getCell(19)),"y",j,20,"n36");
                        model.setN36(getDefault(getValue(row.getCell(19))));
                        flag=setErro(flag,mList,getValue(row.getCell(20)),"y",j,21,"n37");
                        model.setN37(getDefault(getValue(row.getCell(20))));
                        flag=setErro(flag,mList,getValue(row.getCell(21)),"y",j,22,"n38");
                        model.setN38(getDefault(getValue(row.getCell(21))));
                        flag=setErro(flag,mList,getValue(row.getCell(22)),"y",j,23,"n39");
                        model.setN39(getDefault(getValue(row.getCell(22))));
                        flag=setErro(flag,mList,getValue(row.getCell(23)),"y",j,24,"n310");
                        model.setN310(getDefault(getValue(row.getCell(23))));
                        flag=setErro(flag,mList,getValue(row.getCell(24)),"y",j,25,"n311");
                        model.setN311(getDefault(getValue(row.getCell(24))));
                        flag=setErro(flag,mList,getValue(row.getCell(25)),"y",j,26,"n312");
                        model.setN312(getDefault(getValue(row.getCell(25))));
                        flag=setErro(flag,mList,getValue(row.getCell(26)),"y",j,27,"n313");
                        model.setN313(getDefault(getValue(row.getCell(26))));
                        flag=setErro(flag,mList,getValue(row.getCell(27)),"y",j,28,"n314");
                        model.setN314(getDefault(getValue(row.getCell(27))));
                        flag=setErro(flag,mList,getValue(row.getCell(28)),"y",j,29,"n315");
                        model.setN315(getDefault(getValue(row.getCell(28))));
                        flag=setErro(flag,mList,getValue(row.getCell(29)),"y",j,30,"n316");
                        model.setN316(getDefault(getValue(row.getCell(29))));
                        flag=setErro(flag,mList,getValue(row.getCell(30)),"y",j,31,"n317");
                        model.setN317(getDefault(getValue(row.getCell(30))));
                        flag=setErro(flag,mList,getValue(row.getCell(31)),"y",j,32,"n318");
                        model.setN318(getDefault(getValue(row.getCell(31))));
                        flag=setErro(flag,mList,getValue(row.getCell(32)),"y",j,33,"n319");
                        model.setN319(getDefault(getValue(row.getCell(32))));
                        flag=setErro(flag,mList,getValue(row.getCell(33)),"y",j,34,"n320");
                        model.setN320(getDefault(getValue(row.getCell(33))));
                        flag=setErro(flag,mList,getValue(row.getCell(34)),"y",j,35,"n321");
                        model.setN321(getDefault(getValue(row.getCell(34))));
                        flag=setErro(flag,mList,getValue(row.getCell(35)),"y",j,36,"n322");
                        model.setN322(getDefault(getValue(row.getCell(35))));
                        flag=setErro(flag,mList,getValue(row.getCell(36)),"y",j,37,"n398");
                        model.setN398(getDefault(getValue(row.getCell(36))));
                        
                        model.setN5((getValue(row.getCell(37))==null||getValue(row.getCell(37))=="")?"0":getValue(row.getCell(37)));
                        model.setN6((getValue(row.getCell(38))==null||getValue(row.getCell(38))=="")?"0":getValue(row.getCell(38)));
                        //flag=setErro(flag,mList,getValue(row.getCell(39)),"n",j,40,"n7");
                        model.setN7(getDefault(getValue(row.getCell(39))));
                        
                        flag= setErro(flag,mList,getValue(row.getCell(40)),"n",j,41,"f1");
                        model.setF1(getDefault(getValue(row.getCell(40))));
                        flag=setErro(flag,mList,getValue(row.getCell(41)),"n",j,42,"f2");
                        model.setF2(getDefault(getValue(row.getCell(41))));
                        flag=setErro(flag,mList,getValue(row.getCell(42)),"n",j,43,"f3");
                        model.setF3(getDefault(getValue(row.getCell(42))));
                        
                        flag= setErro(flag,mList,getValue(row.getCell(43)),"n",j,44,"f4");
                        model.setF4(getDefault(getValue(row.getCell(43))));
                        flag= setErro(flag,mList,getValue(row.getCell(44)),"n",j,45,"f5");
                        model.setF5(getDefault(getValue(row.getCell(44))));
                        
                        
                        model.setButlerCognition(getDefault(getValue(row.getCell(45))));
                        
                        
                        model.setOtherUnsatisfy((getValue(row.getCell(46))==null||getValue(row.getCell(46))=="")?"0":getValue(row.getCell(46)));
                    
                       
                        
                        model.setVoice(getValue(row.getCell(47)));
                        
                        
                        model.setCreateBy(userCode);
                        model.setUpdateBy(userCode);
                        model.setPid(pid);
                        list.add(model);
                    }else{
                        break;
                    }
                    j++;
                }
        }  
                
                
                
                if(list!=null&&list.size()>0){
                    hashMap.put("flag",flag);
                    if(!flag){   
                       hashMap.put("data",mList);
                    }
                    list.get(0).setMsgMap(hashMap);
                }
        
                    return list;
                
            }catch(Exception e){
                MicroSatisfyModel model = new MicroSatisfyModel();
                hashMap.put("flag", false);
                mList.add("小业主数据转换异常");
                hashMap.put("data",mList);
                model.setMsgMap(hashMap);
                list.add(model);
               e.printStackTrace();
            }
            
            return list;
        }
    
    
    public String getDefault(String value){
        if(StringUtil.isBlankOrEmpty(value)){
            return "0";
        }
        return value;
    }
    
    public Boolean setErro(Boolean flag,List<String> mList,String value,String s,int i,int e,String Identification){
         
        if(StringUtil.isNotBlankAndNotEmpty(value)){
            if(s.equals("y")){
                if(!ArrayUtils.contains(JOB02,value)){
                    flag=false;
                    mList.add("第【"+i+"】行的第"+e+"列{"+Identification+"}值只能是1或0");
                } 
            }else{
                if(!ArrayUtils.contains(JOB01,value)){
                    flag=false;
                    mList.add("第【"+i+"】行的第"+e+"列{"+Identification+"}值只能是1到5之间,或者是默认值0");
                }   
            }
          //  flag=flag;  
          return flag; 
        }else{
            return flag;  
        }
    }
    
    
/*  
    model.setN1("".equals(getValue(row.getCell(12)))?"0":getValue(row.getCell(12)));
    model.setF1("".equals(getValue(row.getCell(13)))?"0":getValue(row.getCell(13)));
    model.setF2("".equals(getValue(row.getCell(14)))?"0":getValue(row.getCell(14)));
    model.setF3("".equals(getValue(row.getCell(15)))?"0":getValue(row.getCell(15)));
    model.setN2("".equals(getValue(row.getCell(16)))?"0":getValue(row.getCell(16)));
    model.setN31("".equals(getValue(row.getCell(17)))?"0":getValue(row.getCell(17)));
    model.setN32("".equals(getValue(row.getCell(18)))?"0":getValue(row.getCell(18)));
    model.setN33("".equals(getValue(row.getCell(19)))?"0":getValue(row.getCell(19)));
    model.setN34("".equals(getValue(row.getCell(20)))?"0":getValue(row.getCell(20)));
    model.setN35("".equals(getValue(row.getCell(21)))?"0":getValue(row.getCell(21)));
    model.setN36("".equals(getValue(row.getCell(22)))?"0":getValue(row.getCell(22)));
    model.setN37("".equals(getValue(row.getCell(23)))?"0":getValue(row.getCell(23)));
    model.setN38("".equals(getValue(row.getCell(24)))?"0":getValue(row.getCell(24)));
    model.setN39("".equals(getValue(row.getCell(25)))?"0":getValue(row.getCell(25)));
    model.setN310("".equals(getValue(row.getCell(26)))?"0":getValue(row.getCell(26)));
    model.setN311("".equals(getValue(row.getCell(27)))?"0":getValue(row.getCell(27)));
    model.setN312("".equals(getValue(row.getCell(28)))?"0":getValue(row.getCell(28)));
    model.setN313("".equals(getValue(row.getCell(29)))?"0":getValue(row.getCell(29)));
    model.setN314("".equals(getValue(row.getCell(30)))?"0":getValue(row.getCell(30)));
    model.setN315("".equals(getValue(row.getCell(31)))?"0":getValue(row.getCell(31)));
    model.setN316("".equals(getValue(row.getCell(32)))?"0":getValue(row.getCell(32)));
    model.setN317("".equals(getValue(row.getCell(33)))?"0":getValue(row.getCell(33)));
    model.setN318("".equals(getValue(row.getCell(34)))?"0":getValue(row.getCell(34)));
    model.setN319("".equals(getValue(row.getCell(35)))?"0":getValue(row.getCell(35)));
    model.setN320("".equals(getValue(row.getCell(36)))?"0":getValue(row.getCell(36)));
    model.setN321("".equals(getValue(row.getCell(37)))?"0":getValue(row.getCell(37)));
    model.setN322("".equals(getValue(row.getCell(38)))?"0":getValue(row.getCell(38)));
    model.setN398("".equals(getValue(row.getCell(39)))?"0":getValue(row.getCell(39)));
    model.setOtherUnsatisfy("".equals(getValue(row.getCell(40)))?"0":getValue(row.getCell(40)));
    model.setN5("".equals(getValue(row.getCell(41)))?"0":getValue(row.getCell(41)));
    model.setN6("".equals(getValue(row.getCell(42)))?"0":getValue(row.getCell(42)));
    model.setN7("".equals(getValue(row.getCell(43)))?"0":getValue(row.getCell(43)));*/
    
    /**
     * @描述 获取cell数据
     * @作者 张世通
     * @时间 2018年6月21日
     * @版本 
     * @param cell
     * @return
     */
    //@SuppressWarnings({ "static-access", "deprecation" })
/*  private String getValue(Cell cell){
        if(null == cell){
            return "";
        }else{
            if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN){  
                return String.valueOf( cell.getBooleanCellValue());  
            }else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){ 
                if(HSSFDateUtil.isCellDateFormatted(cell)){
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
                }else{
                    return String.valueOf( cell.getNumericCellValue());  
                }
            }else if(cell.getCellType() == cell.CELL_TYPE_FORMULA){
                try{
                    return String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    return String.valueOf(cell.getRichStringCellValue());
                }
            }else{
                return String.valueOf(cell.getStringCellValue());  
            }  
        }
    }*/
    
    
       /**
     * 获取单元格的值，不论单元格是什么形式的，一律返回String
     * null或者"    "返回 ""
     * " trim "返回 "trim"
     * @author LiuQS
     * */
    public static String getValue(Cell cell) {
        return UploadUtil.getCellValue(cell);
    }
    /**
     * @描述 按批次查询导入数据
     * @作者 张世通
     * @时间 2018年6月22日
     * @version 
     * @param pid
     * @param timeStr
     * @return
     */
    @Override
    public List<Map<String, Object>> queryImportData(String pid,String timeStr,PageRowBounds pageRowBounds) {
        List<Map<String, Object>> queryImportData = microSatisfMapper.queryImportData(pid,timeStr,pageRowBounds);
        if(queryImportData!=null&&queryImportData.size()>0){
            for (Map<String, Object> map : queryImportData) {
                if(map!=null&&map.getOrDefault("ifLocking","")!=""){
                   String ifLocking= (String) map.get("ifLocking");
                   int parseInt = Integer.parseInt(ifLocking);
                   map.put("ifLocking",parseInt);
                }
                if(map!=null&&map.getOrDefault("isAssessment","")!=""){
                    String isAssessment= (String) map.get("isAssessment");
                    int parseInt = Integer.parseInt(isAssessment);
                    map.put("isAssessment",parseInt);
                 }
            }
        }
        return queryImportData;
    }
    
    /**
     * @描述 查询pid
     * @作者 张世通
     * @时间 2018年6月22日
     * @version 
     * @return
     */
    @Override
    public List<Map<String, String>> queryPid() {
        return microSatisfMapper.queryPid();
    }
    /**
     * @描述 查询当月管家满意度
     * @作者 张世通
     * @时间 2018年6月22日
     * @version 
     * @param pageRowBounds
     * @return
     */
    @Override
    public List<Map<String, String>> queryManagerSatisfy(PageRowBounds pageRowBounds,String timeStr,String organId) {
        List<Map<String, String>> managerSatisfy = microSatisfMapper.getManagerSatisfy(timeStr,organId,pageRowBounds);
        for (Map<String, String> map : managerSatisfy) {
            map.put("beginDate",timeStr );
            map.put("endDate", timeStr);
            
            Map<String, String> managerData = findManagerData(map);
            map.put("recognitionPercentage",managerData.getOrDefault("avgRecognitionPercentage","") );
            map.put("satisfaction", managerData.getOrDefault("avgSatisfaction",""));
        }
        
        
       // return microSatisfMapper.queryManagerSatisfy(pageRowBounds,beginDate,endDate,organId);
        return managerSatisfy;
    }
    /**
     * @描述 查询当月管家满意度排名
     * @作者 张世通
     * @时间 2018年6月28日
     * @version 
     * @param pageRowBounds
     * @param timeStr
     * @param organId
     * @param commId
     * @return
     */
    @Override
    public List<Map<String, String>> queryManagerSatisfyRank(PageRowBounds pageRowBounds, String timeStr,
            String organId, String commId) {
        return microSatisfMapper.queryManagerSatisfyRank(pageRowBounds, timeStr, organId, commId);
    }
    /**
     * @描述 查询管家满意度折线图
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @param timeStr
     * @param organId
     * @param commId
     * @return
     */
    @Override
    public Map<String, String> queryManagerScore(String timeStr, String organId, String commId) {
    
        
         Map<String,String> map=new HashMap<>();
         map.put("beginDate",timeStr);
         map.put("endDate",timeStr);
         map.put("organId",organId);
         map.put("commId",commId);
         
         
        Map<String, String> managerData = findYeryManagerData(map); 

       return managerData;
    }
    /**
     * @描述 查询当月区域满意度排名
     * @作者 张世通
     * @时间 2018年6月23日
     * @version 
     * @param pageRowBounds
     * @return
     */
    @Override
    public List<MicroSatisfyRankModel> queryOrganRank(PageRowBounds pageRowBounds,String beginDate,String endDate,String flag,String cruentDate,String organId,String regionId) {
        //TODO         aa
       
        if(StringUtils.isNotBlank(organId)&&(StringUtils.isNotBlank(regionId)&&!organId.equals(regionId))){
            return null;
        }
        
        
        
        
        if(flag.equals("monthly")){
            if(beginDate.equals(endDate)){
                    String format = getMonthReduction(beginDate);
                
                    //还要排除  不考核的项目 
                    
                List<Map<String, String>> effectiveProject = getOrganEffectiveProject(beginDate, endDate, null,null);
                    
                List<Map<String, String>> project = getOrganEffectiveProject(format, format, null,null);
                    
                List<MicroSatisfyRankModel> currentRegional=new ArrayList<>();
                if(effectiveProject!=null&&effectiveProject.size()>0){
                   currentRegional= getRegionalRanking(beginDate,beginDate,"n",pageRowBounds,null,effectiveProject);
                }
                List<MicroSatisfyRankModel> lastRegional=new ArrayList<>();
                if(project!=null&&project.size()>0){
                    getRegionalRanking(format,format,"n",pageRowBounds,null,project);
                 }
                
                List<MicroSatisfyRankModel> commonRegionalRanking = getCommonRegionalRanking(lastRegional, currentRegional);
                
                if(commonRegionalRanking!=null&&commonRegionalRanking.size()>0){
                    
                    //getOrganCollections(commonRegionalRanking);
                    
                    List<MicroSatisfyRankModel> list=new ArrayList<>();
                    List<MicroSatisfyRankModel> lModels;
                    if(organId!=null){
                        
                        for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                            if(microSatisfyRankModel.getOrganId().equals(organId)){
                                list.add(microSatisfyRankModel);
                            } 
                        }
                        pageRowBounds.setTotal(new Long(list.size()));
                       lModels=getLimit(pageRowBounds, list);
                        
                        return lModels;
                    }
                    
                   
                    if(StringUtils.isNotBlank(regionId)){

                            for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                                if(microSatisfyRankModel.getOrganId().equals(regionId)){
                                    list.add(microSatisfyRankModel);
                                } 
                            }
                            pageRowBounds.setTotal(new Long(list.size()));
                           lModels=getLimit(pageRowBounds, list);
                            
                            return lModels;
 
                    }else{
                        pageRowBounds.setTotal(new Long(commonRegionalRanking.size()));
                        lModels=  getLimit(pageRowBounds, commonRegionalRanking);
                     }
                    
                    return lModels;
                }else{
                    return null;
                }
                
                
                
            }else{
                List<String> intervalTime = getIntervalTime(beginDate,endDate);
                
    String xDate="";
                
                String nDate="";
                
                if(cruentDate!=null&&cruentDate!=""){
                    String substring = cruentDate.substring(0,7);
                    for (String string : intervalTime) {
                        String substring2 = string.substring(0, 7);
                        if(substring.equals(substring2)){
                            xDate=string;
                            nDate=getMonthReduction(string);
                            break;
                        }
                    }
                }else{
                    try {
                        throw new Exception("比对值不能为空");
                    } catch (Exception e) {
                          
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                        
                    }
                }
                
                List<Map<String, String>> effectiveProject = getOrganEffectiveProject(xDate, xDate, null,null);
                
                List<Map<String, String>> project = getOrganEffectiveProject(nDate, nDate, null,null);
                
                List<MicroSatisfyRankModel> currentRegional=new ArrayList<>();
                if(effectiveProject!=null&&effectiveProject.size()>0){
                   currentRegional= getRegionalRanking(xDate,xDate,"n",pageRowBounds,null,effectiveProject);
                }
                List<MicroSatisfyRankModel> lastRegional=new ArrayList<>();
                if(project!=null&&project.size()>0){
                    lastRegional= getRegionalRanking(nDate,nDate,"n",pageRowBounds,null,project);
                 }
                 
                List<MicroSatisfyRankModel> commonRegionalRanking = getCommonRegionalRanking(lastRegional, currentRegional);
                
                if(commonRegionalRanking!=null&&commonRegionalRanking.size()>0){
                    //getOrganCollections(commonRegionalRanking);  
                    
                    
                    List<MicroSatisfyRankModel> aList=new ArrayList<>();
                    List<MicroSatisfyRankModel> list=new ArrayList<>();
                    if(organId!=null){
                        
                        for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                            if(microSatisfyRankModel.getOrganId().equals(organId)){
                                list.add(microSatisfyRankModel);
                            } 
                        }
                        pageRowBounds.setTotal(new Long(list.size()));
                        aList=getLimit(pageRowBounds, list);
                    }else{
                        
                        if(StringUtils.isNotBlank(regionId)){

                            for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                                if(microSatisfyRankModel.getOrganId().equals(regionId)){
                                    list.add(microSatisfyRankModel);
                                } 
                            }
                            pageRowBounds.setTotal(new Long(list.size()));
                            aList=getLimit(pageRowBounds, list);
                    }else{
                        pageRowBounds.setTotal(new Long(commonRegionalRanking.size()));
                        aList= getLimit(pageRowBounds, commonRegionalRanking); 
                    }
             }

                    
                    for (MicroSatisfyRankModel cModel : aList) {
                
                         Map<String,String> sMap=new HashMap<>();
                         
                         for (String string : intervalTime) {
                             
                             List<Map<String, String>> cList = getOrganEffectiveProject(string, string, cModel.getOrganId(),null);
                             if(cList!=null&&cList.size()>0){
                                 Map<String, List<MicroSatisfyRankModel>> oMap =
                                         gettingGroupedData(string, string, organId, cList);

                                 Double colxxlect=new Double(0);
                                   //根据区域 分组 并且计算出  区域 满意度 得分
                                   for(String key:oMap.keySet()){
                                       List<MicroSatisfyRankModel> liMicroSatisfyRankModels = oMap.get(key);
                                     //区域满意度
                                        colxxlect =liMicroSatisfyRankModels.stream().collect(Collectors.averagingDouble(MicroSatisfyRankModel::getSatisfy));
                                   }
                                   BigDecimal setScale = new BigDecimal(colxxlect).setScale(2,BigDecimal.ROUND_HALF_UP);
                                   sMap.put(string, setScale.toString());  
                             }    
                         }
                         cModel.setMap(sMap);
                     }  

                    return aList;
                }else{
                    return null;
                }
            

            }

        }

        String ks = beginDate.substring(5,7);
        String js = endDate.substring(5,7);
        
        int yerInt = Integer.parseInt(beginDate.substring(0,4));
        
        List<MicroSatisfyRankModel> lastRegional=null;
        
        if(ks.equals("01")&&js.equals("03")){
            int parseInt = Integer.parseInt(beginDate.substring(0,4))-1;
            String ksDate = Integer.toString(parseInt).concat("-10-01");
            String jsDate = Integer.toString(parseInt).concat("-12-01");
            List<Map<String, String>> project = getOrganEffectiveProject(ksDate, jsDate, null,null);

           lastRegional= getRegionalRanking(ksDate, jsDate,"y",pageRowBounds,null,project);
           
        }else if (ks.equals("04")&&js.equals("06")) {
            String ksDate = Integer.toString(yerInt).concat("-01-01");
            String jsDate = Integer.toString(yerInt).concat("-03-01");
            
            List<Map<String, String>> project = getOrganEffectiveProject(ksDate, jsDate, null,null);
      
            lastRegional= getRegionalRanking(ksDate, jsDate,"y",pageRowBounds,null,project);
        }else if (ks.equals("07")&&js.equals("09")) {
            String ksDate = Integer.toString(yerInt).concat("-04-01");
            String jsDate = Integer.toString(yerInt).concat("-06-01");
            
            List<Map<String, String>> project = getOrganEffectiveProject(ksDate, jsDate, null,null);
            
            lastRegional= getRegionalRanking(ksDate, jsDate,"y",pageRowBounds,null,project);
        }else if (ks.equals("10")&&js.equals("12")) {
            String ksDate = Integer.toString(yerInt).concat("-07-01");
            String jsDate = Integer.toString(yerInt).concat("-09-01");
            
            List<Map<String, String>> project = getOrganEffectiveProject(ksDate, jsDate, null,null);
            
            lastRegional= getRegionalRanking(ksDate, jsDate,"y",pageRowBounds,null,project);
        }
        
        List<Map<String, String>> effectiveProject = getOrganEffectiveProject(beginDate, endDate, null,null);
        
        List<MicroSatisfyRankModel> currentRegional= getRegionalRanking(beginDate, endDate,"y",pageRowBounds,null,effectiveProject);
        
        List<MicroSatisfyRankModel> commonRegionalRanking = getCommonRegionalRanking(lastRegional, currentRegional);

        if(commonRegionalRanking!=null&&commonRegionalRanking.size()>0){

            
            //getOrganCollections(commonRegionalRanking); 
            
            List<MicroSatisfyRankModel> list=new ArrayList<>();
            List<MicroSatisfyRankModel> lModels;
            if(organId!=null){
                
                for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                    if(microSatisfyRankModel.getOrganId().equals(organId)){
                        list.add(microSatisfyRankModel);
                    } 
                }
                pageRowBounds.setTotal(new Long(list.size()));
                lModels=getLimit(pageRowBounds, list);
                
                return lModels;
            }
            
            
            if(StringUtils.isNotBlank(regionId)){

                    for (MicroSatisfyRankModel microSatisfyRankModel : commonRegionalRanking) {
                        if(microSatisfyRankModel.getOrganId().equals(regionId)){
                            list.add(microSatisfyRankModel);
                        } 
                    }
                    pageRowBounds.setTotal(new Long(list.size()));
                   lModels=getLimit(pageRowBounds, list);
                    
                    return lModels;

            }else{
                pageRowBounds.setTotal(new Long(commonRegionalRanking.size()));
                lModels=  getLimit(pageRowBounds, commonRegionalRanking);
             } 
            return lModels;
        
        }else{
            return null;
        }

    }


    private List<MicroSatisfyRankModel> getLimit(PageRowBounds pageRowBounds,
            List<MicroSatisfyRankModel> commonRegionalRanking) {
        int offset = pageRowBounds.getOffset();
        int limit = pageRowBounds.getLimit();
        int o=offset-1;
        int star=o*limit;

        if(commonRegionalRanking.size()>0){
            int end =commonRegionalRanking.size()-star>limit?star+limit:commonRegionalRanking.size();
            
            List<MicroSatisfyRankModel>   list = commonRegionalRanking.subList(star, end==0?star:end);
            return list;
        }else{
            return commonRegionalRanking;
        }
    }

    
    //区域详细--折线图
       public Map<String, Object> queryRegionScore(String beginDate,String endDate, String organId,String flag) {
            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM");

            Map<String,Object> map=new HashMap<>();
            if(flag.equals("monthly")){
                List<String> intervalTime =new ArrayList<>();
                if(beginDate.equals(endDate)){
                    intervalTime.add(beginDate);
                }else{
                    intervalTime = getIntervalTime(beginDate,endDate);
                }
                
                
                for (String string : intervalTime) {
                    List<Map<String, String>> effectiveProject = getOrganEffectiveProject(string, string, organId,null);
                       
                    BigDecimal bigDecimal = getWholeCountrySatisfaction(beginDate, endDate, organId,
                            effectiveProject);
               
                    try {
                      Date  format = formatDate.parse(string);
                      String   format2 = formatDate.format(format);
                         
                         map.put(format2,bigDecimal.toString()); 
                    } catch (ParseException e) {
                        e.printStackTrace();   
                    }   
                }
                return map;
            }

            ArrayList<Entry<String, String>> list = getList(beginDate.substring(0,4));

            int i=1;
            for (Entry<String, String> entry : list) {
                List<Map<String, String>> effectiveProject = getOrganEffectiveProject(entry.getKey(),entry.getValue(), organId,null);
                
                BigDecimal bigDecimal = getWholeCountrySatisfaction(entry.getKey(),entry.getValue(), organId,
                        effectiveProject);
                
               map.put("第"+i+"季度", bigDecimal.toString());
               i++;
            }
            return map;
        }

    private List<Map<String, String>> getEffectiveProject(String beginDate, String endDate,
            String organId,String commId) {
        List<Map<String, String>> effectiveProject = microSatisfMapper.getEffectiveProject(beginDate,endDate,organId,commId);
        
        List<Map<String, String>> organIfLocking = microSatisfMapper.getOrganIfLocking(beginDate,endDate,organId,commId);
      
        organIfLocking.stream().forEach(m-> effectiveProject.add(m));
         List<Map<String, String>> collect = effectiveProject.parallelStream().distinct().collect(Collectors.toList());
        
        return collect;
    }
    
    private List<Map<String, String>> getOrganEffectiveProject(String beginDate, String endDate,
            String organId,String commId) {
        List<Map<String, String>> organEffectiveProject = microSatisfMapper.getOrganEffectiveProject(beginDate,endDate,organId,commId);
        List<Map<String, String>> organIfLocking = microSatisfMapper.getOrganIfLocking(beginDate,endDate,organId,commId);
        organIfLocking.stream().forEach(m-> organEffectiveProject.add(m));
         List<Map<String, String>> collect = organEffectiveProject.parallelStream().distinct().collect(Collectors.toList());
      
        return collect;
    }

    private String getMonthReduction(String beginDate) {
        SimpleDateFormat ee = new SimpleDateFormat("yyyy-MM-dd");//格式化为2017-10
            String format ="";
            try {
        Date date= ee.parse(beginDate);
        Calendar calendar = Calendar.getInstance();//得到Calendar实例
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        format = ee.format(calendar.getTime());
            } catch (Exception e) {
          
        // TODO Auto-generated catch block  
        e.printStackTrace();  
        
            }
        return format;
    }

    private List<MicroSatisfyRankModel> getCommonRegionalRanking(List<MicroSatisfyRankModel> lastRegional, List<MicroSatisfyRankModel> currentRegional) {
        //Map<String,Object> map=new HashMap<>();
        if((currentRegional!=null&&currentRegional.size()>0)&&(lastRegional!=null&&lastRegional.size()>0)){

            for (MicroSatisfyRankModel model : currentRegional) {
                
               // int i=0;
                for (MicroSatisfyRankModel lModel : lastRegional) {
                    if((lModel!=null&&lModel.getOrganId()!=null)&&(model!=null&&model.getOrganId()!=null)){
                        if(model.getOrganId().equals(lModel.getOrganId())){
                            int rankCurMon = model.getOrganRank();
                            int lastRankCurMon = lModel.getOrganRank();
                            
                            String curSatisfy = model.getCommScore();
                            String lastSatisfy = lModel.getCommScore();
                            
                           // if(!curSatisfy.equals("0")&&!lastSatisfy.equals("0")){
                                Map<String, Object> rankings = getRankings(lastSatisfy,curSatisfy,rankCurMon,lastRankCurMon);
                                
                                model.setRankLastMon(lastRankCurMon);
                                model.setMonthUp(String.valueOf(rankings.get("monthlyPromotion")));
                                model.setRankChange(String.valueOf(rankings.get("rankingsChange")));
                            //}
                   
                           // i++;
                            break;
                        }
                    }
                   
                }

            }
           
            return currentRegional;  
            
        }
        return currentRegional;  
    }
    
    
    public List<String> getIntervalTime(String beginDate,String endDate){
        
        List<String> list=new ArrayList<>();
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");//格式化为2017-10
            Date date = formatter.parse(beginDate);
            SimpleDateFormat ee = new SimpleDateFormat("yyyy-MM");//格式化为2017-10
            Date date1= ee.parse(endDate);

             list.add(beginDate);
            for(int i=1;i<=12;i++){
                Calendar calendar = Calendar.getInstance();//得到Calendar实例
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, +i);
                String format = formatter.format(calendar.getTime());
                Date time = calendar.getTime();
                
                list.add(format.concat("-01"));  
                if(date1.equals(time)){
                    break;
                }
                 
               
            }
        } catch (Exception e) {
              
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            
        }
        return list;
    }
    
    
    /**
     * 
     * getRankings:.获取排名变化（提高了多少名）  和月提升值 <br/>  
     *  
     * @param lastSatisfy 上月得分
     * @param curSatisfy 本月得分
     * rankCurMon  本月排名
     * lastRankCurMo 上月排名
     * @return
     */
    public Map<String,Object> getRankings(String lastSatisfy,String curSatisfy,int rankCurMon,int lastRankCurMon){
       //所有区域--排名--- 先根据 传入的时间  去基本数据表里 查出 区域的分数 
        
        Map<String,Object> map=new HashMap<>();
            
            //计算提升值
            BigDecimal curSa = new BigDecimal(curSatisfy);
            BigDecimal lastSa = new BigDecimal(lastSatisfy);
            
            BigDecimal saChange = curSa.subtract(lastSa);
            String str="";
            if(saChange.intValue()<0){
                if(curSatisfy.equals("0.00")||curSatisfy.equals("0")){
                    str=String.format("-%s%%",100);    
                }else{
                    //下降了
                    String string = saChange.toString();
                    
                    String substring = string.substring(1,string.length());
                    
                    
                    System.out.println("--vvvvvv------   "+substring+"    "+curSa);

                   BigDecimal multiply = new BigDecimal(string.substring(1,string.length())).divide(curSa,2,BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100"));

                   str=String.format("-%s%%",multiply.intValue());    
                }
      
               
            }else if(saChange.intValue()>0){
              //提升了
                
                BigDecimal multiply =saChange.divide(curSa,2,BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"));

              str=String.format("+%s%%",multiply.intValue());  
            }else{
                str=String.format("%s%%",0);  
            }
            

     
            map.put("monthlyPromotion", str);
            
            //计算排名
            int change = rankCurMon -lastRankCurMon;
            
            map.put("rankingsChange",change);//负数为下降 --正数为上升
          //上月排名，本月排名，排名变动（上升了多少或下降了多少）

        
        return map;
    }

    private List<MicroSatisfyRankModel> getRegionalRanking(String beginDate, String endDate,String flag,PageRowBounds pageRowBounds,String organId,List<Map<String, String>> effectiveProject) {
        Map<String, List<MicroSatisfyRankModel>> oMap =
                gettingGroupedData(beginDate, endDate, organId, effectiveProject);
          
          List<MicroSatisfyRankModel> cList=new ArrayList<>();
          //根据区域 分组 并且计算出  区域 满意度 得分
          for(String key:oMap.keySet()){
              List<MicroSatisfyRankModel> list = oMap.get(key);
            //区域满意度
              Double colxxlect =list.stream().collect(Collectors.averagingDouble(MicroSatisfyRankModel::getSatisfy));
               BigDecimal setScale = new BigDecimal(colxxlect).setScale(2,BigDecimal.ROUND_HALF_UP);
              MicroSatisfyRankModel model=new MicroSatisfyRankModel();
              String score = getAssessmentScore(key,null,colxxlect.toString());
              //collect(Collectors.toMap(MicroSatisfyRankModel::getOrganId, MicroSatisfyRankModel::getOrganName));
             // Map<String, String> collect2 = ;
              List<MicroSatisfyRankModel> dList=list.stream().filter(m-> key.equals(m.getOrganId())).collect(Collectors.toList());
             String organName=dList.size()>0?dList.get(0).getOrganName():"";
              model.setSatisfy(setScale.doubleValue());
              model.setOrganId(key);
              model.setOrganName(organName);
              model.setCommScore(score);
              model.setCommNum(list.size()+"");
              
              cList.add(model);
          }
          List<MicroSatisfyRankModel> collect2 = cList.stream().sorted(Comparator.comparing(MicroSatisfyRankModel::getSatisfy).reversed()).collect(Collectors.toList());
          int i=0;
          Double satisfy=new Double(0);
          for (MicroSatisfyRankModel microSatisfyRankModel4 : collect2) {
              if(satisfy.equals(microSatisfyRankModel4.getSatisfy())){
                  microSatisfyRankModel4.setOrganRank(i);
              }else{
                  microSatisfyRankModel4.setOrganRank(++i);
              }
              satisfy=microSatisfyRankModel4.getSatisfy();
          }
          //如果写好 了，还要 看一下  封装的 参数  和  之前的方法 能不能 对应上
          
          //项目 的 也 要 参考 这里面 的 算项目 的方式
          
          
          //折线图的   要 先算项目 再算区域，后面 再通过区域 得出 全国
          
        return collect2;
    }



    private Map<String, List<MicroSatisfyRankModel>> gettingGroupedData(String beginDate,
            String endDate, String organId, List<Map<String, String>> effectiveProject) {
        List<MicroSatisfyOrganDetailModel> queryPublicProject = microSatisfMapper.queryPublicProject(beginDate,endDate,"1",organId,effectiveProject);
        List<MicroSatisfyOrganDetailModel> publicProject = microSatisfMapper.queryPublicProject(beginDate,endDate,"2",organId,effectiveProject);

        //effectiveProject  这里面 也要 把 不考核的排除

        
        List<MicroSatisfyRankModel> lModels=new ArrayList<>();
        
        if(queryPublicProject!=null&&queryPublicProject.size()>0){
            for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : queryPublicProject) {
                
                String basicLevel ="0";
                String commId=microSatisfyOrganDetailModel.getCommId();
                String userNum = microSatisfyOrganDetailModel.getUserNum();
                String serviceNum = microSatisfyOrganDetailModel.getServiceNum();
                String safeNum = microSatisfyOrganDetailModel.getSafeNum();
                String environmentNum = microSatisfyOrganDetailModel.getEnvironmentNum();
                //如果被豁免 就直接 根据  项目id去 项目的目标表  里面取  基础目标
                if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        basicLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                  basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                }
                
                String  score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), basicLevel);
            
                MicroSatisfyRankModel microSatisfyRankModel=new MicroSatisfyRankModel();
                microSatisfyRankModel.setCommScore(score);
                microSatisfyRankModel.setSatisfy(new Double(basicLevel));
                microSatisfyRankModel.setCommId(commId);
                microSatisfyRankModel.setOrganId(microSatisfyOrganDetailModel.getOrganId());
                microSatisfyRankModel.setCommName(microSatisfyOrganDetailModel.getCommName());
                microSatisfyRankModel.setOrganName(microSatisfyOrganDetailModel.getOrganName());
                
                lModels.add(microSatisfyRankModel);
            }
        }
        
          if(publicProject!=null&&publicProject.size()>0){
              for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : publicProject) {
                  String userNum = microSatisfyOrganDetailModel.getUserNum();
                  String highUserNum = microSatisfyOrganDetailModel.getHighUserNum();
                  String commId=microSatisfyOrganDetailModel.getCommId();
                  String qualityLevel="0";
                //如果被豁免 就直接 根据  项目id去 项目的目标表  里面取  基础目标
                  if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                      MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                      if(microSatisfyPointModel!=null){
                          qualityLevel=microSatisfyPointModel.getBasePoint();
                      }
                     
                  }else{
                      qualityLevel = getQualityLevel(userNum, highUserNum);
                  }
         
                    String score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), qualityLevel);
                    
                    MicroSatisfyRankModel microSatisfyRankModel=new MicroSatisfyRankModel();
                    microSatisfyRankModel.setCommScore(score);
                    microSatisfyRankModel.setSatisfy(new Double(qualityLevel));
                    microSatisfyRankModel.setCommId(commId);
                    microSatisfyRankModel.setOrganId(microSatisfyOrganDetailModel.getOrganId());
                    microSatisfyRankModel.setCommName(microSatisfyOrganDetailModel.getCommName());
                    microSatisfyRankModel.setOrganName(microSatisfyOrganDetailModel.getOrganName());
                    
                    lModels.add(microSatisfyRankModel);
                }
            }

          Map<String, List<MicroSatisfyRankModel>> oMap = lModels.stream().collect(Collectors.groupingBy((MicroSatisfyRankModel::getOrganId)));
        return oMap;
    }

    
    
    
   

    private List<String> getSortValue(List<String> collect, List<String> collect2) {
        List<String> notList=new ArrayList<>();
        for (String string : collect) {
            
            int i=0;
            for (String string2 : collect2) {
                if(string.equals(string2)){
                    i++;
                }
            }
            if(i==0){
                notList.add(string);
            }else{
                i=0;
            }
        }
        return notList;
    }
    
    //根据实际满意度 得到 考核分数
    public String getAssessmentScore(String organId,String commId,String satisfyOrign){
        MicroSatisfyPointModel pointModel =null;
        if(organId!=null){
          pointModel = microSatisfMapper.queryOrganPointByOrganCode(organId);
        }else{
          pointModel = microSatisfMapper.queryCommPointByCommCode(commId);
        }
        
        //查询目标
        
        if(null==satisfyOrign){
            satisfyOrign="0";
        }
        String flag="0";
        
        //计算得分
        if(null != pointModel){
            BigDecimal crossPoint = new BigDecimal(pointModel.getCrossPoint()); //门槛
            BigDecimal basePoint = new BigDecimal(pointModel.getBasePoint());   //保底
            BigDecimal middlePoint = new BigDecimal(pointModel.getMiddePoint());//尖叫
            BigDecimal highPoint = new BigDecimal(pointModel.getHighPoint());   //嚎叫
            BigDecimal curOrignPoint = new BigDecimal(satisfyOrign);  //p值(实际得到的 满意度)
            if(curOrignPoint.compareTo(crossPoint) == -1){
                flag="0";
            }else if(curOrignPoint.compareTo(crossPoint) > -1 && curOrignPoint.compareTo(basePoint) == -1){
                BigDecimal satisfy = new BigDecimal("60").add(new BigDecimal("40").multiply(curOrignPoint.subtract(crossPoint)
                        .divide(basePoint.subtract(crossPoint),4,BigDecimal.ROUND_HALF_UP))).setScale(2, BigDecimal.ROUND_HALF_UP);
                flag=satisfy.toString();
            }else if(curOrignPoint.compareTo(basePoint) > -1 && curOrignPoint.compareTo(middlePoint) == -1){
                BigDecimal satisfy = new BigDecimal("100").add(new BigDecimal("10").multiply(curOrignPoint.subtract(basePoint)
                        .divide(middlePoint.subtract(basePoint),4,BigDecimal.ROUND_HALF_UP))).setScale(2, BigDecimal.ROUND_HALF_UP);
                flag=satisfy.toString();
            }else if(curOrignPoint.compareTo(middlePoint) > -1 && curOrignPoint.compareTo(highPoint) == -1){
                BigDecimal satisfy = new BigDecimal("110").add(new BigDecimal("10").multiply(curOrignPoint.subtract(middlePoint)
                        .divide(highPoint.subtract(middlePoint),4,BigDecimal.ROUND_HALF_UP))).setScale(2, BigDecimal.ROUND_HALF_UP);
                flag=satisfy.toString();
            }else{
                flag="120.00";
            }
        }
        
        return flag; 
    }
    
    
    /**
     * @描述 查询当月项目满意度排名
     * @作者 张世通
     * @时间 2018年6月23日
     * @version 
     * @param pageRowBounds
     * @return
     */
    @Override
    public List<MicroSatisfyRankModel> queryCommRank(PageRowBounds pageRowBounds,String beginDate,String endDate,String flag,String cruentDate,String organId,String regionId,String projectId) {
      //  Map<String,Object> map=new HashMap<>();
        
           if(StringUtils.isNotBlank(organId)&&(StringUtils.isNotBlank(regionId)&&!organId.equals(regionId))){
                return null;
            }
        
        if(flag.equals("monthly")){
            
            if(beginDate.equals(endDate)){   
                //TODO x
                
                String format = getMonthReduction(beginDate);

                List<Map<String, String>> effectiveProject = getEffectiveProject(beginDate, endDate, null,null);

                List<Map<String, String>> pList = getEffectiveProject(format, format, null,null);
                
                List<MicroSatisfyRankModel> curr = new ArrayList<>();
                if(effectiveProject!=null&&effectiveProject.size()>0){
                    curr =getProjectRanking(beginDate, endDate,pageRowBounds,null,effectiveProject);
                }
                List<MicroSatisfyRankModel> last = new ArrayList<>();
                if(pList!=null&&pList.size()>0){
                    last =getProjectRanking(format, format,pageRowBounds,null,pList);
                 }

                getProjectRankingShare(last, curr);

                if(curr!=null&&curr.size()>0){
                    //getCollections(curr);
                    
                    List<MicroSatisfyRankModel> lModels = new ArrayList<>();
                    
                    List<MicroSatisfyRankModel> list=new ArrayList<>();
                    
                    if(organId!=null){  
                        
                        for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                            if(microSatisfyRankModel.getOrganId().equals(organId)){
                                if(StringUtils.isNotBlank(projectId)){
                                    if(projectId.equals(microSatisfyRankModel.getCommId())){
                                        list.add(microSatisfyRankModel);
                                    }
                                }else{
                                    list.add(microSatisfyRankModel);
                                }
                               
                            } 
                        }
                        pageRowBounds.setTotal(new Long(list.size()));
                         lModels=getLimit(pageRowBounds, list);
                        
                        return lModels;
                    }
                    
                    
                    
                    
                    if(StringUtils.isNotBlank(regionId)){
                        
                        
                        if(StringUtils.isNotBlank(projectId)){
                            for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                if(microSatisfyRankModel.getOrganId().equals(regionId)&&projectId.equals(microSatisfyRankModel.getCommId())){
                                    list.add(microSatisfyRankModel);
                                } 
                            }
                            pageRowBounds.setTotal(new Long(list.size()));
                           lModels=getLimit(pageRowBounds, list);
                        }else{
                            for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                if(microSatisfyRankModel.getOrganId().equals(regionId)){
                                    list.add(microSatisfyRankModel);
                                } 
                            }
                            pageRowBounds.setTotal(new Long(list.size()));
                           lModels=getLimit(pageRowBounds, list); 
                        }
 

                }else if(StringUtils.isNotBlank(projectId)){
                    for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                        if(projectId.equals(microSatisfyRankModel.getCommId())){
                            list.add(microSatisfyRankModel);
                        } 
                    }
                    pageRowBounds.setTotal(new Long(list.size()));
                   lModels=getLimit(pageRowBounds, list);
                }else{
                    pageRowBounds.setTotal(new Long(curr.size()));
                    
                    lModels=getLimit(pageRowBounds, curr);
                 }
                    
                return  lModels;
                }else{
                    return null; 
                }
                
      
              
            }else{
                
                List<String> intervalTime = getIntervalTime(beginDate,endDate);

                
                String xDate="";
                
                String nDate="";
                
                if(cruentDate!=null&&cruentDate!=""){
                    String substring = cruentDate.substring(0,7);
                    for (String string : intervalTime) {
                        String substring2 = string.substring(0, 7);
                        if(substring.equals(substring2)){
                            xDate=string;
                            nDate=getMonthReduction(string);
                            break;
                        }
                    }
                }else{
                    try {
                        throw new Exception("比对值不能为空");
                    } catch (Exception e) {
                          
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                        
                    }
                }
                
                
                List<Map<String, String>> effectiveProject = getEffectiveProject(xDate,xDate,null,null);
                
                
                List<Map<String, String>> pList = getEffectiveProject(nDate,nDate,null,null);
                
                
                List<MicroSatisfyRankModel> curr = new ArrayList<>();
                if(effectiveProject!=null&&effectiveProject.size()>0){
                    curr = getProjectRanking(xDate,xDate,pageRowBounds,null,effectiveProject);
                }
                List<MicroSatisfyRankModel> last = new ArrayList<>();
                if(pList!=null&&pList.size()>0){
                    last = getProjectRanking(nDate,nDate,pageRowBounds,null,pList);
                 }

               getProjectRankingShare(last, curr);

          
                    if(curr!=null&&curr.size()>0){
      
                       // getCollections(curr);
                        
                        List<MicroSatisfyRankModel> lModels=new ArrayList<>();
                        List<MicroSatisfyRankModel> list=new ArrayList<>();
                        if(organId!=null){
                            
                            for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                if(microSatisfyRankModel.getOrganId().equals(organId)){
                                    
                                    if(StringUtils.isNotBlank(projectId)){
                                        if(projectId.equals(microSatisfyRankModel.getCommId())){
                                            list.add(microSatisfyRankModel);
                                        }
                                    }else{
                                        list.add(microSatisfyRankModel);
                                    }
                 
                                } 
                            }
                            pageRowBounds.setTotal(new Long(list.size()));
                            lModels=getLimit(pageRowBounds, list);
                        }else{
                            
                            if(StringUtils.isNotBlank(regionId)){
                                
                                
                                if(StringUtils.isNotBlank(projectId)){
                                    for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                        if(microSatisfyRankModel.getOrganId().equals(regionId)&&projectId.equals(microSatisfyRankModel.getCommId())){
                                            list.add(microSatisfyRankModel);
                                        } 
                                    }
                                    pageRowBounds.setTotal(new Long(list.size()));
                                   lModels=getLimit(pageRowBounds, list);
                                }else{
                                    for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                        if(microSatisfyRankModel.getOrganId().equals(regionId)){
                                            list.add(microSatisfyRankModel);
                                        } 
                                    }
                                    pageRowBounds.setTotal(new Long(list.size()));
                                   lModels=getLimit(pageRowBounds, list); 
                                }
         

                        }else if(StringUtils.isNotBlank(projectId)){
                                for (MicroSatisfyRankModel microSatisfyRankModel : curr) {
                                    if(projectId.equals(microSatisfyRankModel.getCommId())){
                                        list.add(microSatisfyRankModel);
                                    } 
                                }
                                pageRowBounds.setTotal(new Long(list.size()));
                               lModels=getLimit(pageRowBounds, list);
                            }else{
                            pageRowBounds.setTotal(new Long(curr.size()));
                            
                            lModels=getLimit(pageRowBounds, curr);
                         }
               }

          
                        
                        for (MicroSatisfyRankModel cModel : lModels) {
                            Map<String,String> sMap=new HashMap<>();
                            for (String string : intervalTime) {
                                List<Map<String, String>> commList = getEffectiveProject(string,string,null,cModel.getCommId());
                                if(commList!=null&&commList.size()>0){
                                    MicroSatisfyOrganDetailModel parameter = microSatisfMapper.getProjectSatisfactionParameter(string,string,cModel.getCommId(),pageRowBounds);
                                    if(parameter!=null){
                                        String basicLevel ="";
                                        if(parameter.getQuality()==1){
                                            String userNum = parameter.getUserNum();
                                            String serviceNum = parameter.getServiceNum();
                                            String safeNum = parameter.getSafeNum();
                                            String environmentNum = parameter.getEnvironmentNum();
                                           basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                                        }else{
                                            String userNum = parameter.getUserNum();
                                            String highUserNum = parameter.getHighUserNum();
                                            basicLevel = getQualityLevel(userNum, highUserNum);
                                        }
                                        sMap.put(string, basicLevel);
                                    }
                                }  
                            }
                            
                            cModel.setMap(sMap);  
                        }
  
                    return  lModels;
                    }else{
                        return null; 
                    }
                    
                
            }
            
            
        }
        
        
          String ks = beginDate.substring(5,7);
            String js = endDate.substring(5,7);
            
            int yerInt = Integer.parseInt(beginDate.substring(0,4));
            
            List<MicroSatisfyRankModel> lastRegional=null;
            
            if(ks.equals("01")&&js.equals("03")){
                int parseInt = Integer.parseInt(beginDate.substring(0,4))-1;
                String ksDate = Integer.toString(parseInt).concat("-10-01");
                String jsDate = Integer.toString(parseInt).concat("-12-01");
                
               lastRegional= getProjectRanking(ksDate, jsDate,pageRowBounds,null,null);
               
            }else if (ks.equals("04")&&js.equals("06")) {
                String ksDate = Integer.toString(yerInt).concat("-01-01");
                String jsDate = Integer.toString(yerInt).concat("-03-01");
                
                lastRegional= getProjectRanking(ksDate, jsDate,pageRowBounds,null,null);
            }else if (ks.equals("07")&&js.equals("09")) {
                String ksDate = Integer.toString(yerInt).concat("-04-01");
                String jsDate = Integer.toString(yerInt).concat("-06-01");
                
                lastRegional= getProjectRanking(ksDate, jsDate,pageRowBounds,null,null);
            }else if (ks.equals("10")&&js.equals("12")) {
                String ksDate = Integer.toString(yerInt).concat("-07-01");
                String jsDate = Integer.toString(yerInt).concat("-09-01");
                
                lastRegional= getProjectRanking(ksDate, jsDate,pageRowBounds,null,null);
            }
            
            List<MicroSatisfyRankModel> projectRanking = getProjectRanking(beginDate, endDate,pageRowBounds,null,null);
        
            getProjectRankingShare(lastRegional, projectRanking);
            
            pageRowBounds.setTotal(new Long(projectRanking.size()));
            

            if(projectRanking!=null&&projectRanking.size()>0){
                //getCollections(projectRanking);  
                
                List<MicroSatisfyRankModel> list=new ArrayList<>();
                List<MicroSatisfyRankModel> lModels;
                if(organId!=null){
                    
                    for (MicroSatisfyRankModel microSatisfyRankModel : projectRanking) {
                        if(microSatisfyRankModel.getOrganId().equals(organId)){
                            if(StringUtils.isNotBlank(projectId)){
                                if(projectId.equals(microSatisfyRankModel.getCommId())){
                                    list.add(microSatisfyRankModel);
                                }
                            }else{
                                list.add(microSatisfyRankModel);
                            }
                        } 
                    }
                    pageRowBounds.setTotal(new Long(list.size()));
                     lModels=getLimit(pageRowBounds, list);
                    
                    return lModels;
                }
                
                
                
                
                if(StringUtils.isNotBlank(regionId)){
                    
                    
                    if(StringUtils.isNotBlank(projectId)){
                        for (MicroSatisfyRankModel microSatisfyRankModel : projectRanking) {
                            if(microSatisfyRankModel.getOrganId().equals(regionId)&&projectId.equals(microSatisfyRankModel.getCommId())){
                                list.add(microSatisfyRankModel);
                            } 
                        }
                        pageRowBounds.setTotal(new Long(list.size()));
                       lModels=getLimit(pageRowBounds, list);
                    }else{
                        for (MicroSatisfyRankModel microSatisfyRankModel : projectRanking) {
                            if(microSatisfyRankModel.getOrganId().equals(regionId)){
                                list.add(microSatisfyRankModel);
                            } 
                        }
                        pageRowBounds.setTotal(new Long(list.size()));
                       lModels=getLimit(pageRowBounds, list); 
                    }


            }else if(StringUtils.isNotBlank(projectId)){
                    for (MicroSatisfyRankModel microSatisfyRankModel : projectRanking) {
                        if(projectId.equals(microSatisfyRankModel.getCommId())){
                            list.add(microSatisfyRankModel);
                        } 
                    }
                    pageRowBounds.setTotal(new Long(list.size()));
                   lModels=getLimit(pageRowBounds, list);
                }else{
                pageRowBounds.setTotal(new Long(projectRanking.size()));
                lModels= getLimit(pageRowBounds, projectRanking);
             }

            return  lModels;
            }else{
                return null; 
            }

    }


    private void getOrganCollections(List<MicroSatisfyRankModel> curr) {
        Collections.sort(curr, new Comparator<MicroSatisfyRankModel>() {  

            @Override  
            public int compare(MicroSatisfyRankModel o1, MicroSatisfyRankModel o2) {
               if (o1.getOrganRank() > o2.getOrganRank()) {  
                   return 1;  
               }  
               if (o1.getOrganRank() == o2.getOrganRank()) {  
                   return 0;  
               }  
               return -1;    
            }  
        });
    }
    
    
    private void getCollections(List<MicroSatisfyRankModel> curr) {
        Collections.sort(curr, new Comparator<MicroSatisfyRankModel>() {  

            @Override  
            public int compare(MicroSatisfyRankModel o1, MicroSatisfyRankModel o2) {  
                if (o1.getRankCurMon() > o2.getRankCurMon()) {  
                    return 1;  
                }  
                if (o1.getRankCurMon() == o2.getRankCurMon()) {  
                    return 0;  
                }  
                return -1;  
            }  
        });
    }

    private void getProjectRankingShare(List<MicroSatisfyRankModel> lastRegional,
            List<MicroSatisfyRankModel> projectRanking) {
        if((projectRanking!=null&&projectRanking.size()>0)&&(lastRegional!=null&&lastRegional.size()>0)){
            for (MicroSatisfyRankModel microSatisfyRankModel : projectRanking) {
                
                
                for (MicroSatisfyRankModel lModel : lastRegional) {
                    if(microSatisfyRankModel.getCommId().equals(lModel.getCommId())){
                        int rankCurMon = microSatisfyRankModel.getRankCurMon();
                        int lastRankCurMon = lModel.getRankCurMon();
                        
                        String curSatisfy = microSatisfyRankModel.getSatisfy().toString();
                        String lastSatisfy = lModel.getSatisfy().toString();
                        if(curSatisfy.equals("0.00")||lastSatisfy.equals("0.00")){
                            System.out.println(curSatisfy+"      "+lastSatisfy);
                        }
                        
                            Map<String, Object> rankings = getRankings(lastSatisfy,curSatisfy,rankCurMon,lastRankCurMon);
                            
                            microSatisfyRankModel.setRankLastMon(lastRankCurMon);
                            microSatisfyRankModel.setMonthUp(String.valueOf(rankings.get("monthlyPromotion")));
                            microSatisfyRankModel.setRankChange(String.valueOf(rankings.get("rankingsChange")));
                       

                    }
                }
            }
        }
    }

    private List<MicroSatisfyRankModel> getProjectRanking(String beginDate, String endDate,PageRowBounds pageRowBounds,String organId,List<Map<String, String>> effectiveProject) {
        List<MicroSatisfyOrganDetailModel> queryPublicProject = microSatisfMapper.queryPublicProject(beginDate,endDate,"1",organId,effectiveProject);
        List<MicroSatisfyOrganDetailModel> publicProject = microSatisfMapper.queryPublicProject(beginDate,endDate,"2",organId,effectiveProject);

        List<MicroSatisfyRankModel> lModels=new ArrayList<>();
        
        if(queryPublicProject!=null&&queryPublicProject.size()>0){
            for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : queryPublicProject) {
                String userNum = microSatisfyOrganDetailModel.getUserNum();
                String serviceNum = microSatisfyOrganDetailModel.getServiceNum();
                String safeNum = microSatisfyOrganDetailModel.getSafeNum();
                String environmentNum = microSatisfyOrganDetailModel.getEnvironmentNum();
                String basicLevel ="0";
                String commId = microSatisfyOrganDetailModel.getCommId();
                if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        basicLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                    basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                }
                
                String score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), basicLevel);
                
                MicroSatisfyRankModel microSatisfyRankModel=new MicroSatisfyRankModel();
                microSatisfyRankModel.setCommScore(score);
                microSatisfyRankModel.setSatisfy(new Double(basicLevel));
                microSatisfyRankModel.setCommId(commId);
                microSatisfyRankModel.setOrganId(microSatisfyOrganDetailModel.getOrganId());
                microSatisfyRankModel.setCommName(microSatisfyOrganDetailModel.getCommName());
                microSatisfyRankModel.setOrganName(microSatisfyOrganDetailModel.getOrganName());
                
                lModels.add(microSatisfyRankModel);
            }
        }
        
          if(publicProject!=null&&publicProject.size()>0){
              for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : publicProject) {
                  String userNum = microSatisfyOrganDetailModel.getUserNum();
                    String highUserNum = microSatisfyOrganDetailModel.getHighUserNum();
                    String qualityLevel ="0";
                    String commId = microSatisfyOrganDetailModel.getCommId();
                    if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                        MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                        if(microSatisfyPointModel!=null){
                            qualityLevel=microSatisfyPointModel.getBasePoint();
                        }
                       
                    }else{
                        qualityLevel = getQualityLevel(userNum, highUserNum);
                    }
                    
                    
                    String score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), qualityLevel);
                    
                    MicroSatisfyRankModel microSatisfyRankModel=new MicroSatisfyRankModel();
                    microSatisfyRankModel.setCommScore(score);
                    microSatisfyRankModel.setSatisfy(new Double(qualityLevel));
                    microSatisfyRankModel.setCommId(commId);
                    microSatisfyRankModel.setOrganId(microSatisfyOrganDetailModel.getOrganId());
                    microSatisfyRankModel.setCommName(microSatisfyOrganDetailModel.getCommName());
                    microSatisfyRankModel.setOrganName(microSatisfyOrganDetailModel.getOrganName());
                    
                    lModels.add(microSatisfyRankModel);
                }
            }
          
          List<MicroSatisfyRankModel> collect2 = lModels.stream().sorted(Comparator.comparing(MicroSatisfyRankModel::getSatisfy).reversed()).collect(Collectors.toList());
          int i=0;
          Double satisfy=new Double(0);
          for (MicroSatisfyRankModel microSatisfyRankModel4 : collect2) {
              if(satisfy.equals(microSatisfyRankModel4.getSatisfy())){
                  microSatisfyRankModel4.setRankCurMon(i);
              }else{
                  microSatisfyRankModel4.setRankCurMon(++i);
              }
              satisfy=microSatisfyRankModel4.getSatisfy();
          }
        return collect2;
    }

    /**
     * @描述 查询区域项目满意度基本信息
     * @作者 张世通
     * @时间 2018年6月26日
     * @version 
     * @param pageRowBounds
     * @return
     */
    @Override
    public List<MicroSatisfyOrganDetailModel> queryOrganSatisfyDetail(String timeStr,String userCode,String pid) {
        List<DupOrgan> commResult = dupCommService.listAllComm();
        List<MicroSatisfyOrganDetailModel> detail = microSatisfMapper.queryOrganSatisfyDetail(timeStr,pid);
        if(null != detail && detail.size()>0){
            for(MicroSatisfyOrganDetailModel item:detail){
                //常驻人数
                String permanentNum = item.getPermanentNum();
                //样本量
                String userNum = item.getUserNum();
                
                 BigDecimal safe = new BigDecimal(item.getEffectiveNum()).
                            multiply(new BigDecimal("0.30")).setScale(0,BigDecimal.ROUND_HALF_UP) ;
                
                 int value = safe.intValue();
                int i = Integer.parseInt(userNum);
                if(i>=value){
                 
                //常驻率
                String permanent = new BigDecimal(permanentNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                item.setPermanent(permanent);
                item.setMonth(timeStr);
                item.setCreatedBy(userCode);
                item.setPid(pid);
                
                //判断品品质级与基础级
                if(null != commResult && commResult.size()>0){
                    //默认判断为基础级项目
                    boolean flag = false;
                    for(DupOrgan itemOrgan : commResult){
                        if(itemOrgan.getOrganCode().equals(item.getOrganId())){
                            List<DupComm> commList = itemOrgan.getComms();
                            if(null != commList && commList.size()>0){
                                for(DupComm itemComm: commList){
                                    if(itemComm.getCommId().equals(item.getCommId())){
                                        //top3 4-5 品质满意度
                                        String highUserNum = item.getHighUserNum();
                                        String topThree = new BigDecimal(highUserNum)
                                                .divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                                                .multiply(new BigDecimal("100")).toString();
                                        item.setTopThree(topThree);
                                        //品质级项目
                                        flag = true;
                                    }
                                }
                            }
                            break;
                        }
                    }
                    if(!flag){
                        //基础级项目
                        /*整体满意度(B2)=F1*W1+F2*W2+F3*W3
                        安全管理满意度(F1)=季度安全管理满意人次/季度有效样本量
                        环境卫生满意度(F2)=季度环境卫生满意人次/季度有效样本量
                        服务态度满意度(F3)=季度服务态度满意人次/季度有效样本量
                        安全管理权重(W1)=0.35
                        环境卫生权重(W2)=0.30
                        服务态度权重(W3)=0.35*/
                        //安全满意度人数
                        String safeNum = item.getSafeNum();
                        //环境满意度人数
                        String environmentNum = item.getEnvironmentNum();
                        //服务卫生满意度人数
                        String serviceNum = item.getServiceNum();
                        //安全满意度
                        BigDecimal safePercent = new BigDecimal(safeNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                                .setScale(2, BigDecimal.ROUND_HALF_UP);
                        //环境满意度
                        BigDecimal environmentPercent = new BigDecimal(environmentNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal("0.30")).multiply(new BigDecimal("100"))
                                .setScale(2, BigDecimal.ROUND_HALF_UP);
                        //服务卫生满意度
                        BigDecimal servicePercent = new BigDecimal(serviceNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                                .setScale(2, BigDecimal.ROUND_HALF_UP);
                        //总体加权满意度top2
                        String totalSatisfy = safePercent.add(environmentPercent).add(servicePercent).toString();
                        item.setTopTwo(totalSatisfy);
                    }
                    
                }else{
                    //top2 3-5 基础加权满意度
                    //安全满意度人数
                    String safeNum = item.getSafeNum();
                    //环境满意度人数
                    String environmentNum = item.getEnvironmentNum();
                    //服务卫生满意度人数
                    String serviceNum = item.getServiceNum();
                    //安全满意度
                    BigDecimal safePercent = new BigDecimal(safeNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);
                    //环境满意度
                    BigDecimal environmentPercent = new BigDecimal(environmentNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal("0.30")).multiply(new BigDecimal("100"))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);
                    //服务卫生满意度
                    BigDecimal servicePercent = new BigDecimal(serviceNum).divide(new BigDecimal(userNum),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);
                    //总体加权满意度top2
                    String totalSatisfy = safePercent.add(environmentPercent).add(servicePercent).toString();
                    item.setTopTwo(totalSatisfy);
                }
            }
            microSatisfMapper.insertOrganCommDetail(detail);
            }
        }
        return detail;
    }
    /**
     * @描述 豁免并锁定
     * @作者 张世通
     * @时间 2018年6月26日
     * @version 
     * @param list
     */
    @Override
    public void updateOragnCommDetail(List<Map<String, Object>> list,String userCode,String falg) {
        if("1".equals(falg)){
            microSatisfMapper.updateIsAssessmentComm(list,userCode);
        }else{
            microSatisfMapper.updateOragnCommDetail(list,userCode);
        } 
    }
    /**
     * @描述 根据organId 查询区域详情信息
     * @作者 张世通
     * @时间 2018年6月26日
     * @version 
     * @param pageRowBounds
     * @param organId
     * @param timeStr
     * @return
     */
    @Override
    public List<MicroSatisfyOrganDetailModel> queryOrganSatisfyDetailByOrganId(PageRowBounds pageRowBounds,
            String organId, String beginDate,String endDate) {

        List<MicroSatisfyOrganDetailModel> analysis = microSatisfMapper.queryRegionalAnalysis(beginDate,endDate,organId,pageRowBounds,null);
        for (MicroSatisfyOrganDetailModel aModel : analysis) {
            if(aModel.getQuality()==1){
                String userNum = aModel.getUserNum();
                String serviceNum = aModel.getServiceNum();
                String safeNum = aModel.getSafeNum();
                String environmentNum = aModel.getEnvironmentNum();
                String basicLevel="0";
                if("1".equals(aModel.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(aModel.getCommId());
                    if(microSatisfyPointModel!=null){
                        basicLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                     basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                }
   
                aModel.setTopTwoAndThree(basicLevel);
            }else{
                String userNum = aModel.getUserNum();
                String highUserNum = aModel.getHighUserNum();
                String qualityLevel ="0";
                if("1".equals(aModel.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(aModel.getCommId());
                    if(microSatisfyPointModel!=null){
                        qualityLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                     qualityLevel = getQualityLevel(userNum, highUserNum);
                }

                aModel.setTopTwoAndThree(qualityLevel);
            }

            Map<String,String> map=new HashMap<>();
            map.put("beginDate",endDate);
            map.put("endDate",endDate);
            map.put("organId",aModel.getOrganId());
            map.put("commId",aModel.getCommId());
            
            Map<String, String> managerData = findManagerData(map);
            if(managerData!=null&&managerData.size()>0){                       
                aModel.setManagerAwarenessRate(String.valueOf(managerData.get("avgRecognitionPercentage")));
                aModel.setManagerSatisfactionRate(String.valueOf(managerData.get("avgSatisfaction")));
            }

        }

        return analysis;
    }
    
    //项目分析
    public MicroSatisfyOrganDetailModel querySatisfyDetailByCommId(String organId,String commId, String beginDate,String endDate) {
        MicroSatisfyOrganDetailModel analysis = microSatisfMapper.querySatisfyDetailByCommId(beginDate,endDate,organId,commId);
     
        if(analysis!=null){
            if(analysis.getQuality()==1){
                String userNum = analysis.getUserNum();
                String serviceNum = analysis.getServiceNum();
                String safeNum = analysis.getSafeNum();
                String environmentNum = analysis.getEnvironmentNum();
                String basicLevel ="0";
                if("1".equals(analysis.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        basicLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                    basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                }
                analysis.setTopTwoAndThree(basicLevel);
            }else{
                String userNum = analysis.getUserNum();
                String highUserNum = analysis.getHighUserNum();
                String qualityLevel = "0";
                if("1".equals(analysis.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        qualityLevel=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                    qualityLevel = getQualityLevel(userNum, highUserNum);
                }
                analysis.setTopTwoAndThree(qualityLevel);
            }

            Map<String,String> map=new HashMap<>();
            map.put("beginDate",endDate);
            map.put("endDate",endDate);
            map.put("organId",analysis.getOrganId());
            map.put("commId",analysis.getCommId());
            
            Map<String, String> managerData = findManagerData(map);
            if(managerData!=null&&managerData.size()>0){                       
                analysis.setManagerAwarenessRate(String.valueOf(managerData.get("avgRecognitionPercentage")));
                analysis.setManagerSatisfactionRate(String.valueOf(managerData.get("avgSatisfaction")));
            }
        }
        return analysis;
    }
    
    public int getDate(String beginDate,String endDate) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(beginDate));
        aft.setTime(sdf.parse(endDate));
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
       return Math.abs(month + result);   
    }
    
    
    
    /**
     * @描述 查询项目详情
     * @作者 张世通
     * @时间 2018年6月28日
     * @version 
     * @param organId
     * @param commId
     * @param timeStr
     * @param pid
     * @return
     */
    @Override
    public MicroSatisfyOrganDetailModel queryCommDetail(String organId, String commId, String timeStr,
            String pid) {
        return microSatisfMapper.queryCommDetail(organId, timeStr, commId, pid);
    }


    /**
     * @描述 查询当月批次统计信息
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @return
     */
    @Override
    public Map<String, Object> queryDataCount(String beginDate,String endDate,String flag,String organId) {
           //Map<String,Object> map=new HashMap<>();
            
           Map<String, Object> count = microSatisfMapper.queryDataCount(beginDate,endDate,organId);
           
           List<Map<String, String>> effectiveProject = new ArrayList<>();

               if(beginDate.equals(endDate)){
                   effectiveProject = getOrganEffectiveProject(beginDate, endDate, organId,null);
                   if(effectiveProject!=null&&effectiveProject.size()>0){

                       BigDecimal bigDecimal = getWholeCountrySatisfaction(beginDate, endDate, organId,
                            effectiveProject);
                         //折线图的   要 先算项目 再算区域，后面 再通过区域 得出 全国
                       if(count!=null&&count.size()>0){
                           count.put("satisfaction",bigDecimal.toString());
                       }

                    return count;
                   }
                   return null;
               }else{
                   BigDecimal bigDecimal = getWholeCountrySatisfaction(beginDate, endDate, organId,
                           effectiveProject);
               if(count!=null&&count.size()>0){
                   count.put("satisfaction",bigDecimal.toString());
               }

            return count;
           }
           
      
    }



    private BigDecimal getWholeCountrySatisfaction(String beginDate, String endDate, String organId,
            List<Map<String, String>> effectiveProject) {
        Map<String, List<MicroSatisfyRankModel>> oMap =
                   gettingGroupedData(beginDate, endDate, organId, effectiveProject);

           BigDecimal bigDecimal = new BigDecimal(0);
             //根据区域 分组 并且计算出  区域 满意度 得分
             for(String key:oMap.keySet()){
                 List<MicroSatisfyRankModel> list = oMap.get(key);
                 //DoubleSummaryStatistics collect2 = list.stream().collect(Collectors.summarizingDouble(MicroSatisfyRankModel::getSatisfy));
                 Double colxxlect =list.stream().collect(Collectors.averagingDouble(MicroSatisfyRankModel::getSatisfy));
                 bigDecimal=bigDecimal.add(new BigDecimal(colxxlect));
             }
             if(oMap.size()>0){
                 bigDecimal = bigDecimal.divide(new BigDecimal(oMap.size()),2,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);  
             }
        return bigDecimal;
    }
    
    
    //区域统计
       public Map<String, Object> queryRegionCount(String beginDate,String endDate,String flag,String organId) {
           Map<String, Object> count = microSatisfMapper.queryDataCount(beginDate,endDate,organId); 
           
           List<Map<String, String>> effectiveProject = getOrganEffectiveProject(beginDate, endDate, organId,null);
           
           Map<String, List<MicroSatisfyRankModel>> oMap =
                   gettingGroupedData(beginDate, endDate, organId, effectiveProject);

             List<MicroSatisfyRankModel> cList=new ArrayList<>();
             //根据区域 分组 并且计算出  区域 满意度 得分
             for(String key:oMap.keySet()){
                 List<MicroSatisfyRankModel> list = oMap.get(key);
               //区域满意度
                 Double colxxlect =list.stream().collect(Collectors.averagingDouble(MicroSatisfyRankModel::getSatisfy));
                 BigDecimal setScale = new BigDecimal(colxxlect).setScale(2,BigDecimal.ROUND_HALF_UP);
                 //Map<String, String> collect2 = list.stream().filter(m-> key.equals(m.getOrganId())).collect(Collectors.toMap(MicroSatisfyRankModel::getOrganId, MicroSatisfyRankModel::getOrganName));
                 List<MicroSatisfyRankModel> dList=list.stream().filter(m-> key.equals(m.getOrganId())).collect(Collectors.toList());
                 String organName=dList.size()>0?dList.get(0).getOrganName():"";
                 MicroSatisfyRankModel model=new MicroSatisfyRankModel();
                 model.setSatisfy(setScale.doubleValue());
                 model.setOrganId(key);
                 model.setOrganName(organName);
 
                 cList.add(model);
             }
             List<MicroSatisfyRankModel> collect2 = cList.stream().sorted(Comparator.comparing(MicroSatisfyRankModel::getSatisfy).reversed()).collect(Collectors.toList());
             int i=0;
             Double satisfy=new Double(0);
             for (MicroSatisfyRankModel microSatisfyRankModel4 : collect2) {
                 if(satisfy.equals(microSatisfyRankModel4.getSatisfy())){
                     microSatisfyRankModel4.setOrganRank(i);
                 }else{
                     microSatisfyRankModel4.setOrganRank(++i);
                 }
                 satisfy=microSatisfyRankModel4.getSatisfy();
             }

           for (MicroSatisfyRankModel microSatisfyOrganDetailModel : collect2) {
               if(organId.equals(microSatisfyOrganDetailModel.getOrganId())){
                   
                   if(count!=null&&count.size()>0){
                       count.put("organName",microSatisfyOrganDetailModel.getOrganName());
                       count.put("nationalRankings",microSatisfyOrganDetailModel.getOrganRank());
                       List<String> iList=new ArrayList<>();
                       iList.add(organId);
                       List<TbHSPRRegionAvatarInfo> organList = tbHSPRRegionAvatarInfoMapper.selectOrganList(iList);
                       if(organList!=null&&organList.size()>0){
                           count.put("names",organList.get(0).getNames());
                       }

                       count.put("satisfaction",microSatisfyOrganDetailModel.getSatisfy());
                   }
                   break;
               }
           }
        return count;
    }
    
    
    /**
     * @描述 查询区域批次统计信息
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @return
     */
    @Override
    public Map<String, Object> queryOrganCount(String timeStr, String organId,String pid) {
        return microSatisfMapper.queryOrganCount(timeStr, organId,pid);
    }
    /**
     * @描述 查询项目批次统计信息
     * @作者 张世通
     * @时间 2018年6月28日
     * @version 
     * @param timeStr
     * @param organId
     * @param commId
     * @param pid
     * @return
     */
    @Override
    public Map<String, Object> queryCommCount(String beginDate,String endDate, String organId, String commId) {

        List<MicroSatisfyOrganDetailModel> project = microSatisfMapper.queryPublicProject(beginDate,endDate,null,null,null);
        
        Map<String, Object> hMap =new HashMap<>();
    
           if(project!=null&&project.size()>0){
               for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : project) {
                   if(microSatisfyOrganDetailModel.getQuality()==1){
                       String userNum = microSatisfyOrganDetailModel.getUserNum();
                       String serviceNum = microSatisfyOrganDetailModel.getServiceNum();
                       String safeNum = microSatisfyOrganDetailModel.getSafeNum();
                       String environmentNum = microSatisfyOrganDetailModel.getEnvironmentNum();
                       
                       String  basicLevel = "0";
                       if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                           MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                           if(microSatisfyPointModel!=null){
                               basicLevel=microSatisfyPointModel.getBasePoint();
                           }
                          
                       }else{
                           basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                       }

                       String score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), basicLevel);
                       microSatisfyOrganDetailModel.setTopTwoAndThree(basicLevel);
                       microSatisfyOrganDetailModel.setN2(score);
                   }else{
                       String userNum = microSatisfyOrganDetailModel.getUserNum();
                       String highUserNum = microSatisfyOrganDetailModel.getHighUserNum();
                       String qualityLevel ="0";
                       if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                           MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                           if(microSatisfyPointModel!=null){
                               qualityLevel=microSatisfyPointModel.getBasePoint();
                           }
                          
                       }else{
                           qualityLevel = getQualityLevel(userNum, highUserNum);
                       }

                       String score = getAssessmentScore(null,microSatisfyOrganDetailModel.getCommId(), qualityLevel);
                       microSatisfyOrganDetailModel.setTopTwoAndThree(qualityLevel);
                       microSatisfyOrganDetailModel.setN2(score);
                   }
               }

               List<String> collect = project.stream().map(MicroSatisfyOrganDetailModel::getTopTwoAndThree).collect(Collectors.toList());
             
               Map<String, Object> map = getRanking(collect); 

               for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : project) {
                   if(organId.equals(microSatisfyOrganDetailModel.getOrganId())&&commId.equals(microSatisfyOrganDetailModel.getCommId())){
                       hMap.put("importTime",microSatisfyOrganDetailModel.getCreateDate());
                       hMap.put("commName",microSatisfyOrganDetailModel.getCommName());
                       hMap.put("nationalRankings",getMapToString(map.get(microSatisfyOrganDetailModel.getTopTwoAndThree())));
                       hMap.put("names",tbSysUserMapper.queryRegionAvatarInfoName(microSatisfyOrganDetailModel.getCommId()));
                       hMap.put("satisfaction",microSatisfyOrganDetailModel.getTopTwoAndThree());
                       break;
                   }
               }
               
           }
    
        return hMap;
        
    }
    
    //传入分数进行排名
    public Map<String,Object> getRanking(List<String> satisfactions){
        String[] array = new String[satisfactions.size()];

        satisfactions.toArray(array);

        String t="";
        for (int i = 0; i < array.length - 1; i++){
            for (int j = 0; j < array.length-1-i;j++){
                if (Double.parseDouble(array[j])< Double.parseDouble(array[j+1])) {
                   
                  // Double.parseDouble(array[j])
                    t=array[j];
                    
                    array[j]=array[j+1];
                    array[j+1]=t;
                   
                }
            }
        }
        
        
        
        Map<String,Object> map=new HashMap<>();
        String flag="";
        int i=0;
        for (String satisfaction : array) {
            if(!satisfaction.equals(flag)){
                i++;
                map.put(satisfaction, i);  
            }
            flag=satisfaction;
        }
        return map;
    }
    
    /**
     * @描述 查询全国走势图
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @param timeStr
     * @return
     */
    @Override
    public Map<String, Object> queryCountryScore(String beginDate,String endDate,String flag,String organId) {
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM");
        
        Map<String,Object> map=new HashMap<>();
        if(flag.equals("monthly")){
            List<String> intervalTime =new ArrayList<>();
            if(beginDate.equals(endDate)){
                intervalTime.add(beginDate);
            }else{
                intervalTime = getIntervalTime(beginDate,endDate);
            }
            
            
            for (String string : intervalTime) {
                List<Map<String, String>> effectiveProject = getOrganEffectiveProject(string, string, organId,null);
                   
                if(effectiveProject!=null&&effectiveProject.size()>0){
                    BigDecimal bigDecimal = getWholeCountrySatisfaction(string, string, organId,
                            effectiveProject);
               
                    try {
                      Date  format = formatDate.parse(string);
                      String   format2 = formatDate.format(format);
                         
                         map.put(format2,bigDecimal.toString()); 
                    } catch (ParseException e) {
                          
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                        
                    }
                }
  
            }
            return map;
        }

        ArrayList<Entry<String, String>> list = getList(beginDate.substring(0,4));

        int i=1;
        for (Entry<String, String> entry : list) {
            List<Map<String, String>> effectiveProject = getOrganEffectiveProject(entry.getKey(),entry.getValue(),organId,null);
            BigDecimal bigDecimal = getWholeCountrySatisfaction(entry.getKey(),entry.getValue(), organId,
                    effectiveProject);
    
           map.put("第"+i+"季度", bigDecimal.toString());
           i++;
        }
        return map;
    }

    private Map<String, Object> getMonthlySatisfaction(String beginDate, String endDate,
            Map<String, Object> map,String organId) {
        List<MicroSatisfyOrganDetailModel> queryCountryScore = microSatisfMapper.queryCountryScore(beginDate,endDate,"1",organId);
        List<MicroSatisfyOrganDetailModel> countryScore = microSatisfMapper.queryCountryScore(beginDate,endDate,"2",organId);
        
        
        List<String> notList = new ArrayList<>();
        
        if(countryScore!=null&&countryScore.size()>0){
            for (MicroSatisfyOrganDetailModel mDetailModel : countryScore) {
                if(mDetailModel!=null){
                    String userNum = mDetailModel.getUserNum();
                    String highUserNum = mDetailModel.getHighUserNum();
                    String qualityLevel = getQualityLevel(userNum, highUserNum);
                    mDetailModel.setTopThree(qualityLevel);
                }
            }
        }
        
           if(queryCountryScore!=null&&queryCountryScore.size()>0){
               for (MicroSatisfyOrganDetailModel mDetailModel : queryCountryScore) {
                    if(mDetailModel!=null){
                        String userNum = mDetailModel.getUserNum();
                        String safeNum = mDetailModel.getSafeNum();
                        String environmentNum = mDetailModel.getEnvironmentNum();
                        String serviceNum = mDetailModel.getServiceNum();
                        String basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                        mDetailModel.setTopTwoAndThree(basicLevel);
                        

                    }
                }
            }
           
           //List<MicroSatisfyOrganDetailModel> lDetailModels=new ArrayList<>();
           if((countryScore!=null&&countryScore.size()>0)&&(queryCountryScore!=null&&queryCountryScore.size()>0)){
               for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : countryScore) {
                   
                   int i=0;
                   for (MicroSatisfyOrganDetailModel mDetailModel : queryCountryScore) {
                       
                       //MicroSatisfyRankModel microSatisfyRankModel =new MicroSatisfyRankModel();
                       
                       if(microSatisfyOrganDetailModel.getMonth().equals(mDetailModel.getMonth())){
                        
                          // BigDecimal bigDecimal = new BigDecimal(microSatisfyOrganDetailModel.getCommNum()).add(new BigDecimal(mDetailModel.getCommNum()));
                           
                           
                       String  average = new BigDecimal(microSatisfyOrganDetailModel.getTopThree()).add(new BigDecimal(mDetailModel.getTopTwoAndThree()))
                        .divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP).toString();
              
                       mDetailModel.setTopTwoAndThree(average);

                       i++;
                     break;
                    }
                       

                }
                   if(i==0){
                       notList.add(microSatisfyOrganDetailModel.getMonth());
                   }else{
                      i=0; 
                   }
                  // models.add(microSatisfyRankModel);
            }
               
               if(notList!=null&&notList.size()>0){
                 
                       for (String moth : notList) {
                          // MicroSatisfyRankModel microSatisfyRankModel =new MicroSatisfyRankModel();
                           MicroSatisfyOrganDetailModel model=new MicroSatisfyOrganDetailModel();
                           
                           for (MicroSatisfyOrganDetailModel mDetailModel : countryScore) {
                              
                               
                               if(mDetailModel.getMonth().equals(moth)){
                                   model.setMonth(mDetailModel.getMonth());
                                   model.setTopTwoAndThree(mDetailModel.getTopThree());
                                 break;
                                }
                           }
                          // models.add(microSatisfyRankModel);
                           queryCountryScore.add(model);
                    }
                
               }
              
               for (MicroSatisfyOrganDetailModel mDetailModel : queryCountryScore) {
                map.put(mDetailModel.getMonth(), mDetailModel.getTopTwoAndThree());
            }
               return map;
   }else{
        
        if(countryScore!=null&&countryScore.size()>0){
            for (MicroSatisfyOrganDetailModel mDetailModel : countryScore) {
                if(mDetailModel!=null){
                    String userNum = mDetailModel.getUserNum();
                    String highUserNum = mDetailModel.getHighUserNum();
                    String qualityLevel = getQualityLevel(userNum, highUserNum);
                   
                    map.put(mDetailModel.getMonth(), qualityLevel);
                }
            }
        }
        
           if(queryCountryScore!=null&&queryCountryScore.size()>0){
               for (MicroSatisfyOrganDetailModel mDetailModel : queryCountryScore) {
                    if(mDetailModel!=null){
                        String userNum = mDetailModel.getUserNum();
                        String safeNum = mDetailModel.getSafeNum();
                        String environmentNum = mDetailModel.getEnvironmentNum();
                        String serviceNum = mDetailModel.getServiceNum();
                        String basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                        
                        map.put(mDetailModel.getMonth(), basicLevel);
                    }
                }
            }
           
           return map;
   }
    }

    private ArrayList<Entry<String, String>> getList(String timeStr) {
        TreeMap<String, String> daMap = new TreeMap<>();
          daMap.put(getConcat(timeStr.concat("-01")), getConcat(timeStr.concat("-03")));
            daMap.put(getConcat(timeStr.concat("-04")), getConcat(timeStr.concat("-06")));
            daMap.put(getConcat(timeStr.concat("-07")), getConcat(timeStr.concat("-09")));
            daMap.put(getConcat(timeStr.concat("-10")), getConcat(timeStr.concat("-12")));
        
         ArrayList<Entry<String, String>> list =
                 new ArrayList<Map.Entry<String, String>>(daMap.entrySet());
  
         Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
             @Override
             public int compare(Entry<String, String> o1,
                                Entry<String, String> o2) {
                 return o1.getValue().compareTo(o2.getValue());//顺序
             }
         });
        return list;
    }
    

    
    public String getConcat(String concat){
        return concat.concat("-01");
    }

    private String getSatisfaction(String beginDate,String endDate,String timeStr,String organId) {
       
        Map<String, Object> quality =null;
        Map<String, Object> Basics =null;
        if(beginDate!=null&&endDate!=null){
            quality = microSatisfMapper.queryCountryQuarterScore(beginDate,endDate,"2",organId);
            
            Basics = microSatisfMapper.queryCountryQuarterScore(beginDate,endDate,"1",organId);
        }
        
/*        else{
            quality = microSatisfMapper.queryCountryNationwideScore(timeStr,"y");
            
            Basics = microSatisfMapper.queryCountryNationwideScore(timeStr,null);
        }
*/
        
        String topThree ="";
        
        if(quality!=null&&quality.size()>0){
                String permanentNum = getMapToString(quality.get("userNum"));
                
                String highUserNum = getMapToString(quality.get("highUserNum"));
                
                
                topThree = getQualityLevel(permanentNum, highUserNum);
        }
        String totalSatisfy ="";
        if(Basics!=null&&Basics.size()>0){
            String permanentNum = getMapToString(Basics.get("userNum"));
            
            String safeNum = getMapToString(Basics.get("safeNum"));
            String serviceNum = getMapToString(Basics.get("serviceNum"));
            String environmentNum = getMapToString(Basics.get("environmentNum"));
            
               totalSatisfy = getBasicLevel(permanentNum, safeNum, serviceNum, environmentNum);
        }

        if(topThree!=""&&totalSatisfy!=""){
            //String commNum = getMapToString(quality.get("commNum"));
            //String bCommNum = getMapToString(Basics.get("commNum"));

            //BigDecimal bigDecimal = new BigDecimal(commNum).add(new BigDecimal(bCommNum));
            
            
        String  average = new BigDecimal(topThree).add(new BigDecimal(totalSatisfy))
         .divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP).toString();
              
           return average;
        }
        String rvZeroAndDot = rvZeroAndDot(topThree+totalSatisfy);
        logger.info("---去除小数之后的值--"+rvZeroAndDot);
        return rvZeroAndDot;
    }
    
    public static String rvZeroAndDot(String s){  
        if (s.isEmpty()) {
   return null;
      }
        if(s.indexOf(".") > 0){  
        s = s.replaceAll("0+?$", "");//去掉多余的0  
        s = s.replaceAll("[.]$", "");//如最后一位是.则去掉  
        }  
       return s;  
  }  

    private String getQualityLevel(String permanentNum, String highUserNum) {
        String topThree;
        topThree = new BigDecimal(highUserNum)
        .divide(new BigDecimal(permanentNum),4,BigDecimal.ROUND_HALF_UP)
        .multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        return topThree;
    }

    private String getBasicLevel(String permanentNum, String safeNum, String serviceNum,
            String environmentNum) {
        String totalSatisfy;
        //安全满意度
        BigDecimal safePercent = new BigDecimal(safeNum).divide(new BigDecimal(permanentNum),4,BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        //环境满意度
        BigDecimal environmentPercent = new BigDecimal(environmentNum).divide(new BigDecimal(permanentNum),4,BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal("0.30")).multiply(new BigDecimal("100"))
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        //服务卫生满意度
        BigDecimal servicePercent = new BigDecimal(serviceNum).divide(new BigDecimal(permanentNum),4,BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal("0.35")).multiply(new BigDecimal("100"))
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        //总体加权满意度top2
        totalSatisfy = safePercent.add(environmentPercent).add(servicePercent).toString();
        return totalSatisfy;
    }
    public String getMapToString(Object object){
        if(object!=null){
            return object.toString();
        }
        return "";
    }
    
    
    /**
     * @描述 查询区域走势图
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @param timeStr
     * @return
     */
    @Override
    public Map<String, Object> queryOrganScore(String timeStr, String organId,String pid) {
        return microSatisfMapper.queryOrganScore(timeStr, organId,pid);
    }
    /**
     * @描述 查询项目走势图
     * @作者 张世通
     * @时间 2018年6月28日
     * @版本 
     * @param timeStr
     * @return
     */
    public Map<String, Object> queryCommScore(String beginDate,String endDate, String organId, String commId,String flag) {
        Map<String,Object> map=new HashMap<>();
        if(flag.equals("monthly")){
            
       
            List<MicroSatisfyOrganDetailModel> queryCommScore = microSatisfMapper.queryCommScore(beginDate,endDate,organId,commId);
            
            for (MicroSatisfyOrganDetailModel microSatisfyOrganDetailModel : queryCommScore) {
                String basicLevel ="0";
                if(microSatisfyOrganDetailModel.getQuality()==1){
                
                        String userNum = microSatisfyOrganDetailModel.getUserNum();
                        String serviceNum = microSatisfyOrganDetailModel.getServiceNum();
                        String safeNum = microSatisfyOrganDetailModel.getSafeNum();
                        String environmentNum = microSatisfyOrganDetailModel.getEnvironmentNum();
                         
                        if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                            MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                            if(microSatisfyPointModel!=null){
                                basicLevel=microSatisfyPointModel.getBasePoint();
                            }
                           
                        }else{
                            basicLevel = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                        }  
                }else{
                    String userNum = microSatisfyOrganDetailModel.getUserNum();
                    String highUserNum = microSatisfyOrganDetailModel.getHighUserNum();
                    
                    if("1".equals(microSatisfyOrganDetailModel.getIfLocking())){
                        MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                        if(microSatisfyPointModel!=null){
                            basicLevel=microSatisfyPointModel.getBasePoint();
                        }
                       
                    }else{
                        basicLevel= getQualityLevel(userNum, highUserNum);
                    }  
                }
                map.put(microSatisfyOrganDetailModel.getMonth(),basicLevel) ;
            }
            
           return map; 
            
        }
        
        ArrayList<Entry<String, String>> list = getList(beginDate.substring(0,4));
        
        
        int i=1;
        for (Entry<String, String> entry : list) {
            String servicePercent = getProjectSatisfaction(entry.getKey(),entry.getValue(),organId, commId);
           map.put("第"+i+"季度", servicePercent);
           i++;
        }
        
        
        return map;
    }

    private String getProjectSatisfaction(String beginDate,String endDate,String organId,String commId) {
        
        Map<String, Object> queryProjectScore = microSatisfMapper.queryProjectScore(beginDate,endDate, organId, commId);
        if(queryProjectScore!=null&&queryProjectScore.size()>0){
            
              
              String quality = getMapToString(queryProjectScore.get("quality"));
              
              String level = "0";
              
              if(quality!=""&&quality.equals("2")){
                  String userNum = getMapToString(queryProjectScore.get("userNum"));
                  String highUserNum = getMapToString(queryProjectScore.get("highUserNum"));
                  
                  if("1".equals(queryProjectScore.get("ifLocking"))){
                      MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                      if(microSatisfyPointModel!=null){
                          level=microSatisfyPointModel.getBasePoint();
                      }
                     
                  }else{
                      level = getQualityLevel(userNum, highUserNum);
                  }    
              }else{
                  String safeNum = getMapToString(queryProjectScore.get("safeNum"));
                  String environmentNum = getMapToString(queryProjectScore.get("environmentNum"));
                  String serviceNum = getMapToString(queryProjectScore.get("serviceNum"));
                 
                  String userNum = getMapToString(queryProjectScore.get("userNum"));
                  
                  if("1".equals(queryProjectScore.get("ifLocking"))){
                      MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                      if(microSatisfyPointModel!=null){
                          level=microSatisfyPointModel.getBasePoint();
                      }
                     
                  }else{
                      level = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                  }    
              }
              return level;
          }
        return "";
    }
    /**
     * @描述 修改项目类型
     * @作者 李子民
     * @时间 2018年7月17日
     * @版本
     */
    public void updateQuality(UpdateQualityVO vo) {
        Map <String,String> map = new HashMap<>();
        map.put("cruentDate", vo.cruentDate);
        map.put("commId", vo.commId.toString());
        map.put("organId", vo.organId);
        map.put("quality", vo.quality.toString());
        microSatisfMapper.updateQuality(map);
    }
    /**
     * @描述 得分统计
     * @作者 李子民
     * @时间 2018年7月17日
     * @版本
     */
    public MicroSatisfyOrganDetailModel scoreStatistics(String beginDate,String endDate,String organId,String commId){

        MicroSatisfyOrganDetailModel summary = microSatisfMapper.queryProjectSummary(beginDate,endDate,organId,commId);
        if(summary!=null){
            String userNum = summary.getUserNum();
            String satisfyOrign ="0";
            if(summary.getQuality()==1){
                String serviceNum = summary.getServiceNum();
                String safeNum = summary.getSafeNum();
                String environmentNum = summary.getEnvironmentNum();
                
                if("1".equals(summary.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        satisfyOrign=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                    satisfyOrign = getBasicLevel(userNum, safeNum, serviceNum, environmentNum);
                }
                
            }else{
                String highUserNum = summary.getHighUserNum();
                if("1".equals(summary.getIfLocking())){
                    MicroSatisfyPointModel microSatisfyPointModel=microSatisfMapper.queryCommPointByCommCode(commId);
                    if(microSatisfyPointModel!=null){
                        satisfyOrign=microSatisfyPointModel.getBasePoint();
                    }
                   
                }else{
                    satisfyOrign = getQualityLevel(userNum, highUserNum);
                }
               
            }
            String score = getAssessmentScore(null,commId, satisfyOrign);
            summary.setN2(score);

            Map<String,String> map=new HashMap<>();
            map.put("beginDate",endDate);
            map.put("endDate",endDate);
            map.put("organId",organId);
            map.put("commId",commId);
            
            Map<String, String> managerData = findManagerData(map);
            if(managerData!=null&&managerData.size()>0){
                summary.setManagerAwarenessRate(String.valueOf(managerData.get("avgRecognitionPercentage")));
                summary.setManagerSatisfactionRate(String.valueOf(managerData.get("avgSatisfaction")));
            }

        }
        
        return summary;
    }
    /**
     * 业主心声
     * @param commId
     * @return
     */
    public List<Map<String, Object>> selectVoice(String beginDate,String endDate,String organId,String commId){
        return microSatisfMapper.selectVoice(beginDate,endDate,organId,commId);
    }
    
       public List<Map<String, Object>> selectVoiceRegion(String beginDate,String endDate,String organId,String flag){
           List<Map<String, String>> effectiveProject = new ArrayList<>();
            if(flag.equals("monthly")){
                if(beginDate.equals(endDate)){
                    effectiveProject = getEffectiveProject(beginDate, endDate,organId,null);
                }
                
            }
            return microSatisfMapper.selectVoiceRegion(beginDate,endDate,organId,effectiveProject);
        }
    
    
    /**
     * 获取问卷明细
     * @param 
     * @return
     */
    public List<MicroSatisfyOrganDetailModel> queryQuestionnaire(String beginDate,String endDate,String organId,String commId,PageRowBounds pageRowBounds){
        return microSatisfMapper.queryQuestionnaire(beginDate,endDate,organId,commId,pageRowBounds);
    }
    
    public List<Map<String,String>> querySatisfyQuestionnaireByType(String userCode){
        return microSatisfMapper.querySatisfyQuestionnaireByType(userCode);
    }
    
    
    public String getUser(String userCode){
       
        System.out.println("----用户code---"+userCode);
        //TbSysUser user = tbSysUserService.getCurrentSysUser(); 
        /*
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        HttpSession session = request.getSession(); */

     /*   
        Condition condition = new Condition(UserRoles.class);
        condition.createCriteria()
                .andEqualTo("userCode",userCode);*/


        //List<UserRoles> list = userRolesMapper.selectByCondition(condition);
   /*     List<String>  aList= new ArrayList<>();
        aList.add(userCode);
        List<UserRoles> list = userRolesMapper.searchByUserRoles(aList);*/
        
        
        List<Role> list = roleMapper.findByUserCode(userCode);
        
        String flag="";
        for (Role userRoles : list) {
            if(userRoles.getCode().equals("xyz_ordinary")){
                // 用户管辖区域（会有很多）
                //TbSysOrgan tbSysOrgan = tbSysOrganService.findByUserCode(userCode);
                
                List<WcxRegionProjectDto> code = tbHsprContractMapper.findErpRegionByUserCode(userCode);
                if(code.isEmpty()&&code.size()<=0){
                    try {
                        throw new Exception("查找不到用户所在区域");
                    } catch (Exception e) {
                          
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                        
                    }
                }
               
               // logger.info("---普通用户的区域----"+getJson(tbSysOrgan));
                
                WcxRegionProjectDto wcxRegionProjectDto = code.get(0);
                
                System.out.println("----区域名字---"+wcxRegionProjectDto.getRegionName());
                
                String organCode = tbHsprContractMapper.getOrganName(wcxRegionProjectDto.getRegionName());
                
                //flag=tbSysOrgan.getOrganCode();
                flag=organCode;
                break;
            }else if(userRoles.getCode().equals("xyz_admin")||userRoles.getCode().equals("admin")){
                flag="all";
                break;
            }
        }
        return flag;
    }
    
    private String getJson(Object... obj){
        
        List<Object> list=new ArrayList<>();
        
        for (Object object : obj) {
       /*     if(object instanceof Map){
                @SuppressWarnings("unchecked")
                Map<String,Object> mapObject = (Map<String,Object>)object;

            }
            if(object instanceof Integer){
                if("".equals((Integer)object)){
                    throw new HrmsException(message.getMessage("CommonNationalityServiceImpl.003"));
                }
            }
            if(object instanceof String){
                if(StringUtils.isEmpty((String)object)){
                    throw new  HrmsException(message.getMessage("CommonNationalityServiceImpl.004"));
                }
            }
            if(object instanceof List){
                if(((List)object).size() <= 0){
                    throw new HrmsException(message.getMessage("CommonNationalityServiceImpl.012"));
                }
            }*/
            
            
            list.add(obj);
         
        }
        
        Object json = JSONObject.toJSON(list);
        String string = json.toString();
        
        return string;
    }
    
    
    public Map<String,String> findManagerData(Map<String,String> map){
        
        Map<String,String> queryMap =new HashMap<String,String>();
        
        
        List<ManagerData> sum = microSatisfMapper.sumByDate(map);
        
        
        if(sum.size()>0){
            ManagerData sMap= sum.get(0);
        
            //String orDefault3 = (String) sMap.getOrDefault("manager_name","0");
            
            String managerName = sMap.getManagerName();
            
            //计算百分比
            int total = Integer.parseInt(managerName);
            //String orDefault = sMap.getOrDefault("recognition_percentage","0").toString();
            Double percentage = sMap.getRecognitionPercentage();
            
            Double avgRecognitionPercentage = NumberUtil.avgPercentage(percentage,total);
            queryMap.put("avgRecognitionPercentage", avgRecognitionPercentage.toString());
            //String orDefault2 = sMap.getOrDefault("satisfaction","0").toString();
            
            Double satisfaction = sMap.getSatisfaction();
            
            Double avgSatisfaction = NumberUtil.avgPercentage(satisfaction,total);
            queryMap.put("avgSatisfaction",avgSatisfaction.toString());
        } 
        
        return queryMap;
 }
    
    public Map<String,String> findYeryManagerData(Map<String,String> map){
        
        Map<String,String> queryMap =new HashMap<String,String>();
        
        
        List<ManagerData> sum = microSatisfMapper.sumYeryByDate(map);
        
        
        if(sum.size()>0){
            for (ManagerData sMap : sum) {
                String managerName = sMap.getManagerName();
                
                //计算百分比
                int total = Integer.parseInt(managerName);

                Double satisfaction = sMap.getSatisfaction();
                
                Double avgSatisfaction = NumberUtil.avgPercentage(satisfaction,total);
                //sMap.setSatisfaction(avgSatisfaction);
                queryMap.put(sMap.getCreatedBy(),avgSatisfaction.toString());
            }
           
        } 
        
        return queryMap;
    }
    
    
    //区域详情 --不满意统计
    public MicroSatisfyOrganDetailModel scoreStatisticsRegion(String beginDate,String endDate,String flag,String organId) {
        List<Map<String, String>> organEffectiveProject = getOrganEffectiveProject(beginDate, endDate, organId,null);

        MicroSatisfyOrganDetailModel queryProjectRegion = microSatisfMapper.queryProjectRegion(beginDate,endDate,organId,organEffectiveProject);
        
        BigDecimal bigDecimal = getWholeCountrySatisfaction(beginDate, endDate, organId,
                    organEffectiveProject);
        
        String score = getAssessmentScore(organId,null,bigDecimal.toString());
            
        if(queryProjectRegion!=null){
            queryProjectRegion.setN2(score);
        }
        return queryProjectRegion;
    }
    
    
    public List<Map<String, Object>> comA1() {
       
        List<Map<String, Object>> list = new ArrayList<>();
       // if ("1".equals(a)) {
           // Map<String, Object> map1 = new HashMap<>();
            //map1.put("text", "all");
           // map1.put("value", "全部区域");
           // list.add(map1);
       // }
        
        //Set<String> areaList = new HashSet<>();
        List<TbSysOrgan> tbSysOrgans = tbSysOrganMapper.findAllActive();
        for (TbSysOrgan tbSysOrgan : tbSysOrgans) {
            //areaList.add(tbSysOrgan.getOrganName());
            Map<String, Object> map = new HashMap<>();
            map.put("value", tbSysOrgan.getOrganCode());
            map.put("label", tbSysOrgan.getOrganName());
            list.add(map);
        }
   /*     for (String ar : areaList) {
            Map<String, Object> map = new HashMap<>();
            map.put("text", ar);
            map.put("value", ar);
            list.add(map);
        }*/
        return list;
    }
    
    
    public List<Map<String, Object>> getProjectName(String area) {
        List<Map<String, Object>> list = new ArrayList<>();
        list = this.comT2(area, list);
        return list;
    }
    
    
    public List<Map<String, Object>> comT2(String area, List<Map<String, Object>> list) {
        Set<TbSysOrgan> tbSysOrgans = this.b(area);
        Set<ErpCommunity> erpCommunitys1 = new HashSet<>();
        for (TbSysOrgan tbSysOrgan : tbSysOrgans) {
            List<ErpCommunity> erpCommunitys = tbHsprCommunityMapper.slectErpCommunityByOrganCode(tbSysOrgan.getOrganCode());
            for (ErpCommunity erpCommunity : erpCommunitys) {
                erpCommunitys1.add(erpCommunity);
            }
        }
        for (ErpCommunity erpCommunity : erpCommunitys1) {
            Map<String, Object> map = new HashMap<>();
            map.put("value", erpCommunity.getCommId());
            map.put("label", erpCommunity.getCommName());
            list.add(map);
        }
        return list;
    }
    
    
    public Set<TbSysOrgan> b(String area) {
        Set<TbSysOrgan> tbOrgans = new HashSet<>();
        if (StringUtils.isNotBlank(area)) {
            TbSysOrgan tbOrgan = tbSysOrganMapper.findByOrganCode(area);
            tbOrgans.add(tbOrgan);
        } else {
            List<TbSysOrgan> tbOrgans1 = tbSysOrganMapper.findAllActive();
            for (TbSysOrgan tbSysOrgan2 : tbOrgans1) {
                tbOrgans.add(tbSysOrgan2);
            }
        }
        return tbOrgans;
    }
}
