package com.palmnest.service.dinner.service.impl;

import java.io.File;
import java.math.BigDecimal;
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.HashMap;
import java.util.List;
import java.util.Map;

import cn.superdesk.libs.common.json.JsonUtils;
import com.palmnest.application.dto.*;
import com.palmnest.model.dinner.*;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.service.dinner.manager.*;
import com.palmnest.service.notice.WxPubManager;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.CollectionUtils;
import scala.collection.concurrent.TNode;
import sun.security.krb5.internal.crypto.crc32;
import cn.jiguang.common.utils.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.ListPage;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.ExcelUtils;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.KfnewsDto;
import com.palmnest.application.core.util.MD5;
import com.palmnest.application.core.util.PageUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.core.util.WeekDate;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.IntegralRecodeDto;
import com.palmnest.application.dto.output.MealAndUserDto;
import com.palmnest.application.dto.output.MealOutPutDto;
import com.palmnest.application.dto.output.VisitorStatisticsDto;
import com.palmnest.dao.notice.MobileConfigDao;
import com.palmnest.model.DateTypeInfo;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.MobileConfigModel;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.AppUserService;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.dinner.service.OrderDinnerService;
import com.palmnest.service.dinner.service.PlaceAnOrderService;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.DateTypeInfoManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.notice.MobileConfigManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.WeChatApiManager;
@Service("placeAnOrderService")
public class PlaceAnOrderServiceImpl implements PlaceAnOrderService{
	private Logger LOG=Logger.getLogger(PlaceAnOrderServiceImpl.class);

	@Autowired
	private OrderDinnerInfoManager orderDinnerInfoManager;
	@Autowired
	private MealCarManager mealCarManager;
	
	@Autowired
	private AppUserManager appUserManager;
	@Autowired
	private MealManager mealManager;
	
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private IntegralRecodeInfoManager integralRecodeInfoManager;
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private OrderDinnerManager orderDinnerManager;
	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private WeChatApiManager weChatApiManager;
	@Autowired
	private RechargeSetManager rechargeSetManager;
	@Autowired
	private RechargeRecordManager rechargeRecordManager;
	@Autowired
	private BaseRedisService baseRedisService;
	@Autowired
	private UserManager userManager;
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	
	@Autowired
	private WxPubManager wxPubManager;
	
	@Autowired
	private ScWxuserManager scWxuserManager;
	@Autowired
	private OrganizationManager organizationManager;
	
	@Autowired 
	private PropertyManager propertyManager;
	
	@Autowired
	private OrderDinnerService orderDinnerService;
	@Autowired
	private DateTypeInfoManager dateTypeInfoManager;

	@Autowired
	private OrderDinnerSetManager orderDinnerSetManager;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    
	public static String host = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wxDinnerUrl = PropertiesKit.readPropertiesValue("wxDinnerUrl", "wechat.properties");
	public static String clientNo = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");
	public static final String wxMessageUrl  = PropertiesKit.readPropertiesValue("wxMessageUrl", "wechat.properties");

	public static final String wxTempUrl  = PropertiesKit.readPropertiesValue("wxTempUrl", "wechat.properties");
	/**
	 * 获取能够订餐的用户
	 * @return
	 */
	@Override
	public AppResultDto getUserBy(Map<String, Object> paraments) {
		Integer orgId=Integer.parseInt(paraments.get("orgId").toString());
		Integer wxUserId=Integer.parseInt(paraments.get("wxUserId").toString());
		String res=appUserService.getAppUser( orgId, wxUserId);
		if(StringUtils.isNotEmpty(res)){
			return AppResultUtil.createErrorDto("100", res);
		}
		AppUser user=appUserManager.get(wxUserId);
		RechargeSet reSet=rechargeSetManager.findByOrgId(orgId.toString());
		if(reSet==null){
			return AppResultUtil.createErrorDto("100", "该项目下未设置积分，无法提交");
		}
		int type=0;
		if(paraments.containsKey("type")){
			if(StringUtils.isNotEmpty(paraments.get("type")==null?"":paraments.get("type").toString())){
				type=Integer.parseInt(paraments.get("type").toString());
			}
		}
		if(type==1){//获取有效的订餐时间的用户
			//根据openId获取userId
			String operator="";//developId
			
			if(user!=null){
				operator=user.getId().toString();
			}
			String time=paraments.get("time")==null?"":paraments.get("time").toString();
			List<ConsumerDto> userDtoList=new ArrayList<ConsumerDto>();
			Map<String,List<ConsumerDto>> map=orderDinnerInfoManager.getUserByTime(paraments.get("orgId").toString(), paraments.get("time").toString());
			if(map.containsKey("notHaveOrderList")){
				List<ConsumerDto> dtoList=map.get("notHaveOrderList");
				if(dtoList!=null&&dtoList.size()>0){
					for(int i=0;i<dtoList.size();i++){
						ConsumerDto dto=dtoList.get(i);
						int isHaveCar=mealCarManager.getMealCarByUserIdAndTime(dto.getId(),time, operator);
						if(isHaveCar==1){
							dto.setIsMealCar(1);//购物车中有数据(需要灰显)
						}else{
							dto.setIsMealCar(0);//购物车中没数据
						}
						if(StringUtils.isNotEmpty(dto.getId())&&appUserManager.exists(Integer.parseInt(dto.getId()))){
							AppUser users=appUserManager.get(Integer.parseInt(dto.getId()));
							if(users!=null&&users.getIntegral()>=reSet.getDayCount()){
								userDtoList.add(dto);
							}
						}
					}
				}
			}
			if(userDtoList!=null&&userDtoList.size()>0){
				return AppResultUtil.createSuccesDto(userDtoList);
			}
		}else if(type==2){//获取今天所有用户
			Date date=new Date();
			Map<String,List<ConsumerDto>> map=orderDinnerInfoManager.getUserByTime(paraments.get("orgId").toString(), sdf.format(date));
			return AppResultUtil.createSuccesDto(map);
		}
		return AppResultUtil.createErrorDto("100", "暂无账号");
	}
//	@Override
//	public AppResultDto getWeek(String orgId, String wxUserId) {
//		long beginTime=System.currentTimeMillis();
//		System.out.println("beginTime:"+beginTime);
//		LOG.info("beginTime:"+beginTime);
//		List<WeekDate> weekNewList=new ArrayList<WeekDate>();
//		int isOver=orderDinnerManager.isOver(orgId,"orderTime");
//		try {
//			String mealJson = baseRedisService.get(CodeConstants.ORG_MEAL_LIST_KEY+orgId);
//			if(StringUtils.isNotEmpty(mealJson)) {
//				List<WeekDate> weekList=JSONArray.parseArray(mealJson, WeekDate.class);
//				if(weekList!=null&&weekList.size()>0){
//					for(int i=0;i<weekList.size();i++){
//						WeekDate week=weekList.get(i);
//						int count=mealCarManager.findByUserId(wxUserId, week.getDateTime());
//						if(DateUtils.checkIsOver(week.getDateTime(), isOver)){
//							week.setIsShow(0);
//						}else{
//							week.setIsShow(1);
//						}
//						if(count>0&&week.getIsShow()==1){
//							week.setSumCount(count);
//						}else{
//							week.setSumCount(null);
//						}
//						String sysDate=DateUtils.formatDate(new Date(), "yyyy-MM-dd");
//						if(sysDate.equals(week.getDateTime())){
//							week.setIsToday(1);
//						}else{
//							week.setIsToday(0);
//						}
//						int blueCount=orderDinnerInfoManager.getOrderCount(wxUserId, week.getDateTime());
//						if(blueCount>0){
//							week.setIsBule(1);
//						}else{
//							week.setIsBule(0);
//						}
//						List<Meal> mealList=week.getMealList();
//						if(mealList!=null&&mealList.size()>0){
//							week.setMealList(mealList);
//							weekNewList.add(week);
//						}
//					}
//				}
//			}else{
//				List<WeekDate> weekList=DateUtils.getWeek();
//				if(weekList!=null&&weekList.size()>0){
//					for(int i=0;i<weekList.size();i++){
//						WeekDate week=weekList.get(i);
//						int count=mealCarManager.findByUserId(wxUserId, week.getDateTime());
//						if(DateUtils.checkIsOver(week.getDateTime(), isOver)){
//							week.setIsShow(0);
//						}else{
//							week.setIsShow(1);
//						}
//						if(count>0&&week.getIsShow()==1){
//							week.setSumCount(count);
//						}else{
//							week.setSumCount(null);
//						}
//						int blueCount=orderDinnerInfoManager.getOrderCount(wxUserId, week.getDateTime());
//						if(blueCount>0){
//							week.setIsBule(1);
//						}else{
//							week.setIsBule(0);
//						}
//						List<Meal> mealList=mealManager.findMealList(orgId,week.getDateTime());
//						List<Meal> mealLists=mealManager.getMealList(orgId,week.getDateTime());
//						if(mealLists!=null&&mealLists.size()>0){
//							week.setMealList(mealList);
//							weekNewList.add(week);
//						}
//					}
//				}
//				baseRedisService.set(CodeConstants.ORG_MEAL_LIST_KEY+orgId,  JSONObject.toJSONString(weekNewList));
//			}
//			Collections.sort(weekNewList,new Comparator<WeekDate>() {
//				public int compare(WeekDate o1, WeekDate o2) {
//	                String name1 =String.valueOf(o1.getWeekNo());//name1是从你list里面拿出来的一个
//	                String name2= String.valueOf(o2.getWeekNo()); //name1是从你list里面拿出来的第二个name
//	                return name1.compareTo(name2);
//	        }
//			});
//		} catch (Exception e) {
//			LOG.error(e.getMessage());
//			return AppResultUtil.createErrorDto("100", "获取餐品列表失败");
//		}
//		long endTime=System.currentTimeMillis();
//		System.out.println("endTime:"+endTime+",间隔："+(endTime-beginTime));
//		LOG.info("endTime:"+endTime+",间隔："+(endTime-beginTime));
//		if(weekNewList!=null&&weekNewList.size()>0){
//			return AppResultUtil.createSuccesDto(weekNewList);
//		}
//		return AppResultUtil.createErrorDto("100", "尚未维护餐品，请联系管理员");
//	}


