package com.yeejoin.amos.patrol.business.service.impl;

import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.patrol.business.dao.mapper.TaskReportMapper;
import com.yeejoin.amos.patrol.business.util.Toke;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TaskReportService {

    public static  final String STATISTICAL_TYPE_POINT = "POINT"; //按检查点
    public static  final String STATISTICAL_TYPE_ROUTE = "ROUTE";//按路线
    public static  final String STATISTICAL_TYPE_DEPT  = "DEPT";//按部门
    public static  final String STATISTICAL_TYPE_USER  = "USER";//按用户
    public static  final String STATISTICAL_TYPE_PLAN  = "PLAN";//按计划



    @Autowired
    private RemoteSecurityService remoteSecurityService;
    @Autowired
    private TaskReportMapper taskReportMapper;


    public Map<String,Object> queryForTaskReport(String token,String product,String appkey,String statisticalType, String startDate, String endDate, Integer planId, Integer routeId,String orgCode)
    {
        Map<String,Object> returnMap    = new HashMap<>();
        List<Map> result                = new ArrayList<>();
        Map  summation = new HashMap();
        switch (statisticalType)
        {
            case STATISTICAL_TYPE_DEPT:
                result                  = taskReportMapper.queryWithDept("false",startDate, endDate, planId, routeId,orgCode);
                List<Map> summationListDept = taskReportMapper.queryWithDept( "true",startDate, endDate, planId, routeId,orgCode);
                summation               = summationListDept.get(0);


	            //安全处里
	            if(result!=null&&result.size()>0){

	            	  //获取部门名称
	                String userIds="";
	                Set<String> set = new HashSet<>();
	                result.forEach(s -> {
	                	 set.add(s.get("itemName").toString());
	                });
                    result.forEach(s -> {
                        // 跨部门任务
                        if(s.get("itemName").toString().indexOf(",")>0){
                            StringBuffer stringBuffer =new StringBuffer();
                            String [] departments =   s.get("itemName").toString().split(",");
                            Arrays.asList(departments).stream().forEach(department->{
                                stringBuffer.append(department.substring(department.indexOf("@")+1)).append(",");
                            });
                            s.put("itemName",stringBuffer.toString());
                            s.put("itemId",stringBuffer.toString());
                        }else{
                            //不跨部门任务
                            s.put("itemName",s.get("itemName").toString().substring(s.get("itemName").toString().indexOf("@")+1));
                            s.put("itemId",s.get("itemId").toString().substring(s.get("itemId").toString().indexOf("@")+1));
                        }
                        set.add(s.get("itemName").toString());
                    });
                    //相同不部门相加

//	                List<String> list1 = new ArrayList<>(set);
//	                userIds = String.join(",", list1);
//	                List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( token,product,appkey,userIds);
//
//	                //新安全
//	                result.forEach(s -> {
//	                	if(  listd != null && listd.size() > 0) {
//	                		List<LinkedHashMap> filterDep = listd.stream().filter(d -> d.get("sequenceNbr").toString().equals(s.get("itemName").toString())).collect(Collectors.toList());
//
//	            			if(filterDep != null && filterDep.size() > 0){
//	            				LinkedHashMap dep = filterDep.get(0);
//	            				 s.put("itemName",dep.get("departmentName").toString());
//	                        }
//	                	}
//
//	                	    });
	            }

                break;
            case STATISTICAL_TYPE_POINT:
                result                  = taskReportMapper.queryWithPoint("false",startDate, endDate, planId, routeId,orgCode);
                List<Map> summationList = taskReportMapper.queryWithPoint( "true",startDate, endDate, planId, routeId,orgCode);
                summation               = summationList.get(0);
                break;
            case STATISTICAL_TYPE_ROUTE:
                result                  = taskReportMapper.queryWithRoute("false",startDate, endDate, planId, routeId,orgCode);
                List<Map> summationListRoute = taskReportMapper.queryWithRoute( "true",startDate, endDate, planId, routeId,orgCode);
                summation               = summationListRoute.get(0);
                break;
            case STATISTICAL_TYPE_USER:
                result                  = taskReportMapper.queryWithUser("false",startDate, endDate, planId, routeId,orgCode);
                List<Map> summationListUser = taskReportMapper.queryWithUser( "true",startDate, endDate, planId, routeId,orgCode);

                //查询用户名

                //安全处里
	            if(result!=null&&result.size()>0){

	            	  //处理用户信息
	                String userIds="";
	                Set<String> set = new HashSet<>();
	                result.forEach(s -> {
		                     set.add(s.get("itemName").toString());
	                });
	                List<String> list1 = new ArrayList<>(set);
	                userIds = String.join(",", list1);
	                List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds( token,product,appkey,userIds);
	                //新安全
	                result.forEach(s -> {
	                		 listd.forEach(s1 -> {
	                	    		if(s.get("itemName").toString().equals(s1.getUserId())){
	                	    			 s.put("itemName", s1.getRealName());
	                	    		}
	                	        });

	                	    });
	            }


                summation               = summationListUser.get(0);
                break;
            case STATISTICAL_TYPE_PLAN:
                result                  = taskReportMapper.queryWithPlan("false",startDate, endDate, planId, routeId,orgCode);
                List<Map> summationListPlan = taskReportMapper.queryWithPlan( "true",startDate, endDate, planId, routeId,orgCode);
                summation               = summationListPlan.get(0);
                break;
        }

        returnMap.put("dataByMonth",result);
        returnMap.put("summation",summation);
        return returnMap;
    }




    public Map<String,Object> comprehensiveStatisticalForUser(Toke toke,String product,String appKey,String startTime,String endTime) {

        Map<String,Object> returnMap    = new HashMap<>();
        List<Map> result                = new ArrayList<>();
        Map  summation = new HashMap();
        result                  = taskReportMapper.comprehensiveStatisticalForUser("false",startTime,endTime);
        List<Map> summationListPlan = taskReportMapper.comprehensiveStatisticalForUser( "true",startTime,endTime);
        summation = summationListPlan.get(0);

       //处理用户信息
        String userIds="";
        Set<String> set = new HashSet<>();
        result.forEach(s -> {
        	 if(s.containsKey("userId")){
        		 set.add(s.get("userId").toString());
        	 }

        });

        List<String> list1 = new ArrayList<>(set);
        userIds = String.join(",", list1);


        List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds( toke.getToke(), product, appKey, userIds);

        //新安全
        result.forEach(s -> {
               String [] uids=null;
               StringBuilder userNames =new StringBuilder("");
               StringBuilder deptNames =new StringBuilder("");
               if(s.get("userId").toString().indexOf(",")>0){
                 uids = s.get("userId").toString().split(",");
               }
             Map<String,String> deptMap = new HashMap<>();
            if(s.get("user_dept").toString().indexOf(",") > 0){
                List<String>  depts =  Arrays.asList(s.get("user_dept").toString().split(","));
                depts.stream().forEach(dept->{
                    deptMap.put(dept.substring(0,dept.indexOf("@")),dept.substring(dept.indexOf("@")+1,dept.length()));
                    List<DepartmentModel> departmentModel =  remoteSecurityService.getlistDepartmentByDeptIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), dept.substring(dept.indexOf("@")+1,dept.length()));
                    StringBuffer  deptNameBuffer = new StringBuffer();
                    departmentModel.forEach(companyModel -> {
                        deptNameBuffer.append(companyModel.getDepartmentName()).append("|");
                    });
                    deptMap.put(dept.substring(0,dept.indexOf("@")),deptNameBuffer.toString());
                });
            }else{
                List<DepartmentModel> departmentModel =  remoteSecurityService.getlistDepartmentByDeptIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), s.get("user_dept").toString().substring(s.get("user_dept").toString().indexOf("@")+1));
                StringBuffer  deptNameBuffer = new StringBuffer();
                departmentModel.forEach(companyModel -> {
                    deptNameBuffer.append(companyModel.getDepartmentName()).append("|");
                });
                deptMap.put(s.get("user_dept").toString().substring(0,s.get("user_dept").toString().indexOf("@")),deptNameBuffer.toString());
            }

               if(uids!=null&&uids.length>0){
                   for (String uid:uids) {
                     listd.forEach(s1 -> {
                         if(uid!=null) {
                             if (uid.equals(s1.getUserId())) {
                                 if(userNames.length()==0){
                                         userNames.append(s1.getRealName());
                                         userNames.append(",");
                                     String deptName = "";
                                     Map<Long, List<DepartmentModel>> map = s1.getCompanyDepartments();
                                     if(map!=null){
                                         for (Long key : map.keySet()) {
                                             List<DepartmentModel> value = map.get(key);//
                                             for (DepartmentModel departmentModel : value) {
                                                 if (departmentModel != null) {
                                                     if (!deptName.contains(departmentModel.getDepartmentName())) {
                                                         deptName = deptName + departmentModel.getDepartmentName() + ",";
                                                     }
                                                 }
                                             }

                                         }
                                     }
                                     deptNames.append(deptName);
                                     deptNames.append("|");
                                 }else if(userNames.length()>1) {
                                     if (s1.getRealName().length() < userNames.length()) {
                                         if (!s1.getRealName().equals(userNames.substring(userNames.length() - 1-s1.getRealName().length(), userNames.length() - 1))) {
                                             userNames.append(s1.getRealName());
                                             userNames.append(",");
                                             String deptName = "";
                                             Map<Long, List<DepartmentModel>> map = s1.getCompanyDepartments();
                                             if (map != null) {
                                                 for (Long key : map.keySet()) {
                                                     List<DepartmentModel> value = map.get(key);//
                                                     for (DepartmentModel departmentModel : value) {
                                                         if (departmentModel != null) {
                                                             if (!deptName.contains(departmentModel.getDepartmentName())) {
                                                                 deptName = deptName + departmentModel.getDepartmentName() + ",";
                                                             }
                                                         }
                                                     }

                                                 }
                                             }
                                             deptNames.append(deptName);
                                             deptNames.append("|");
                                         }
                                     }
                                 }

                             }
                         }
                     });
                  }
                if(userNames.length()>0){
                    s.put("userName",userNames);
                }
//                if(deptNames.length()>0){
//                    s.put("deptName",deptNames.substring(0,deptNames.length()-1));
//                }

                   s.put("deptName",deptMap.get(s).toString().substring(0,deptMap.get(s).toString().length()-1));
               }else {
                   listd.forEach(s1 -> {
                       if (s.get("userId").toString().equals(s1.getUserId())) {
                           s.put("userName", s1.getRealName());
                           String deptName = "";
                           Map<Long, List<DepartmentModel>> map = s1.getCompanyDepartments();
                           if(map!=null){
                           for (Long key : map.keySet()) {
                               List<DepartmentModel> value = map.get(key);//
                               for (DepartmentModel departmentModel : value) {
                                   if (departmentModel != null) {
                                       if (!deptName.contains(departmentModel.getDepartmentName())) {
                                           deptName = deptName + departmentModel.getDepartmentName() + ",";
                                       }
                                   }
                               }
                             }
                           }
                           s.put("deptName",deptMap.get(s.get("userId")).toString().substring(0,deptMap.get(s.get("userId")).toString().length()-1));
                       }
                   });
               }
          });
        returnMap.put("report",result);
        returnMap.put("summation",summation);
        return returnMap;
    }







}