	@Override
	public AppResultDto getWeek(String orgId, String wxUserId) {
		long beginTime=System.currentTimeMillis();
		System.out.println("beginTime:"+beginTime);
		LOG.info("beginTime:"+beginTime);
		List<WeekDate> weekNewList=new ArrayList<WeekDate>();
		int isOver=orderDinnerManager.isOver(orgId,"orderTime");
		try {
			String mealJson = baseRedisService.get(CodeConstants.ORG_MEAL_LIST_KEY+orgId);
			if(StringUtils.isNotEmpty(mealJson)) {
				List<WeekDate> weekList=JSONArray.parseArray(mealJson, WeekDate.class);
				if(weekList!=null&&weekList.size()>0){
					for(int i=0;i<weekList.size();i++){
						WeekDate week=weekList.get(i);
						int count=mealCarManager.findByUserId(wxUserId, week.getDateTime());
						if(DateUtils.checkIsOver(week.getDateTime(), isOver)){
							week.setIsShow(0);
						}else{
							week.setIsShow(1);
						}
						if(count>0&&week.getIsShow()==1){
							week.setSumCount(count);
						}else{
							week.setSumCount(null);
						}
						String sysDate=DateUtils.formatDate(new Date(), "yyyy-MM-dd");
						if(sysDate.equals(week.getDateTime())){
							week.setIsToday(1);
						}else{
							week.setIsToday(0);
						}
						int blueCount=orderDinnerInfoManager.getOrderCount(wxUserId, week.getDateTime());
						if(blueCount>0){
							week.setIsBule(1);
						}else{
							week.setIsBule(0);
						}
						List<Meal> mealList=week.getMealList();
						if(mealList!=null&&mealList.size()>0){
							week.setMealList(mealList);
							weekNewList.add(week);
						}
					}
				}
			}else{
				List<WeekDate> weekList=mealManager.getMealDate(Integer.parseInt(orgId));
				if(weekList!=null&&weekList.size()>0){
					for(int i=0;i<weekList.size();i++){
						WeekDate week=weekList.get(i);
						int count=mealCarManager.findByUserId(wxUserId, week.getDateTime());
						if(DateUtils.checkIsOver(week.getDateTime(), isOver)){
							week.setIsShow(0);
						}else{
							week.setIsShow(1);
						}
						if(count>0&&week.getIsShow()==1){
							week.setSumCount(count);
						}else{
							week.setSumCount(null);
						}
						int blueCount=orderDinnerInfoManager.getOrderCount(wxUserId, week.getDateTime());
						if(blueCount>0){
							week.setIsBule(1);
						}else{
							week.setIsBule(0);
						}
						List<Meal> mealList=mealManager.findMealList(orgId,week.getDateTime());
						List<Meal> mealLists=mealManager.getMealList(orgId,week.getDateTime());
						if(mealLists!=null&&mealLists.size()>0){
							week.setMealList(mealList);
							weekNewList.add(week);
						}
					}
				}
				baseRedisService.set(CodeConstants.ORG_MEAL_LIST_KEY+orgId,  JSONObject.toJSONString(weekNewList));
			}
//			Collections.sort(weekNewList,new Comparator<WeekDate>() {
//				public int compare(WeekDate o1, WeekDate o2) {
//					String name1 =String.valueOf(o1.getWeekNo());//name1是从你list里面拿出来的一个
//					String name2= String.valueOf(o2.getWeekNo()); //name1是从你list里面拿出来的第二个name
//					return name1.compareTo(name2);
//				}
//			});
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取餐品列表失败");
		}
		long endTime=System.currentTimeMillis();
		System.out.println("endTime:"+endTime+",间隔："+(endTime-beginTime));
		LOG.info("endTime:"+endTime+",间隔："+(endTime-beginTime));
		if(weekNewList!=null&&weekNewList.size()>0){
			return AppResultUtil.createSuccesDto(weekNewList);
		}
		return AppResultUtil.createErrorDto("100", "尚未维护餐品，请联系管理员");
	}
	@Override
	public AppResultDto getWeekDate(String orgId, String wxUserId,
			String dinnerTime) {
		AppUser user=null;
		if(StringUtils.isNotEmpty(wxUserId)&&appUserManager.exists(Integer.parseInt(wxUserId))){
			user=appUserManager.get(Integer.parseInt(wxUserId));
		}
		List<MealAndUserDto> mealDtoList=getDtoList(orgId, dinnerTime,user);
		if(mealDtoList!=null&&mealDtoList.size()>0){
			return AppResultUtil.createSuccesDto(mealDtoList);
		}
		return AppResultUtil.createSuccesDto();
	}
	public List<MealAndUserDto> getDtoList(String orgId,String time,AppUser user){
		List<MealAndUserDto> dtoList=new ArrayList<MealAndUserDto>();
		String mealJson = baseRedisService.get(CodeConstants.ORG_MEAL_LIST_KEY+orgId);
		List<Meal> list=new ArrayList<Meal>();
		if(StringUtils.isNotEmpty(mealJson)) {
			List<WeekDate> weekNewList=JSONArray.parseArray(mealJson,WeekDate.class);
			for(int i=0;i<weekNewList.size();i++){
				WeekDate week=weekNewList.get(i);
				if(time.equals(week.getDateTime())){
					list=week.getMealList();
					break;
				}
			}
		}else{
			list=mealManager.findMealList(orgId,time);
		}
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Meal meal=list.get(i);
				if(meal!=null){
					if(meal.getIsMeetingFood()==1){//是会议餐的时候
						//判断用户是否普通用户，是则跳出循环（个人账号下不显示会议餐）
						if(user!=null&&!"1".equals(user.getRoleType())){
							continue;
						}
					}
					MealAndUserDto dto=new MealAndUserDto();
					MealOutPutDto mealDto=new MealOutPutDto();
					mealDto.setId(meal.getId().toString());
					//设置餐品描述
					mealDto.setMealDescribe(meal.getMealDescribe());
					String mealImagesUrl="";
					//设置餐品图片
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					if(StringUtils.isNotEmpty(meal.getMealImages())){
						String [] urls=meal.getMealImages().split(";");
						if(urls!=null&&urls.length>0){
							for(int j=0;j<urls.length;j++){
								mealImagesUrl=mealImagesUrl+fileUploadUtils.fullVisitPath(urls[j])+";";
							}
							mealDto.setMealImagesUrl(fileUploadUtils.fullVisitPath(urls[0]));
							mealDto.setMealImages(mealImagesUrl);
						}
					}
					//设置餐品名字
					//----餐品
					if(StringUtils.isNotEmpty(meal.getMealCodeId())){
						ElementDto el=elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
						if(el!=null){
							mealDto.setMealName(el.getItemname());
						}
					}
					mealDto.setIsMeetFood(meal.getIsMeetingFood());
//					mealDto.setMealName(meal.getMealName());
					//设置规格参数
					mealDto.setSpec(meal.getSpec());
					//---规格中文描述
					if("1".equals(meal.getSpec())){
						mealDto.setSpecStr("单品");
					}else{
						if(StringUtils.isNotEmpty(meal.getSpec())){
							ElementDto el=elementGroupManager.getElementById(Long.parseLong(meal.getSpec()));
							if(el!=null){
								mealDto.setSpecStr(el.getItemname());
							}
						}
					}
					//设置主食
					if(StringUtils.isNotEmpty(meal.getStapleFood())){
						List<StapleFoodDto> foodList=new ArrayList<StapleFoodDto>();
						String  [] str=meal.getStapleFood().split(";");
						if(str!=null&&str.length>0){
							String stapleFoodStr="";
							for(int k=0;k<str.length;k++){
								StapleFoodDto food=new StapleFoodDto();
								ElementDto el=elementGroupManager.getElementById(Long.parseLong(str[k]));
								if(el!=null){
									stapleFoodStr=stapleFoodStr+el.getItemname()+"、";
									food.setFoodId(el.getId());
									food.setFoodCode(el.getItemcode());
									food.setFoodName(el.getItemname());
									food.setOrderNo(el.getSort());
									foodList.add(food);
								}
							}
							if(foodList!=null&&foodList.size()>0){
								Collections.sort(foodList,new Comparator<StapleFoodDto>() {
									public int compare(StapleFoodDto o1, StapleFoodDto o2) {  
						                String name1 =o1.getOrderNo().toString();//name1是从你list里面拿出来的一个  
						                String name2= o2.getOrderNo().toString(); //name1是从你list里面拿出来的第二个name      
						                return name1.compareTo(name2);    
						        }  
								});
							}
							if(StringUtils.isNotEmpty(stapleFoodStr)){
								stapleFoodStr=stapleFoodStr.substring(0,stapleFoodStr.length()-1);
								mealDto.setStapleFoodStr(stapleFoodStr);
							}
							mealDto.setIsHaveFood(1);
							mealDto.setStapleFood(foodList);
						}
					}else{
						mealDto.setIsHaveFood(0);
					}
					dto.setDto(mealDto);
					if(user!=null){
						int count=mealCarManager.findMealCarListByUserId(user.getId().toString(), time, meal.getId().toString());
						if(count>0){
							dto.setCount(count);
						}
					}
					
					dtoList.add(dto);//汇总该用户该时间该餐品下购物车中的份数
				}
			}
		}
		return dtoList;
	}
	 /**
     * 根据参数获取该餐品下购物车中的详情(仅限组合)
     * @param parements
     * @return
     */
	@Override
	public AppResultDto getMealCarByMealId(Map<String, String> parements) {
		Integer orgId=Integer.parseInt(parements.get("orgId").toString());
		Integer wxUserId=Integer.parseInt(parements.get("wxUserId").toString());
		String res=appUserService.getAppUser( orgId, wxUserId);
		if(StringUtils.isNotEmpty(res)){
			return AppResultUtil.createErrorDto("100", res);
		}
		AppUser user=appUserManager.get(wxUserId);
		String userId=user.getId().toString();
		parements.put("userId", userId);
		List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
		if("1".equals(user.getRoleType())){//管理员
			mapList=mealCarManager.getMealCarGroupFood(parements);
		}else{
			Map<String,Object> map=new HashMap<String, Object>();
			//选中主食、份数(一般情况为1)
			List<MealCar> meaCarList=mealCarManager.getMealCarByParemens(parements);
			if(meaCarList!=null&&meaCarList.size()>0){
				MealCar mealCarInfo=meaCarList.get(0);
				map.put("mealId", mealCarInfo.getMealId());
				map.put("stapleFood", mealCarInfo.getStapleFood());
				map.put("foodCount", mealCarInfo.getFoodCount());
				map.put("users", mealCarInfo.getConsId());
			}
			if(map!=null&&StringUtils.isNotEmpty(map.get("mealId")==null?"":map.get("mealId").toString())){
				mapList.add(map);
			}
		}
		return AppResultUtil.createSuccesDto(mapList);
	}

	@Override
	public AppResultDto getAllMeetFood(String orgIds, String wxUserIds, String time) {
		Integer orgId=Integer.parseInt(orgIds);
		Integer wxUserId=Integer.parseInt(wxUserIds);
		String res=appUserService.getAppUser( orgId, wxUserId);
		if(StringUtils.isNotEmpty(res)){
			return AppResultUtil.createErrorDto("100", res);
		}
		AppUser user=appUserManager.get(wxUserId);
		if(!"1".equals(user.getRoleType())){
			return AppResultUtil.createErrorDto("100", "非管理员无权操作");
		}
		Map<String,Object> map=new HashMap<String, Object>();
		List<Map<String, Object>>  list=orderDinnerInfoManager.getMeetFood(orgIds, time);
		
		if(list!=null&&list.size()>0){
			map.put("sumCount", getMeetFoodCount(orgIds,time));//总份数
			map.put("meetList", list);//会议餐
			return AppResultUtil.createSuccesDto(map);
		}
		return AppResultUtil.createSuccesDto();
	}
	
	@Override
	public AppResultDto getAllTempOrder(String orgIds, String wxUserIds,
			String time) {
		Integer orgId=Integer.parseInt(orgIds);
		Integer wxUserId=Integer.parseInt(wxUserIds);
		String res=appUserService.getAppUser( orgId, wxUserId);
		if(StringUtils.isNotEmpty(res)){
			return AppResultUtil.createErrorDto("100", res);
		}
		AppUser user=appUserManager.get(wxUserId);
		if(!"1".equals(user.getRoleType())){
			return AppResultUtil.createErrorDto("100", "非管理员无权操作");
		}
		Map<String,Object> map=new HashMap<String, Object>();
		List<Map<String, Object>>  list=orderDinnerInfoManager.getTempOrder(orgIds, time);
		
		if(list!=null&&list.size()>0){
			map.put("sumCount", getTempOrderCount(orgIds,time));//总份数
			map.put("meetList", list);//临时工作餐
			return AppResultUtil.createSuccesDto(map);
		}
		return AppResultUtil.createSuccesDto();
	}
	/**
	 * 获取会议餐的总份数
	 * @return
	 */
	@Override
	public int getMeetFoodCount(String orgId,String time){
		List<Map<String, Object>>  list=orderDinnerInfoManager.getMeetFood(orgId, time);
		int sumCount=0;
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Map<String, Object> meetMap=list.get(i);
				if(StringUtils.isNotEmpty(meetMap.get("foodCount")==null?"":meetMap.get("foodCount").toString())){
					sumCount=sumCount+Integer.parseInt(meetMap.get("foodCount").toString());
				}
			}
		}
		return sumCount;
	}
	@Override
	public int getTempOrderCount(String orgId, String time) {
		List<Map<String, Object>>  list=orderDinnerInfoManager.getTempOrder(orgId, time);
		int sumCount=0;
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Map<String, Object> meetMap=list.get(i);
				if(StringUtils.isNotEmpty(meetMap.get("foodCount")==null?"":meetMap.get("foodCount").toString())){
					sumCount=sumCount+Integer.parseInt(meetMap.get("foodCount").toString());
				}
			}
		}
		return sumCount;
	}
	@Override
	public AppResultDto getRecodeInfo(String wxUserId, String orgId) {
		Integer wxUserIds=Integer.parseInt(wxUserId);
		String res=appUserService.getAppUser( Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if(StringUtils.isNotEmpty(res)){
			return AppResultUtil.createErrorDto("100", res);
		}
		AppUser user=appUserManager.get(wxUserIds);
		List< IntegralRecodeDto>intList= integralRecodeInfoManager.getRecodeInfo(user.getUserMobile(), orgId);
		if(intList!=null&&intList.size()>0){
			return AppResultUtil.createSuccesDto(intList);
		}
		return AppResultUtil.createSuccesDto();
	}
	
	@Override
	public WebPageResultDto getAllIntegralRecodeList(Map<String, Object> paramets, int pageSize, int pageNo) {

		Page  page   = integralRecodeInfoManager.getPageRecodeInfo(paramets, pageSize,pageNo);		
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "", page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}
	
	@Override
	public AppResultDto getMealUser(Map<String, String> parements) {
		Map<String, Object> map=mealCarManager.getMealUser(parements);
		return AppResultUtil.createSuccesDto(map);
	}
	
	@Override
	public void sendMessageByEveryDay(String openId,String orgId) {
		//判断该日期是否工作日0工作日1休息日2节假日
//		int dataType=DateUtils.getDateType(sdf.format(new Date()));
		int dataType=-1;
		DateTypeInfo nowDay=dateTypeInfoManager.getDateTypeInfoList(sdf.format(new Date()));
    	if(nowDay!=null){
    		dataType=nowDay.getType();
    	}
    	LOG.info("sendMessageByEveryDay/dataType:"+dataType);
		//首先获取某个服务下的项目
		String newOrgs=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		LOG.info("sendMessageByEveryDay/orgIds:"+newOrgs);
		String[] orgArr=newOrgs.split(",");
		//获取设置了微信提醒的项目
        String orgIds="";
    	if(orgArr!=null&&orgArr.length>0){
        	for(int i=0;i<orgArr.length;i++){
    			TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgArr[i]));
    			if(org==null){
    				continue;
    			}
    			LOG.info("getIsSetWechatMessage========orgId:"+orgArr[i]+";isSetWechatMessage:"+org.getIsSetWechatMessage());
    			if(org!=null&&org.getIsSetWechatMessage()==1){
    				orgIds=orgIds+orgArr[i]+",";
    			}
    		}
        }
    	LOG.info("newOrgs："+orgIds);
    	if(StringUtils.isNotEmpty(orgIds)&&",".equals(orgIds.substring(orgIds.length()-1,orgIds.length()))){
    		orgIds=orgIds.substring(0,orgIds.length()-1);
    	}
    	LOG.info("newOrgs："+orgIds);
		
		if(!StringUtil.isNotEmpty(openId)&&(dataType==0||dataType==2)&&StringUtils.isNotEmpty(orgIds)){
				//然后查询该项目下的用户(wxUserId存在的)
				//然后根据wxUserId获取wxUser,然后调用推送消息
				//获取有效的用户
				List<AppUser> appUserList=appUserManager.getWxUserByOrgIds(orgIds);
				if(appUserList!=null&&appUserList.size()>0){
					for(int i=0;i<appUserList.size();i++){
						AppUser appUser=appUserList.get(i);
						if(appUser!=null&&null!=appUser.getWxUserId()&&scWxuserManager.exists(appUser.getWxUserId())){
							Map<String, String> map=setMealListByOrgIds(appUser.getOrganizationId().toString());
							TbOrganization org=organizationManager.getOrganizationById(appUser.getOrganizationId());
							String orgName="";
							if(org!=null){
								orgName=org.getName();
							}else{
								orgName=appUser.getOrganizationName();
							}
							LOG.info("wechat  orgName:"+orgName);
							
							String time=orderDinnerManager.getOrderTimeStr(appUser.getOrganizationId().toString(),"orderTime");
							
							StringBuilder content=new StringBuilder(""+org.getName()+"服务之窗提醒您:\n“亲，今日已为您准备精美工作餐，将于"+time+"前截止预定，不要忘了订餐哦！”\n");
							if(!StringUtil.isNotEmpty(map.get("chuan"))&&!StringUtil.isNotEmpty(map.get("yue"))){
							}else{
								content.append("今日供应： \n");
								if(StringUtil.isNotEmpty(map.get("chuan"))){
									content.append("川菜："+map.get("chuan")+" \n");
								}
								if(StringUtil.isNotEmpty(map.get("yue"))){
									content.append("粤菜："+map.get("yue")+"\n");
								}
							}
							content.append("<a href='REURL' >点击查看更多美食</a>");
							WxUser wxUser=scWxuserManager.get(appUser.getWxUserId());
								if(wxUser==null){
									continue;
								}
								if(("test".equals(clientNo)||"dev".equals(clientNo))){
									if(appUser.getIsLeader()!=null&&appUser.getIsLeader().intValue()==1){
										LOG.info("wechat userId:"+appUser.getId());
										LOG.info("wechat wxUserId:"+wxUser.getId());
										LOG.info("wechat openId:"+wxUser.getOpenId());
										LOG.info("wechat isLeader:"+appUser.getIsLeader());
										try {
											TbOrganization tb=organizationManager.getOrganizationInfoByName("航空大厦");
											int tbId=0;
											if(tb!=null){
												tbId=tb.getId();
											}
											if(appUser.getOrganizationId().intValue()!=tbId&&"o4L9Qtw62YMCbJLomSJLpwJ9HeoU".equals(wxUser.getOpenId())){
												String url=host+wxDinnerUrl.replaceAll("@userId", appUser.getId().toString()).replaceAll("@openId", wxUser.getOpenId()).replaceAll("@orgId", appUser.getOrganizationId().toString());
												LOG.info("wechat url:"+url);
												String text=content.toString().replaceAll("REURL",url);
												String str=weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), text);
											}
										} catch (Exception e) {
											e.printStackTrace();
											LOG.error(e.getMessage());
										}
									}
								}else{//正式环境
									try {
										LOG.info("wechat userId:"+appUser.getId());
										LOG.info("wechat wxUserId:"+wxUser.getId());
										LOG.info("wechat openId:"+wxUser.getOpenId());
										TbOrganization tb=organizationManager.getOrganizationInfoByName("深圳航空大厦");
										int tbId=0;
										if(tb!=null){
											tbId=tb.getId();
										}
										if(appUser.getOrganizationId()!=null&&appUser.getOrganizationId().intValue()!=tbId){
											String url=host+wxDinnerUrl.replaceAll("@userId", appUser.getId().toString()).replaceAll("@openId", wxUser.getOpenId()).replaceAll("@orgId", appUser.getOrganizationId().toString());
											LOG.info("wechat url:"+url);
											String text=content.toString().replaceAll("REURL",url);
											LOG.info("开始推送:----------------begin-------------------------");
											String str=weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), text);
											LOG.info("开始推送:----------------end-------------------------:"+str);
										}
									} catch (Exception e) {
										e.printStackTrace();
										LOG.error(e.getMessage());
									}
								}
							}
					}
				} 
		}else{
			if(StringUtil.isNotEmpty(orgId)&&StringUtil.isNotEmpty(openId)){
				WxUser wxUser=scWxuserManager.getScWxuserByOpenId(openId);
				if(wxUser!=null){
					AppUser appUser=appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), Integer.parseInt(orgId));
					if(appUser!=null){
						Map<String, String> map=setMealListByOrgIds(appUser.getOrganizationId().toString());
						String url=host+wxDinnerUrl.replaceAll("@userId", appUser.getId().toString()).replaceAll("@openId", wxUser.getOpenId()).replaceAll("@orgId", appUser.getOrganizationId().toString());
						LOG.info("wechat url:"+url);
//						String chuan=baseRedisService.get(CodeConstants.ORG_MEAL_CHUAN+orgId);
//						String yue=baseRedisService.get(CodeConstants.ORG_MEAL_YUE+orgId);
						TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgId));
						String time=orderDinnerManager.getOrderTimeStr(appUser.getOrganizationId().toString(),"orderTime");
						StringBuilder content=new StringBuilder(""+org.getName()+"服务之窗提醒您:\n“亲，今日已为您准备精美工作餐，将于"+time+"前截止预定，不要忘了订餐哦！”\n");
						if(!StringUtil.isNotEmpty(map.get("chuan"))&&!StringUtil.isNotEmpty(map.get("yue"))){
						}else{
							content.append("今日供应： \n");
							if(StringUtil.isNotEmpty(map.get("chuan"))){
								content.append("川菜："+map.get("chuan")+" \n");
							}
							if(StringUtil.isNotEmpty(map.get("yue"))){
								content.append("粤菜："+map.get("yue")+"\n");
							}
						}
						content.append("<a href='"+url+"' >点击查看更多美食</a>");
						try {
							String orgName="";
							if("dev".equals(clientNo)||"test".equals(clientNo)){
								orgName="航空大厦";
							}else{
								orgName="深圳航空大厦";
							}
							TbOrganization tb=organizationManager.getOrganizationInfoByName(orgName);
							int tbId=0;
							if(tb!=null){
								tbId=tb.getId();
							}
							if(appUser.getOrganizationId().intValue()!=tbId){
								String str=weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(),content.toString());
								LOG.info("result:"+str);
							}
						} catch (Exception e) {
							e.printStackTrace();
							LOG.error(e.getMessage());
						}
						
					}
				}
			}
		}
	}
	
	
	private String getContent(String orgId,String openId,String userId){
		Map<String, String> map=setMealListByOrgIds(orgId);
		String time=orderDinnerManager.getOrderTimeStr(orgId,"orderTime");
		String url=host+wxDinnerUrl.replaceAll("@userId", userId).replaceAll("@openId", openId).replaceAll("@orgId", orgId);
		LOG.info("wechat url:"+url);
		TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgId));
		StringBuilder content=new StringBuilder(""+org.getName()+"服务之窗提醒您:\n“亲，今日已为您准备精美工作餐 ");
		if(StringUtil.isNotEmpty(time)){
			content.append(",将于"+time+"前截止预定");
		}
		content.append("，不要忘了订餐哦！”\n");
		if(!StringUtil.isNotEmpty(map.get("chuan"))&&!StringUtil.isNotEmpty(map.get("yue"))){
		}else{
			content.append("今日供应： \n");
			if(StringUtil.isNotEmpty(map.get("chuan"))){
				content.append("川菜："+map.get("chuan")+" \n");
			}
			if(StringUtil.isNotEmpty(map.get("yue"))){
				content.append("粤菜："+map.get("yue")+"\n");
			}
		}
		content.append("点击链接查看更多美食:"+url+" ");
		
		return content.toString();
	}
	
	private Map<String, String> setMealListByOrgIds(String orgIds){
		Map<String, String> map=new HashMap<String, String>();
		// 获取这些项目下所有的餐品
		List<Meal> mealList=mealManager.findMealList(orgIds);
		// 获取餐品的名字的id（数据字典换成项目级的时候，需要更改）
		// 先从项目级数据字典查询,查不到再从系统级数据字典取值
		String chuanId = "";
		String yueId = "";
		ElementDto chuan = elementGroupManager.getByItemname(orgIds, "mealName", "川菜");
		if (chuan == null){
			Element chuanEl=elementGroupManager.getByItemname("mealName", "川菜");
			chuanId = chuanEl.getId().toString();
		}else {
			chuanId = chuan.getId().toString();
		}

		ElementDto yue = elementGroupManager.getByItemname(orgIds, "mealName", "粤菜");
		if (yue == null){
			Element yueEl=elementGroupManager.getByItemname("mealName", "粤菜");
			yueId = yueEl.getId().toString();
		}else {
			yueId = yue.getId().toString();
		}

		//餐品列表不为空
		map.put("chuan", "");
		map.put("yue", "");
		if(mealList!=null&&mealList.size()>0){
			for(int i=0;i<mealList.size();i++){
				Meal meal=mealList.get(i);
				if(meal!=null){
//					if(chuanEl!=null){
						if(meal.getMealCodeId().equals(chuanId)){//当餐品名为川菜时
							map.put("chuan", meal.getMealDescribe());
						}
//					}
//					if(yueEl!=null){
						if(meal.getMealCodeId().equals(yueId)){//当餐品名为粤菜时
							map.put("yue", meal.getMealDescribe());
						}
//					}
				}
			}
		}
		return map;
	}
	@Transactional
	public void automaticRecharge() {
		String orgIds=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		LOG.info("----automaticRecharge-orgIds:"+orgIds+"----------------");
		Calendar cal=Calendar.getInstance();
		String day = sdf.format(cal.getTime());
		LOG.info("----automaticRecharge-day:"+day+"------------");
//		List<DateTypeInfo> list=dateTypeInfoManager.getDateTypeInfoList(String.valueOf(cal.get(Calendar.YEAR)), String.valueOf((cal.get(Calendar.MONTH) + 1)), "0,2");
		List<Map<String,Object>> list=dateTypeInfoManager.getWeekDateInfoList(day, "0,2");
		LOG.info("----automaticRecharge-list:"+JSONUtils.valueToString(list)+"----------------");
		if(StringUtil.isNotEmpty(orgIds)){
			String [] orgIdArr=orgIds.split(",");
			if(orgIdArr!=null&&orgIdArr.length>0){
				for(int i=0;i<orgIdArr.length;i++){
					String orgId=orgIdArr[i];
					//获取该项目下所配置的积分设置
					RechargeSet reSet=rechargeSetManager.findByOrgId(orgId);
					LOG.info("----automaticRecharge-reSet:"+JSONUtils.valueToString(reSet)+"----------------");
					if(reSet!=null&&reSet.getStatus()==1){//开启状态下才自动充值
						int dayCount=reSet.getDayCount()==null?0:reSet.getDayCount();//每天积分数
						if(list!=null&&list.size()>0){
							int monthCount=list.size();
							//每个项目每周一插入一条自动充值记录
							//int sumCount=dayCount*monthCount;
							int sumCount = 500;//新增每月21日00:00:00清零账户并充值500积分
							RechargeRecord rr=new RechargeRecord(orgId,new Date(),monthCount,sumCount,dayCount);
							rechargeRecordManager.save(rr);
							//保存个人积分
							saveAppUserByRecharge(orgId, sumCount);
						}
					}
				}
			}
		}
	}
	@Transactional
	public void saveAppUserByRecharge(String orgId,int sumCount){
		//获取该项目下所有有效的人员
		List<AppUser> list=appUserManager.getAppUserByOrgId(Integer.parseInt(orgId));
		if(list!=null&&list.size()>0){
			//给这些有效的人员充值
			for(int i=0;i<list.size();i++){
				AppUser user=list.get(i);
				if(user!=null){
					
					if(user.getIntegral()>0){
						IntegralRecodeInfo intRecodeSys=new IntegralRecodeInfo("-1",5,user.getUserName(),user.getUserMobile(),user.getIntegral(),0,new Date(),"-"+user.getIntegral(),orgId,user.getId().toString());
				    	integralRecodeInfoManager.save(intRecodeSys);
					}

					
					
					IntegralRecodeInfo intRecode=new IntegralRecodeInfo("-1",1,user.getUserName(),user.getUserMobile(),user.getIntegral(),sumCount,new Date(),String.valueOf(sumCount),orgId,user.getId().toString());
			    	integralRecodeInfoManager.save(intRecode);
					user.setIntegral(sumCount);
					appUserManager.saveOrUpdateAppUser(user);
				}
			}
		}
	}
	
	@Override
	public AppResultDto getRechargeSetRecode(String orgId) {
		RechargeSetRecordDto dto=new RechargeSetRecordDto();
		RechargeSetDto reSetDto=getRechargeSetDto(orgId);
		if(reSetDto!=null){
			dto.setReSetDto(reSetDto);
			List<RechargeRecordDto> recordList=rechargeRecordManager.findByOrgId(orgId);
			if(recordList!=null&&recordList.size()>0){
				dto.setRecordList(recordList);
			}
			return AppResultUtil.createSuccesDto(dto);
		}
		return AppResultUtil.createSuccesDto();
	}

	@Override
	public AppResultDto getPushSet(Integer orgId) {
		OrderDinnerSet set = orderDinnerSetManager.findByOrgId(orgId);
		if(null == set){
			set = new OrderDinnerSet();
			set.setStatus("1");
			set.setOrgId(orgId);
			return AppResultUtil.createSuccesDto(set);
		}
		return AppResultUtil.createSuccesDto(set);
	}

	@Override
	public AppResultDto getPushSetByUserId(Integer userId) {
		AppUser user = appUserManager.get(userId);
		OrderDinnerSet set = new OrderDinnerSet();
		set.setUserId(userId);
		if(null == user || null == user.getIsPushState()){
			set.setStatus("1");
		}else{
			set.setStatus(user.getIsPushState());
		}
		return AppResultUtil.createSuccesDto(set);
	}

	@Override
	public RechargeSetDto getRechargeSetDto(String orgId) {
		//获取该项目下所配置的积分设置
		RechargeSet reSet=rechargeSetManager.findByOrgId(orgId);
		if(reSet!=null){
			RechargeSetDto dto=new RechargeSetDto(orgId,reSet.getStatus(),reSet.getDayCount());
			dto.setId(reSet.getId().toString());
			return dto;
		}
		return null;
	}
	@Override
	public AppResultDto saveAndRechargeSet(String userId,
			RechargeSetDto reSetDto) {
		RechargeSet reSet=new RechargeSet();
		try {
			
			if(reSetDto!=null&&StringUtil.isNotEmpty(reSetDto.getId())){
				if(rechargeSetManager.exists(Long.parseLong(reSetDto.getId()))){
					reSet=rechargeSetManager.get(Long.parseLong(reSetDto.getId()));
					reSet.setModifier(userId);
				}
			}else{
				reSet.setOrgId(reSetDto.getOrgId());
				reSet.setCreator(userId);
			}
			reSet.setDayCount(reSetDto.getDayCount());
			reSet.setStatus(reSetDto.getStatus());
			if(reSet!=null){
				rechargeSetManager.saveAndUpdateReSet(reSet);
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
		    LOG.error(e.getMessage());
		    e.printStackTrace();
		    return AppResultUtil.createErrorDto("100", "保存失败");
		}
	}

	@Override
	public AppResultDto saveAndPushSet(DinnerPushSetVo reSetDto) {
		if(StringUtils.isEmpty(reSetDto.getStatus())){
			reSetDto.setStatus("1");
		}
		try {
			if(null != reSetDto.getOrgId()){
				OrderDinnerSet set = orderDinnerSetManager.findByOrgId(reSetDto.getOrgId());
				if(null == set){
					set = new OrderDinnerSet();
					set.setOrgId(reSetDto.getOrgId());
					set.setStatus(reSetDto.getStatus());
					orderDinnerSetManager.save(set);
				}else{
					set.setStatus(reSetDto.getStatus());
					orderDinnerSetManager.updateModel(set);
				}
			}else if(null != reSetDto.getUserId()){
				AppUser user = appUserManager.get(reSetDto.getUserId());
				if(null != user){
					user.setIsPushState(reSetDto.getStatus());
					appUserManager.updateModel(user);
				}
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "保存失败");
		}
	}

	@Override
	public void updateOrderDinner() {
		//获取使用订餐的项目
		String orgIds=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		LOG.info("updateOrderDinner/orgIds:"+orgIds);
		//获取当前时间：年-月-日
		String time=sdf.format(new Date());
		LOG.info("updateOrderDinner/time:"+time);
		//修改订单
		int count=orderDinnerManager.updateOrderDinnerByTime(orgIds, time);
		LOG.info("updateOrderDinner/count:"+count);
	}
	
	@Transactional
	public AppResultDto updateAppUserByUserIds(String orgId,Integer integral,String userIds,String userId) {
		//首先根据userIds获取所有用户的信息，记录到操作表中
		try {
			String [] str=userIds.split(",");
			if(str!=null&&str.length>0){
				for(int i=0;i<str.length;i++){
					if(appUserManager.exists(Integer.parseInt(str[i]))){
						AppUser appUser=appUserManager.get(Integer.parseInt(str[i]));
						if(appUser!=null){
							int sumInt=appUser.getIntegral()+integral;
							IntegralRecodeInfo intRecode=new IntegralRecodeInfo(userId,1,appUser.getUserName(),appUser.getUserMobile(),appUser.getIntegral(),sumInt,new Date(),String.valueOf(integral),orgId,appUser.getId().toString());
					    	integralRecodeInfoManager.save(intRecode);
							appUser.setModifier(userId);
							appUser.setModifyTime(new Date());
							appUser.setIntegral(sumInt);
							appUserManager.saveOrUpdateAppUser(appUser);
						}
					}
				}
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			throw new RuntimeException("批量充值失败:"+e.getMessage());
		}
	}
	@Override
	public AppResultDto getIntegralByOrgId(String orgId) {
		RechargeSet reSet=rechargeSetManager.findByOrgId(orgId);
		if(reSet==null){
			 return AppResultUtil.createErrorDto("100", "该项目下未设置每日积分");
		}
		return AppResultUtil.createSuccesDto(reSet.getDayCount());
	}
	
	@Override
	public void sendMessage() {
		String orgIds=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		List<Map<String, Object>> mapList=userManager.getPowerByOrgIds(orgIds,Integer.parseInt(CodeConstants.DINNER_MANAGER));
		String mobiles="";
		try {
			if(mapList!=null&&mapList.size()>0){
				for(int i=0;i<mapList.size();i++){
					Map<String, Object> map=mapList.get(i);
					if(map.containsKey("userTel")){
						String mobile=map.get("userTel")==null?"":map.get("userTel").toString();
						if(StringUtil.isNotEmpty(mobile)){
							mobiles=mobiles+mobile+",";
						}
					}
				}
			}
			if(StringUtil.isNotEmpty(mobiles)){
				//发送短信
				if(StringUtil.isNotEmpty(orgIds)){
					String[] orgIdArr=orgIds.split(",");
					if(orgIdArr!=null&&orgIdArr.length>0){
						for(int i=0;i<orgIdArr.length;i++){
							if(orgIdArr.length>1){
								mobiles=mobiles.substring(0,mobiles.length()-1);
							}
							LOG.info("发送短信号码："+mobiles);
							String result = smsAuthCodeManager.smsSendByOrgId(orgIdArr[i],"尊敬的餐品管理员，请及时更新下周的餐品信息，以免影响订餐服务的正常使用！",mobiles,"",CodeConstants.SMS_DINNER_TYPE);
							LOG.info("isMessage："+result);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("发送短信失败："+e.getMessage());
		}
	}
	
	@Override
	public void cleanRedisByOrgIds() {
		String orgIds=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		if(StringUtil.isNotEmpty(orgIds)){
			String[] orgIdArr=orgIds.split(",");
			if(orgIdArr!=null&&orgIdArr.length>0){
				for(int i=0;i<orgIdArr.length;i++){
					String orgId=orgIdArr[i];
					if(StringUtil.isNotEmpty(orgId)){
						baseRedisService.dele(CodeConstants.ORG_MEAL_LIST_KEY+orgId);
						LOG.info("orgId:"+orgId+"该项目下清理缓存成功!");
					}
				}
			}
		}
	}
	@Override
	public int getTempOpen(String orgId) {
		int open=0;
		try {
			List<ElementDto> dtoList=elementGroupManager.getOrgElementGroupInfo(Integer.parseInt(orgId), "tempOpen");
			if(dtoList!=null&&dtoList.size()>0){
				ElementDto el=dtoList.get(0);
				if(el!=null){
					open=Integer.parseInt(el.getItemname());
				}
			}
		} catch (Exception e) {
			open=0;
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return open;
	}
	/**
     * 获取订餐统计信息
     * @param orgId
     * @param dateType
     * @param date
     * @param endDate
     * @return
     */
	@Override
	public WebPageResultDto getDinnerDateByInfo(String orgId, int dateType,
			String date, String endDate,int pageSize,int pageNo) {
		//定义最终返回的集合
		List<Map<String,Object>> mapList=getStatisticsDinnerByInfo(orgId, dateType, date, endDate);
		//分页
		WebPageResultDto dto=new WebPageResultDto("200","成功",null);
		if(mapList!=null&&mapList.size()>0){
			ListPage page=PageUtils.getListPage(mapList, pageNo, pageSize);
			dto.setCount(Long.parseLong(String.valueOf(mapList.size())));
			dto.setData(page.getDataList());
		}else{
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}
	/**
	 * 封装查询到的订餐总数、普通订餐数、临时工作餐数、会议餐数
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	public List<Map<String,Object>> getStatisticsDinnerByInfo(String orgIds, int dateType,
			String date, String endDate){
		List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> sumCountList=orderDinnerManager.getDinnerDataByInfo(orgIds, dateType, date, endDate);
		if(sumCountList!=null&&sumCountList.size()>0){
			String dateString=StringUtil.getDateString(dateType, date, endDate,1);
			Map<String,Object> sumMap=new HashMap<String, Object>();
			int sumCount=0;
			int sumMeetCount=0;
			int sumtTempCount=0;
			int sumOrdinaryCount=0;
			for(int i=0;i<sumCountList.size();i++) {
				Map<String, Object> map = sumCountList.get(i);
				if (map != null && map.containsKey("count") && Integer.parseInt(map.get("count") == null ? "0" : map.get("count").toString()) > 0) {
					map.put("dateInfo", dateString);
					int count = Integer.parseInt(map.get("count") == null ? "0" : map.get("count").toString());
					int meetCount = Integer.parseInt(map.get("meetCount") == null ? "0" : map.get("meetCount").toString());
					int tempCount = Integer.parseInt(map.get("tempCount") == null ? "0" : map.get("tempCount").toString());
					int ordinaryCount = Integer.parseInt(map.get("ordinaryCount") == null ? "0" : map.get("ordinaryCount").toString());
					sumCount = sumCount + count;
					sumMeetCount = sumMeetCount + meetCount;
					sumtTempCount = sumtTempCount + tempCount;
					sumOrdinaryCount = sumOrdinaryCount + ordinaryCount;
					map.put("orderno", (i + 1));
					mapList.add(map);
				}
			}
			sumMap.put("dateInfo", dateString);
			sumMap.put("orgName","总计");
			sumMap.put("count",sumCount);
			sumMap.put("meetCount",sumMeetCount);
			sumMap.put("tempCount",sumtTempCount);
			sumMap.put("ordinaryCount",sumOrdinaryCount);
			sumMap.put("orderno",0);
			mapList.add(sumMap);
			//排序
			Collections.sort(mapList,new Comparator<Map<String,Object>>() {
				public int compare(Map<String,Object> o1, Map<String,Object> o2) {
					if(null==o1.get("orderno")){
						o1.put("orderno", 9999);
					}
					if(null==o2.get("orderno")){
						o2.put("orderno", 9999);
					}
					Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
					Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
	                return name1.compareTo(name2);    
	        }  
			});
		}
		return mapList;
	}

	
	
	/**
	 * 导出订餐统计报表
	 */
	@Override
	public AppResultDto exportDinnerStatistics(String orgId, Integer dateType,
			String date, String endDate) {
		LOG.info("begin exportDinnerStatistics/orgId:"+orgId+"/dateType:"+dateType+"/date:"+date+"/endDate:"+endDate);
		HSSFWorkbook wb = new HSSFWorkbook();
		List<Map<String,Object>> mapList=getStatisticsDinnerByInfo(orgId, dateType, date, endDate);
		String path=orderDinnerService.setPath("upload/DinnerDataExcel.xls");
		LOG.info("begin exportDinnerStatistics/path:"+path);
		try {
			if(mapList!=null&&mapList.size()>0){
				String sheetName="订餐统计";
				File file =new File( new ExcelUtils().getPath(path));
				String[] titles={"序号","项目","统计时间","订餐总数","普通订餐","临时工作餐","会议餐"};
				String [] fieldNames={"orderno","orgName","dateInfo","count","ordinaryCount","tempCount","meetCount"};
				ExcelUtils.exportExcel(file,wb, sheetName, mapList, titles, fieldNames);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出异常");
		}
		return AppResultUtil.createSuccesDto(path);
	}
	/**
	 *  通行统计
	 */
	@Override
	public WebPageResultDto getVisitorDateByInfo(String orgId, int dateType,
			String date, String endDate, int pageSize, int pageNo) {
		//定义最终返回的集合
		List<VisitorStatisticsDto> mapList=getStatisticsVisitorByInfo(orgId, dateType, date, endDate);
		//分页
		WebPageResultDto dto=new WebPageResultDto("200","成功",null);
		if(mapList!=null&&mapList.size()>0){
			ListPage page=PageUtils.getListPage(mapList, pageNo, pageSize);
			dto.setCount(Long.parseLong(String.valueOf(mapList.size())));
			dto.setData(page.getDataList());
		}else{
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}
	/**
	 * 导出通行统计报表
	 */
	@Override
	public AppResultDto exportVisitorStatistics(String orgId, Integer dateType,
			String date, String endDate) {
		LOG.info("begin exportVisitorStatistics/orgId:"+orgId+"/dateType:"+dateType+"/date:"+date+"/endDate:"+endDate);
		HSSFWorkbook wb = new HSSFWorkbook();
		List<VisitorStatisticsDto> mapList=getStatisticsVisitorByInfo(orgId, dateType, date, endDate);
		//int sum = mapList.stream().mapToInt(VisitorStatisticsDto::getCount).sum();
		//System.out.println(sum);
		String path=orderDinnerService.setPath("upload/VisitorDataExcel.xls");
		LOG.info("begin exportVisitorStatistics/path"+path);
		try {
			if(mapList!=null&&mapList.size()>0){
				String sheetName="访客统计";
				File file =new File( new ExcelUtils().getPath(path));
				String[] titles={"序号","项目","统计时间","通行次数","员工通行次数","访客通行次数","二维码通行次数","实体卡通行次数"};
				String [] fieldNames={"orderno","orgName","dateInfo","count","userCount","visitorCount","QRcodeCount","entityCardCount"};
				ExcelUtils.exportExcel(file,wb, sheetName, mapList, titles, fieldNames);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出异常");
		}
		return AppResultUtil.createSuccesDto(path);
	}
	
	/**
	 * 封装查询到的通行次数、员工通行次数、访客通行次数、二维码通行次数、实体卡通行次数
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	public List<VisitorStatisticsDto> getStatisticsVisitorByInfo(String orgIds, int dateType,
			String date, String endDate){
		List<VisitorStatisticsDto> mapList=new ArrayList<VisitorStatisticsDto>();
		List<Map<String, Object>> sumCountList=orderDinnerManager.getVisitorDataByInfo(orgIds, dateType, date, endDate);
		if(sumCountList!=null&&sumCountList.size()>0){
			String dateString=StringUtil.getDateString(dateType, date, endDate,1);
			int sumCount=0;
			int sumUserCount=0;
			int sumVisitorCount=0;
			int sumQRcodeCount=0;
			int sumEntityCount=0;
			for(int i=0;i<sumCountList.size();i++){
				Map<String, Object> map=sumCountList.get(i);
				if(map!=null&&map.containsKey("count")&&Integer.parseInt(map.get("count")==null?"0":map.get("count").toString())>0){
					int count=Integer.parseInt(map.get("count")==null?"0":map.get("count").toString());
					int userCount=Integer.parseInt(map.get("userCount")==null?"0":map.get("userCount").toString());
					int visitorCount=Integer.parseInt(map.get("visitorCount")==null?"0":map.get("visitorCount").toString());
					int QRcodeCount=Integer.parseInt(map.get("QRcodeCount")==null?"0":map.get("QRcodeCount").toString());
					int entityCardCount=Integer.parseInt(map.get("entityCardCount")==null?"0":map.get("entityCardCount").toString());
					sumCount=sumCount+count;
					sumUserCount=sumUserCount+userCount;
					sumVisitorCount=sumVisitorCount+visitorCount;
					sumQRcodeCount=sumQRcodeCount+QRcodeCount;
					sumEntityCount=sumEntityCount+entityCardCount;
					VisitorStatisticsDto dto=new VisitorStatisticsDto();
					String orgName=map.get("orgName")==null?"":map.get("orgName").toString();
					dto.setOrgName(orgName);
					dto.setDateInfo(dateString);
					dto.setCount(count);
					dto.setUserCount(userCount);
					dto.setVisitorCount(visitorCount);
					dto.setQRcodeCount(QRcodeCount);
					dto.setEntityCardCount(entityCardCount);
					dto.setOrderno((i+1));
					mapList.add(dto);
				}
			}
			if(mapList!=null&&mapList.size()>0){

				VisitorStatisticsDto dto=new VisitorStatisticsDto();
				dto.setOrgName("合计");
				dto.setDateInfo(dateString);
				dto.setCount(sumCount);
				dto.setUserCount(sumUserCount);
				dto.setVisitorCount(sumVisitorCount);
				dto.setQRcodeCount(sumQRcodeCount);
				dto.setEntityCardCount(sumEntityCount);
				dto.setOrderno(0);
				mapList.add(dto);
				//排序
				Collections.sort(mapList,new Comparator<VisitorStatisticsDto>() {
					public int compare(VisitorStatisticsDto o1, VisitorStatisticsDto o2) {  
						Integer name1 =o1.getOrderno();//name1是从你list里面拿出来的一个  
						Integer name2= o2.getOrderno();//name1是从你list里面拿出来的第二个name      
		                return name1.compareTo(name2);    
		        }  
				});
			}
		}
		return mapList;
	}
	@Override
	public WebPageResultDto getPlatformDataByInfo(String orgId, int dateType,
			String date, String endDate, int pageSize, int pageNo) {
		String dateString=StringUtil.getDateString(dateType, date, endDate,1);
		List<Map<String, Object>> mapList=getPlatDataList(orgId, dateType, date, endDate,dateString);
		//分页
		WebPageResultDto dto=new WebPageResultDto("200","成功",null);
		if(mapList!=null&&mapList.size()>0){
			ListPage page=PageUtils.getListPage(mapList, pageNo, pageSize);
			dto.setCount(Long.parseLong(String.valueOf(mapList.size())));
			dto.setData(page.getDataList());
		}else{
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}
	/**
	 * 添加总计行且排个序
	 * @param platList
	 * @param dateString
	 */
	private void addSumPlatform(List<Map<String, Object>> platList,String dateString){
		if(platList!=null&&platList.size()>0){
			String [] titles={"userSumCount","enUserCount","userCount","total","dcfw","dinnerCount"
					,"hys","meetCount","zhfk","lingCount","dzfxt","goodsCount","ktjs"
					,"airAddTimeCount","qyrz","enterCount","qyqc","emigCount","ggzx","activeCount","virtSumCount","virtCount","gcwx","repairUseCount"};
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("orgName", "合计");
			map.put("dateInfo", dateString);
			map.put("orderno", 0);
			map.put("accountTypeStr", "");
			for(int j=0;j<titles.length;j++){
				int sumCount=0;
				String title=titles[j];
				for(int i=0;i<platList.size();i++){
					Map<String,Object> platMap=platList.get(i);
					//有效用户数
					BigDecimal userSumCount=new BigDecimal(platMap.get("enUserCount")==null?"0":platMap.get("enUserCount").toString());
					if(BigDecimal.ZERO.compareTo(userSumCount)==-1){
						//用户活跃
						BigDecimal activeCount=new BigDecimal(platMap.get("activeCount")==null?"0":platMap.get("activeCount").toString());
						BigDecimal rate=activeCount.divide(userSumCount,6, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
						platMap.put("activeCountRate", rate);
					}
					
					sumCount=setAdd(platMap, title, sumCount);
				}
				map.put(title, sumCount);
			}
			
			//总用户数
			BigDecimal userSumCount=new BigDecimal(map.get("enUserCount")==null?"0":map.get("enUserCount").toString());
			if(BigDecimal.ZERO.compareTo(userSumCount)==-1){
				//用户活跃
				BigDecimal activeCount=new BigDecimal(map.get("activeCount")==null?"0":map.get("activeCount").toString());
				BigDecimal rate=activeCount.divide(userSumCount,6, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
				map.put("activeCountRate", rate);
			}
			platList.add(map);
			//排序
			Collections.sort(platList,new Comparator<Map<String,Object>>() {
				public int compare(Map<String,Object> o1, Map<String,Object> o2) {  
					if(null==o1.get("orderno")){
    					o1.put("orderno", 9999);
    				}
    				if(null==o2.get("orderno")){
    					o2.put("orderno", 9999);
    				}
					Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
					Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
	                return name1.compareTo(name2);    
	        }  
			});
		}
	}
	
	private List<Map<String,Object>> getPlatDataList(String orgId, int dateType,String date, String endDate,String dateString){
		List<Map<String, Object>> platList=orderDinnerManager.getPlatformDataByInfo(orgId, dateType, date, endDate,dateString);
		addSumPlatform(platList, dateString);
		return platList;
	}
	/**
	 * 累计每个值的数
	 * @param map
	 * @param title
	 * @param sumCount
	 */
	private int setAdd(Map<String,Object> map,String title,int sumCount){
		if(map!=null&&map.containsKey(title)&&map.get(title)!=null){
			int count=Integer.parseInt(map.get(title).toString());
			sumCount=sumCount+count;
		}
		return sumCount;
	}
	
	@Override
	public AppResultDto exportPlatformStatistics(String orgId,
			Integer dateType, String date, String endDate) {
		LOG.info("begin exportPlatformStatistics/orgId:"+orgId+"/dateType:"+dateType+"/date:"+date+"/endDate:"+endDate);
		HSSFWorkbook wb = new HSSFWorkbook();
		String dateString=StringUtil.getDateString(dateType, date, endDate,1);
		List<Map<String, Object>> platList=getPlatDataList(orgId, dateType, date, endDate,dateString);
		String path=orderDinnerService.setPath("upload/PlatformDataExcel.xls");
		LOG.info("begin exportPlatformStatistics/path"+path);
		try {
			if(platList!=null&&platList.size()>0){
				String sheetName="平台统计";
				File file =new File( new ExcelUtils().getPath(path));
				String[] titles={"序号","项目","账号类型","统计时间","用户总数","有效总用户","新增用户","平台活跃","企业总数","新增企业","用户活跃","用户活跃率","订餐服务活跃","订餐服务使用数"
						,"预订会议室活跃数","预订会议室使用数","通行活跃数","通行使用数","电子放行条活跃数","电子放行条使用数"
						,"空调加时活跃度","空调加时使用数","企业入驻活跃数","企业入驻使用数","企业迁出活跃数","企业迁出使用数","公告活跃数","工程维修使用数","工程维修活跃数"};
				String [] fieldNames={"orderno","orgName","accountTypeStr","dateInfo","userSumCount","enUserCount","userCount","total","virtSumCount","virtCount","activeCount","activeCountRate","dcfw","dinnerCount","hys"
						,"meetCount","zhfk","lingCount","dzfxt","goodsCount","ktjs","airAddTimeCount","qyrz","enterCount","qyqc","emigCount","ggzx","repairUseCount","gcwx"};
				ExcelUtils.exportExcel(file,wb, sheetName, platList, titles, fieldNames);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出异常");
		}
		return AppResultUtil.createSuccesDto(path);
	}
	
	@Override
	public AppResultDto exportMeetStatistics(String orgId, Integer dateType,
			String date, String endDate) {
		LOG.info("begin exportMeetStatistics/orgId:"+orgId+"/dateType:"+dateType+"/date:"+date+"/endDate:"+endDate);
		HSSFWorkbook wb = new HSSFWorkbook();
		List<MeetintDto> mapList=orderDinnerManager.getMeetingInfoList(orgId, dateType, date, endDate);
		String path=orderDinnerService.setPath("upload/MeetingDataExcel.xls");
		LOG.info("begin exportMeetStatistics/path"+path);
		try {
			if(mapList!=null&&mapList.size()>0){
				String sheetName="会议室统计";
				File file =new File( new ExcelUtils().getPath(path));
				String[] titles={"序号","项目","统计时间","预订会议室次数(次)","使用时长(小时)","预订会议室费用(元)","减免时长使用数(小时)","减免时长扣减费用(小时)","附件服务费用(元)","费用总计(元)"};
				String [] fieldNames={"orderno","orgName","dateInfo","reportnum","usetime","usemoney","freenum","freemoney","servicesmoney","totalamount"};
				ExcelUtils.exportExcel(file,wb, sheetName, mapList, titles, fieldNames);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出异常");
		}
		return AppResultUtil.createSuccesDto(path);
	}
	
	@Override
	public String setPath(String fileName) {
		return orderDinnerService.setPath(fileName);
	}
    /**
     * 设置项目的是否开启短信提醒
     * @param orgId
     * @param isSetMessage
     * @return
     */
	@Override
	public AppResultDto setOrgByMessage(String orgId, Integer isSetMessage,Integer isSetWechatMessage) {
		try {
			TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgId));
			if(org!=null){
				if(isSetMessage==null){
					isSetMessage=0;
				}
				org.setIsSetMessage(isSetMessage);
				if(null==isSetWechatMessage){
					isSetWechatMessage=1;
				}
				org.setIsSetWechatMessage(isSetWechatMessage);
				propertyManager.updateModel(org);
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			LOG.error("设置项目的短信提醒失败:"+e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "设置失败");
		}
		
	}

	@Override
	public void sendTempMsg(String openId, String orgId,String date) {
		String nextDate = "";
		if(StringUtils.isEmpty(date)){
			date =  DateHelper.formatDate(new Date(),DateHelper.CURRENT_DATE);
		}

		String tomorrow = DateHelper.getNextDay(date,DateHelper.CURRENT_DATE);
		LOG.info("sendTempMsg/tomorrow:"+tomorrow);

		String orgIds="";

		if(StringUtils.isNotEmpty(orgId)){
			orgIds = orgId;
			OrderDinnerSet orderDinnerSet = orderDinnerSetManager.findByOrgId(Integer.parseInt(orgId));
			if(null != orderDinnerSet && "0".equals(orderDinnerSet.getStatus())){
				LOG.info("sendTempMsg orgId:"+orgId +";该项目未开启订餐提醒，不推送");
				return;
			}
		}else{
			String newOrgs=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
			LOG.info("sendTempMsg/orgIds:"+newOrgs);
			String[] orgArr=newOrgs.split(",");
			//获取设置了微信提醒的项目

			if(null == orgArr || orgArr.length == 0){
				return;
			}
			for(int i=0;i<orgArr.length;i++){
				Integer org = Integer.parseInt(orgArr[i]);
				OrderDinnerSet orderDinnerSet = orderDinnerSetManager.findByOrgId(org);
				if(null != orderDinnerSet && "0".equals(orderDinnerSet.getStatus())){
					continue;
				}
				//获取下一个上了餐的日期：需要判断日期是否为明天，如果是明天，今天才做推送，如果不是明天，不做推送
				LOG.info("begin sendTempMsg-:" + org+";date:"+date);
				nextDate = mealManager.getNextMealDate(org,date,1);
				LOG.info("begin sendTempMsg-:" + org+";date:"+date+";nextDate:"+nextDate);
				if(StringUtils.isEmpty(nextDate)){
					nextDate = date;
					LOG.info("begin sendTempMsg-:" + org+";date:"+date+";nextDate2:"+nextDate);
				}
				if(!tomorrow.equals(nextDate)){
					continue;
				}

				if(null == orderDinnerSet || StringUtils.isEmpty(orderDinnerSet.getStatus())){
					orgIds = orgIds+org+",";
				}else if("1".equals(orderDinnerSet.getStatus())){
					orgIds = orgIds+org+",";
				}
			}
			LOG.info("sendTempMsg-newOrgs："+orgIds);
			if(StringUtils.isNotEmpty(orgIds)&&",".equals(orgIds.substring(orgIds.length()-1,orgIds.length()))){
				orgIds=orgIds.substring(0,orgIds.length()-1);
			}
		}
		LOG.info("sendTempMsg-newOrgs:上线了订餐服务且开启了订餐提醒的项目:"+orgIds);

		//根据项目列表获取所有开启了订餐提醒的用户
		String content = "您好，请及时预定明天的餐品，马上要截止订餐了！";
		String url="";

		if(StringUtils.isEmpty(orgIds)){
			return;
		}
		//获取项目下允许订餐推送的用户
		Map<Integer,String> resMap = orderDinnerSetManager.findUserByOrgIds(orgIds,openId);
		for (Integer org : resMap.keySet()){
			String userIds = resMap.get(org);
			tempMsg(org,userIds,content,url,tomorrow);
		}
	}

	private void tempMsg(Integer org,String userIds,String content,String url,String date){
		WxPublicno no = wxPubManager.getPublicByOrgId(org.toString());
		if(null == no){
			tempMsg1(org,userIds,content,url);//基础推送，平台推送，积余不需要这个模板，换
		}else{
			//根据公众号id获取模板信息
			WxMessageConfigVo vo = smsAuthCodeManager.getWxMessageConfig(no.getId(),CodeConstants.BOOK_DINNER_TASK);
			LOG.info("tempMsg-vo:"+JsonUtils.toJson(vo));
			if(null == vo){
				tempMsg1(org,userIds,content,url);//基础推送，平台推送，积余不需要这个模板，换
			}else{
				tempMsg2(org,userIds,url,vo,date);//模板库发送
			}
		}
	}

	public String sendMessageTemp(WechatMessageDto dto) {
		LOG.info("sendMessageTemp-dto:"+JsonUtils.toJson(dto));
		if(null == dto || null == dto.getOrgId() || null == dto.getType() || StringUtils.isEmpty(dto.getBusinessCode())){
			return "参数为空";
		}
		if(StringUtils.isEmpty(wxTempUrl)){
			return "模板库推送模板地址为空，无法发送";
		}
		LOG.info("======>模板推送-sendMessageTemp-wxTempUrl:"+wxTempUrl);
		String params=JSONObject.toJSONString(dto);
		LOG.info("======>模板推送-sendMessageTemp-params:"+params);
		String result=HttpKit.HttpClientPost(params,wxTempUrl);
		LOG.info("======>模板推送-sendMessageTemp-result:"+result);
		return result;
	}

	private void tempMsg2(Integer org,String userIds,String url,WxMessageConfigVo vo,String date){
		Map<String,String> paramMap=new HashMap<String, String>();
		paramMap.put("[PARAM_URL]", url);
		paramMap.put("[PARAM_DATE]", date);
		WechatMessageDto msgDto=new WechatMessageDto();
		msgDto.setOrgId(org);
		msgDto.setBusinessCode(vo.getBusinessCode());
		msgDto.setParamMap(paramMap);
		msgDto.setType(vo.getType());
		msgDto.setUserIds(userIds);
		sendMessageTemp(msgDto);
	}

	private void tempMsg1(Integer org,String userIds,String content,String url){
		Map<String,Object> map=new HashMap<>();
		map.put("orgId",org);
		map.put("userIds",userIds.split(","));
		map.put("content",content);
		map.put("url",url);
		String params=com.alibaba.fastjson.JSONObject.toJSONString(map);
		LOG.info("sendTempMsg params===>"+  params);
		LOG.info("sendTempMsg wxMessageUrl===>"+  wxMessageUrl);
		String result=HttpKit.HttpClientPost(params,wxMessageUrl);
		LOG.info("sendTempMsg result===>"+  JsonUtils.toJson(result));
	}

	@Override
	public void sendMessageByOrgSet(String orgId,String mobile) {
		Calendar calendar = Calendar.getInstance();    
        calendar.add(Calendar.DATE, -1);
        System.out.println("前一天的日期："+calendar.getTime());
        LOG.info("前一天的日期："+calendar.getTime());
		//首先获取某个服务下的项目
		String orgIds=serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
		LOG.info("sendMessageByOrgSet/orgIds:"+orgIds);
        String[] orgArr=orgIds.split(",");
        int tbId=0;
        try {
        	//正常工作日对应结果为 0, 法定节假日对应结果为 1, 节假日调休补班对应的结果为 2，休息日对应结果为 3 
	        int upDataType=-1;
	   		int dataType=-1;
	   		LOG.info("前一天的日期："+sdf.format(calendar.getTime())+";今天日期："+sdf.format(new Date()));
        	DateTypeInfo lastDay=dateTypeInfoManager.getDateTypeInfoList(sdf.format(calendar.getTime()));
        	if(lastDay!=null){
        		upDataType=lastDay.getType();
        	}
        	DateTypeInfo nowDay=dateTypeInfoManager.getDateTypeInfoList(sdf.format(new Date()));
        	if(nowDay!=null){
        		dataType=nowDay.getType();
        	}
	   		System.out.println("upDataType："+upDataType+";dataType:"+dataType);
	   		LOG.info("sendMessageByOrgSet/upDataType："+upDataType+";dataType:"+dataType);
	   		boolean upBool=(upDataType==1||upDataType==3);
	   		boolean bool=(dataType==0||dataType==2);
	   		LOG.info("sendMessageByOrgSet/前一天是否节假日或休息日/upBool："+upBool+";今天是否为工作日或者补班日/bool:"+bool);
        	//开发环境或者接口调用时跑这段代码
        	if((StringUtil.isNotEmpty(orgId)&&StringUtil.isNotEmpty(mobile))||"dev".equals(clientNo)){
        		if(upBool&&bool){
        			if(!StringUtil.isNotEmpty(orgId)||!StringUtil.isNotEmpty(mobile)){
        				orgId="605";
        				mobile="13423994033";
        			}
        			TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgId));
   					AppUser appUser=appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));
   					if(appUser!=null&&scWxuserManager.exists(appUser.getWxUserId())&&StringUtil.isNotEmpty(appUser.getUserMobile())&&org.getIsSetMessage()==1){
   						WxUser wxUser=scWxuserManager.get(appUser.getWxUserId());
   						String content=getContent(appUser.getOrganizationId().toString(), wxUser.getOpenId(), appUser.getId().toString());
   						LOG.info("sendMessageByOrgSet/content："+content);
   						LOG.info("sendMessageByOrgSet/发送短信号码："+appUser.getUserMobile());
						String result = smsAuthCodeManager.smsSendByOrgId(appUser.getOrganizationId().toString(),content,appUser.getUserMobile(),"",CodeConstants.SMS_DINNER_TYPE);
						LOG.info("sendMessageByOrgSet/isMessage："+result);
   					}
        		}
        	}else if("test".equals(clientNo)||"formal".equals(clientNo)){
        		//测试环境和正式环境跑这段代码
            	if("test".equals(clientNo)){
            		TbOrganization tb=organizationManager.getOrganizationInfoByName("航空大厦");
                	if(tb!=null){
            			tbId=tb.getId();
            		}
            	}else{
            		TbOrganization tb=organizationManager.getOrganizationInfoByName("深圳航空大厦");
                	if(tb!=null){
            			tbId=tb.getId();
            		}
            	}
            	//获取设置了短信提醒的项目
                String newOrgs="";
            	if(orgArr!=null&&orgArr.length>0){
                	for(int i=0;i<orgArr.length;i++){
            			TbOrganization org=organizationManager.getOrganizationById(Integer.parseInt(orgArr[i]));
            			if(org!=null&&org.getIsSetMessage()==1&&tbId!=org.getId()){
            				newOrgs=newOrgs+orgArr[i]+",";
            			}
            		}
                }
            	LOG.info("newOrgs："+newOrgs);
            	//前一天为休息日或者节假日，今天为工作日或者补班日就给用户发送短信
    	   		if(upBool&&bool&&StringUtil.isNotEmpty(newOrgs)){
    	   			if(",".equals(newOrgs.substring(newOrgs.length()-1,newOrgs.length()))){
    	   				LOG.info("sendMessageByOrgSet/切除尾部逗号------");
    	   				newOrgs=newOrgs.substring(0,newOrgs.length()-1);
    	   			}
    	   			LOG.info("sendMessageByOrgSet/end:newOrgs："+newOrgs);
    	   			List<AppUser> appUserList=appUserManager.getWxUserByOrgIds(newOrgs);
    	   			LOG.info("appUserList:"+JSON.toJSONString(appUserList));
    	   			if(appUserList!=null&&appUserList.size()>0){
    	   				for(int i=0;i<appUserList.size();i++){
    	   					AppUser appUser=appUserList.get(i);
    	   					if(appUser!=null&&scWxuserManager.exists(appUser.getWxUserId())&&StringUtil.isNotEmpty(appUser.getUserMobile())){
    	   						WxUser wxUser=scWxuserManager.get(appUser.getWxUserId());
    	   						String content=getContent(appUser.getOrganizationId().toString(), wxUser.getOpenId(), appUser.getId().toString());
    	   						LOG.info("sendMessageByOrgSet/发送短信号码："+appUser.getUserMobile());
    							String result = smsAuthCodeManager.smsSendByOrgId(appUser.getOrganizationId().toString(),content,appUser.getUserMobile(),"",CodeConstants.SMS_DINNER_TYPE);
    							LOG.info("sendMessageByOrgSet/isMessage："+result);
    	   					}
    	   				}
    	   			}
    	   		}
            }
		} catch (Exception e) {
			LOG.error("sendMessageByOrgSet/短信提醒失败："+e.getMessage());
			e.printStackTrace();
		}
	}
	/**
     * 获取会议室统计
     * @param orgId
     * @param dateType
     * @param date
     * @param endDate
     * @return
     */
	@Override
	public WebPageResultDto getMeetStatistics(String orgId, int dateType,
			String date, String endDate, int pageSize, int pageNo) {
		List<MeetintDto> mapList=orderDinnerManager.getMeetingInfoList(orgId, dateType, date, endDate);
		//分页
		WebPageResultDto dto=new WebPageResultDto("200","成功",null);
		if(mapList!=null&&mapList.size()>0){
			ListPage page=PageUtils.getListPage(mapList, pageNo, pageSize);
			dto.setCount(Long.parseLong(String.valueOf(mapList.size())));
			dto.setData(page.getDataList());
		}else{
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}
}
