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

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
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.*;
import com.palmnest.application.dto.MealExcelDto;
import com.palmnest.application.dto.TempOrderDinnerDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.WeekMealCarDto;
import com.palmnest.application.dto.input.MealCarInputDto;
import com.palmnest.application.dto.input.OrderDinnerInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.MealCarDto;
import com.palmnest.application.dto.output.OrderDinnerInfoDto;
import com.palmnest.application.dto.output.OrderDinnerOutPutDto;
import com.palmnest.model.dinner.*;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.washcar.UserEvaluate;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.dinner.manager.*;
import com.palmnest.service.dinner.service.OrderDinnerService;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.washcar.manager.UserEvaluateManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("orderDinnerService")
public class OrderDinnerServiceImpl implements OrderDinnerService {


	@Autowired
	private MealCarManager                  mealCarManager;
	@Autowired
	private ConsumerManager                 consumerManager;
	@Autowired
	private OrderDinnerManager              orderDinnerManager;
	@Autowired
	private OrderDinnerInfoManager          orderDinnerInfoManager;
	@Autowired
	private MealManager                     mealManager;
	@Autowired
	private ElementGroupManager             elementGroupManager;
	@Autowired
	private UserEvaluateManager             userEvaluateManager;
	@Autowired
	private ScWxuserManager                 scWxuserManager;
	@Autowired
	private WeChatApiManager                weChatApiManager;
	@Autowired
	private AppUserManager                  appUserManager;
	@Autowired
	private IntegralRecodeInfoManager       integralRecodeInfoManager;
	@Autowired
	private RechargeSetManager              rechargeSetManager;
	@Autowired
	private DeptManager                     deptManager;
	@Autowired
	private BaseRedisService                baseRedisService;
	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private OrganizationManager             organizationManager;

	private static final String DINNER = "dinner";

	public static final String CLIENTNO  = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");
	public static final String IMAGE_URL = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 加入购物车
	 */
	@Transactional
	public AppResultDto joinMealCar(List<MealCarInputDto> carDto, List<MealCarInputDto> removeCarDto, String orgId, String wxUserId) {
		//根据openId获取当前操作人
		AppUser      appUser  = appUserManager.get(Integer.parseInt(wxUserId));
		int          bugCount = 0;
		StringBuffer bugStr   = new StringBuffer("");
		String       userId   = appUser.getId().toString();

		//清除的购物车数据
		if (removeCarDto != null && removeCarDto.size() > 0) {
			for (int i = 0; i < removeCarDto.size(); i++) {
				MealCarInputDto dto = removeCarDto.get(i);
				if (dto != null && StringUtils.isNotEmpty(dto.getId())) {
					mealCarManager.remove(Long.parseLong(dto.getId()));
				}
			}
		}
		List<MealCarInputDto> listDto = new ArrayList<MealCarInputDto>();
		//重新增加的数据
		if (carDto != null && carDto.size() > 0) {
			for (int i = 0; i < carDto.size(); i++) {
				MealCarInputDto dto = carDto.get(i);
				if (dto != null) {
					//只有会议餐才需要修改数量(别的餐品只能删除，不能修改不能新增)
					if (StringUtils.isNotEmpty(dto.getId()) && dto.getIsMeetingOrder() == 1) {
						listDto.add(dto);
					}
					if (StringUtils.isEmpty(dto.getConsId())) {
						bugStr.append("第" + i + "条数据操作人id为空");
						bugCount++;
						continue;
					}
					if (!appUserManager.exists(Integer.parseInt(dto.getConsId()))) {
						bugStr.append("第" + i + "条数据操作人id在系统中找不到");
						bugCount++;
						continue;
					}
					AppUser user = appUserManager.get(Integer.parseInt(dto.getConsId()));
					if ("1".equals(appUser.getRoleType())) {//管理员身份
						//管理员加入购物车时，首先判断所选用户是否当前操作用户，如果是按照个人下单逻辑判断下；
						//如果不是当前操作人，判断创建人为当前操作用户且下单人及下单时间下是否有购物车，且判断下单人及下单时间下是否有订单.
						//判断购物车
						if (dto.getIsMeetingOrder() == 0) {
							int mealCaCount = mealCarManager.getMealCarByUserIdAndTime(dto.getConsId(), dto.getOrderTime(), userId);
							if (mealCaCount > 0) {
								bugStr.append("下单账号为:" + user.getUserMobile() + "的购物车中已有数据，无法加入购物车");
								bugCount++;
								continue;
							}
						}
						try {

							dto.setOrderTime(sdf.format(sdf.parse(dto.getOrderTime())));
						} catch (Exception e) {
							log.error("加入购物车时，时间格式有问题:" + dto.getOrderTime());
							bugStr.append("加入购物车时，时间格式有问题:" + dto.getOrderTime());
							bugCount++;
							continue;
						}
//						if(user.getId().toString().equals(wxUserId)){
//							if(user.getIntegral()<=0){
//								bugStr.append("下单账号为:"+user.getUserMobile()+"的积分不足，无法加入购物车");
//								bugCount++;
//								continue;
//							}
//						}

					} else {
//						if(user.getIntegral()<=0){
//							bugStr.append("下单账号为:"+user.getUserMobile()+"的积分不足，无法加入购物车");
//							bugCount++;
//							continue;
//						}
						//个人账号、代订账号都需要判断购物车中是否存在数据
						//当前操作人为创建人及下单时间下不能有数据
						List<MealCar> mealCaList = mealCarManager.findMealCarListByUserId(dto.getConsId(), dto.getOrderTime());
						if (mealCaList != null && mealCaList.size() > 0) {
							bugStr.append("下单账号为:" + user.getUserMobile() + "的购物车中已有数据，无法加入购物车");
							bugCount++;
							continue;
						}
					}
					//排除会议餐(会议餐允许下多次)
					if (dto.getIsMeetingOrder() == 0) {
						List<Map<String, Object>> list = orderDinnerInfoManager.getOrderInfoByTime(dto.getConsId(), dto.getOrderTime());
						if (list != null && list.size() > 0) {
							bugStr.append("下单账号为:" + user.getUserMobile() + "已存在订单，无法加入购物车");
							bugCount++;
							continue;
						}
					}
					if (StringUtils.isEmpty(dto.getId())) {
						listDto.add(dto);
					}
				}
			}
		}
		if (bugCount > 0) {
			log.error("加入购物车失败：" + bugStr);
			return AppResultUtil.createErrorDto("100", "每人每天只能预订一份哦，如需修改餐品请先去掉已选餐品");
		} else {
			if (listDto != null && listDto.size() > 0) {
				for (int i = 0; i < listDto.size(); i++) {
					MealCarInputDto dto = carDto.get(i);
					if (StringUtils.isNotEmpty(dto.getId()) && dto.getIsMeetingOrder() == 1) {
						MealCar mealCar = mealCarManager.get(Long.parseLong(dto.getId()));
						mealCar.setFoodCount(dto.getCount());
						mealCar.setModifyTime(new Date());
						mealCar.setModifier(appUser.getId().toString());
						mealCarManager.updateModel(mealCar);
						continue;
					}
					if (StringUtils.isEmpty(dto.getId())) {
						MealCar mealcar = new MealCar();
						mealcar.setIsEnabled("1");
						mealcar.setMealId(dto.getMealId());
						mealcar.setStapleFood(dto.getStapleFood());
						mealcar.setCreateTime(new Date());
						mealcar.setCreator(appUser.getId().toString());
						mealcar.setDinnerTime(dto.getOrderTime());
						mealcar.setConsId(dto.getConsId());
						mealcar.setIsMeetFood(String.valueOf(dto.getIsMeetingOrder()));
						mealcar.setFoodCount(dto.getCount());
						mealcar = mealCarManager.save(mealcar);
					}
				}
			}
		}
		return AppResultUtil.createSuccesDto();
	}

	@Transactional
	public AppResultDto removeMealCar(String orgId, String wxUserId, String id, int type) {
		AppUser appUser = appUserManager.get(Integer.parseInt(wxUserId));
		try {
			if (type == 1) {//删除购物车中餐品的数量
				//根据购物车id进行减少数量
				if (StringUtils.isEmpty(id)) {
					return AppResultUtil.createErrorDto("100", "操作失败");
				}
				if (mealCarManager.exists(Long.parseLong(id))) {
					MealCar mealcar = mealCarManager.get(Long.parseLong(id));
					if (mealcar.getFoodCount() == 0) {
						return AppResultUtil.createErrorDto("100", "数量已为0，无法删减");
					}
					if (mealcar.getFoodCount() - 1 == 0) {//如果购物车中的数量是0了，就移除
						mealCarManager.remove(Long.parseLong(id));
						return AppResultUtil.createSuccesDto();
					}
					//只有会议餐才会需要删除份数
					mealcar.setFoodCount(mealcar.getFoodCount() - 1);
					mealcar.setModifyTime(new Date());
					mealcar.setModifier(appUser.getId().toString());
					mealCarManager.updateModel(mealcar);
					return AppResultUtil.createSuccesDto();
				}
			} else if (type == 2) {//清空购物车
				mealCarManager.removeMealCar(appUser.getId().toString());
				return AppResultUtil.createSuccesDto();
			}
			return AppResultUtil.createErrorDto("100", "操作失败");
		} catch (Exception e) {
			log.error("清空或删除购物车中餐品失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作失败");
		}

	}

	@Transactional
	public OrderDinner saveParentOrder(String userId, String orgId, String dinnerTime, int isSumOrder, String remark) throws ParseException {
		OrderDinner order = new OrderDinner();
		order.setCreateTime(new Date());//操作时间
		order.setCreator(userId);//操作人
		order.setIsEnabled("1");
		order.setNumber(CodeGenerateUtils.generate(DINNER));
		order.setOrgId(orgId);
		order.setStatus("1");
		if (StringUtils.isNotEmpty(dinnerTime)) {
			order.setDinnerTime(sdf.parse(dinnerTime));//下单时间
		}
		order.setConsId(userId);//下单人
		order.setIsSumOrder(isSumOrder);
		if (isSumOrder == 0) {
			order.setRemark(remark);
			order.setIsTempOrder(1);
		}
		order = orderDinnerManager.save(order);//保存订单信息
		return order;
	}

	/**
	 * 校验提单的订单中是否有用户积分不足
	 *
	 * @param list
	 */
	@Transactional
	public Map<String, Object> checkIntegral(List<WeekMealCarDto> list) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (list != null && list.size() > 0) {
			for (WeekMealCarDto dto : list) {

			}
		}
		return null;
	}

	/**
	 * 提交订单
	 * 首先判断时间有没有超过11点(controller)，
	 * 然后再判断该用户能不能再提交一份
	 * 判断餐品是否有效
	 * 然后根据当前登录用户将购物车中的餐品提交到餐品详情中
	 *
	 * @return
	 */
	@Transactional
	public AppResultDto submitDinnerOrder(String wxUserId, String orgId, List<WeekMealCarDto> list) {

		AppUser     appUser = appUserManager.get(Integer.parseInt(wxUserId));
		RechargeSet reSet   = rechargeSetManager.findByOrgId(orgId);
		if (reSet == null) {
			return AppResultUtil.createErrorDto("100", "该项目下未设置积分，无法提交");
		}
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		if (!"1".equals(appUser.getRoleType())) {
			if (appUser.getIntegral() < reSet.getDayCount()) {
				return AppResultUtil.createErrorDto("100", "抱歉，订单提交失败，您账户的积分余额不足！");
			}
		}
		//需要考虑代订的情况，暂不加这个判断
//		if(!StringUtil.isNotEmpty(appUser.getAddress())){
//			return AppResultUtil.createErrorDto("100", "抱歉，订单提交失败，您的订餐地址不能为空！");
//		}

		//如果是管理员账号帮别人代订时，首先拿到所有的人对应消费金额，然后再判断这些人对应的账号是否支持消费这么多金额，不支持整条单据返回；


		int dayCount = reSet.getDayCount();//当前积分

		String userId = appUser.getId().toString();
		try {
			int                  sumAmount = 0;//每个用户的汇总积分
			HashSet<String>      userSet   = new HashSet<String>();
			Map<String, Integer> userMap   = new HashMap<String, Integer>();
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					WeekMealCarDto   weekDto    = list.get(i);
					List<MealCarDto> carDtoList = weekDto.getMealCarList();
					if (null != carDtoList && carDtoList.size() > 0) {
						for (int k = 0; k < carDtoList.size(); k++) {
							MealCarDto mealCarDto = carDtoList.get(k);
							userSet.add(mealCarDto.getUserId());
							if (1 == mealCarDto.getIsMeetingOrder()) {//如果是会议餐无需记录
								continue;
							}
							if (null != mealCarDto.getUserId() && StringUtil.isNotEmpty(mealCarDto.getUserId()) && userMap.containsKey(mealCarDto.getUserId())) {
								//如果用户存在时，首先获取已经存在的积分总数，然后再和本次的累计；
								int count    = mealCarDto.getFoodCount();//当前份数
								int benciSum = count * dayCount;
								sumAmount = userMap.get(mealCarDto.getUserId()) + benciSum;
								userMap.put(mealCarDto.getUserId(), sumAmount);
							} else if (null != mealCarDto.getUserId() && StringUtil.isNotEmpty(mealCarDto.getUserId()) && !userMap.containsKey(mealCarDto.getUserId())) {
								int count    = mealCarDto.getFoodCount();//当前份数
								int benciSum = count * dayCount;
								sumAmount = benciSum;
								userMap.put(mealCarDto.getUserId(), sumAmount);
							}
						}
					}
				}
			}


			int           failCount = 0;//错误个数
			StringBuilder sb        = new StringBuilder();//错误日志
			//循环userSet,然后获取每个用户的积分、地址；积分不足或者地址没有，就不允许再操作
			for (String userIdStr : userSet) {
				if (appUserManager.exists(Integer.parseInt(userIdStr))) {
					AppUser user = appUserManager.get(Integer.parseInt(userIdStr));
					//用户的送餐地址为空时，提示无法下单
					if (!StringUtil.isNotEmpty(user.getAddress())) {
						failCount++;
						sb.append("用户名为:" + user.getUserName() + "(" + user.getUserMobile() + ")的用户送餐地址为空，无法下单;\n <br />");
						continue;
					}
					int     integral     = user.getIntegral();//用户的积分
					Integer userIntegral = userMap.get(userIdStr);//获取本次订单消费的积分
					if (null == userIntegral) {
						userIntegral = 0;
					}

					//用户总的积分减去本次消费的积分小于0时，提示不能成功消费
					if (integral - userIntegral < 0) {
						failCount++;
						sb.append("用户名为:" + user.getUserName() + "(" + user.getUserMobile() + ")的用户积分不足本次消费，无法下单;\n <br />");
						continue;
					}
				} else {
					failCount++;
					sb.append("获取不到用户id为：" + userIdStr + "的用户;");
					continue;
				}
			}

			if (failCount > 0) {
				return AppResultUtil.createErrorDto("100", "下单失败：" + sb.toString());
			}

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					WeekMealCarDto   weekDto     = list.get(i);
					WeekDate         week        = weekDto.getWeekDate();
					List<MealCarDto> dtoList     = new ArrayList<MealCarDto>();
					List<MealCarDto> carDtoList  = weekDto.getMealCarList();
					OrderDinner      orderDinner = new OrderDinner();
					String           weekTime    = sdf.format(sdf.parse(week.getDateTime()));
					String           sysDate     = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
					if (sysDate.equals(weekTime)) {
						//判断当前时间是否超出11点
						String str = orderDinnerManager.getOrderTime(orgId, "orderTime");
						if (StringUtils.isNotEmpty(str)) {//超出
							log.error("抱歉，订单时间已超过订餐截止时间（" + str + "），明天记得早点哦");
							throw new RuntimeException("抱歉，订单时间已超过订餐截止时间（" + str + "），明天记得早点哦");
						}
					}
					//查询是否存在会议餐或该用户的订单
					if ("1".equals(appUser.getRoleType())) {//如果是管理员，这个日期下面有订单明细，就直接生成一个订单
						if (carDtoList != null && carDtoList.size() > 0) {
							orderDinner = saveParentOrder(appUser.getId().toString(), orgId, weekTime, 1, "");
							//首先汇总会议餐以及管理员自己的餐品
							Map<String, Object> ordersMap = new HashMap<String, Object>();
							ordersMap.put("userId", appUser.getId().toString());
							ordersMap.put("userName", appUser.getUserName());
							ordersMap.put("mobile", appUser.getUserMobile());
							ordersMap.put("dinnerTime", weekTime);
							ordersMap.put("isPay", 0);
							ordersMap.put("isParentOrder", 1);
							ordersMap.put("parentId", orderDinner.getId().toString());
							for (int k = 0; k < carDtoList.size(); k++) {
								MealCarDto carDto = carDtoList.get(k);
								//首先判断用户有没有下过订单,并且不能是会议餐
								if (appUser.getId().toString().equals(carDto.getUserId()) && carDto.getIsMeetingOrder() == 0) {
									List<Map<String, Object>> orderList = orderDinnerInfoManager.getOrderInfoByTime(carDto.getUserId(), weekTime);
									if (orderList != null && orderList.size() > 0) {
										log.error("订餐时间" + weekTime + "且账号为:" + carDto.getMobile() + "已存在订单，无法提交!");
										throw new RuntimeException("订餐时间" + weekTime + "且账号为:" + carDto.getMobile() + "已存在订单，无法提交!");
//										return AppResultUtil.createErrorDto("100", "订餐时间"+week.getDateTime()+"且账号为:"+carDto.getMobile()+"已存在订单，无法提交!");
									}
									if (carDto.getIsMeetingOrder() != 1) {
										ordersMap.put("isPay", 1);
										orderDinner.setIntegral(reSet.getDayCount());
										orderDinner.setModifier(appUser.getId().toString());
										orderDinner.setModifyTime(new Date());
										orderDinnerManager.updateModel(orderDinner);
									}
								}
								if (carDto.getIsMeetingOrder() == 1 || appUser.getId().toString().equals(carDto.getUserId())) {
									//根据下单人及下单时间判断是否已有数据，如果有则不允许提交
									dtoList.add(carDto);
									ordersMap.put("orderList", dtoList);
								}
							}
							mapList.add(ordersMap);
							for (int k = 0; k < carDtoList.size(); k++) {
								MealCarDto carDto = carDtoList.get(k);
								//汇总非会议餐以及非本人的
								if (carDto.getIsMeetingOrder() != 1 && !appUser.getId().toString().equals(carDto.getUserId())) {
									Map<String, Object> orderMap = new HashMap<String, Object>();
									orderMap.put("userId", carDto.getUserId());
									orderMap.put("userName", carDto.getUserName());
									orderMap.put("mobile", carDto.getMobile());
									orderMap.put("dinnerTime", weekTime);
									orderMap.put("parentId", orderDinner.getId().toString());
									orderMap.put("isParentOrder", 0);
									orderMap.put("isPay", 1);
									List<MealCarDto> orderInfoList = new ArrayList<MealCarDto>();
									orderInfoList.add(carDto);
									orderMap.put("orderList", orderInfoList);
									mapList.add(orderMap);
								}
							}
						}
					} else {
						if (carDtoList != null && carDtoList.size() > 0) {
							for (int k = 0; k < carDtoList.size(); k++) {
								MealCarDto                carDto    = carDtoList.get(k);
								List<Map<String, Object>> orderList = orderDinnerInfoManager.getOrderInfoByTime(carDto.getUserId(), weekTime);
								if (orderList != null && orderList.size() > 0) {
									log.error("订餐时间" + weekTime + "且账号为:" + carDto.getMobile() + "已存在订单，无法提交!");
									throw new RuntimeException("订餐时间" + weekTime + "且账号为:" + carDto.getMobile() + "已存在订单，无法提交!");
//									return AppResultUtil.createErrorDto("100", "订餐时间"+week.getDateTime()+"且账号为:"+carDto.getMobile()+"已存在订单，无法提交!");
								}
								dtoList.add(carDto);
								Map<String, Object> orderMap = new HashMap<String, Object>();
								orderMap.put("userId", carDto.getUserId());
								orderMap.put("userName", carDto.getUserName());
								orderMap.put("mobile", carDto.getMobile());
								orderMap.put("dinnerTime", weekTime);
								orderMap.put("isParentOrder", 0);
								orderMap.put("parentId", "");
								orderMap.put("isPay", 1);
								orderMap.put("orderList", dtoList);
								mapList.add(orderMap);
							}
						}
					}
				}
			}
			//新增订单-保存操作记录-扣除积分
			submitOrderInfo(mapList, appUser, orgId, reSet.getDayCount());
			mealCarManager.removeMealCar(userId);
			return AppResultUtil.createSuccesDto();
		} catch (RuntimeException e) {
			log.error("提交订单失败:" + e.getMessage());
			e.printStackTrace();
			throw new RuntimeException("提交订单失败:" + e.getMessage());
//			return AppResultUtil.createErrorDto("100", "提交订单失败:"+e.getMessage());
		} catch (Exception e) {
			log.error("提交订单失败:" + e.getMessage());
			e.printStackTrace();
//			return AppResultUtil.createErrorDto("100", "提交订单失败:"+e.getMessage());
			throw new RuntimeException("提交订单失败:" + e.getMessage());
		}
	}

	//新增订单-保存操作记录-扣除积分
	@Transactional
	public void submitOrderInfo(List<Map<String, Object>> mapList, AppUser appUser, String orgId, int integral) throws ParseException {
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
				Map<String, Object> orderMap      = mapList.get(i);
				String              userId        = orderMap.get("userId") == null ? "" : orderMap.get("userId").toString();//下单人
				String              dinnerTime    = orderMap.get("dinnerTime") == null ? "" : orderMap.get("dinnerTime").toString();//下单时间
				int                 isParentOrder = Integer.parseInt(orderMap.get("isParentOrder") == null ? "0" : orderMap.get("isParentOrder").toString());//是否父级
				int                 isPay         = Integer.parseInt(orderMap.get("isPay") == null ? "0" : orderMap.get("isPay").toString());//自己是否有餐品
				String              parentId      = orderMap.get("parentId") == null ? "" : orderMap.get("parentId").toString();
				List<MealCarDto>    orderInfoList = (List<MealCarDto>) orderMap.get("orderList");
				if ("1".equals(appUser.getRoleType())) {
					if (isParentOrder == 1) {
						if (orderMap.containsKey("orderList")) {//直接获取订单详情增加详情即可
							if (StringUtils.isNotEmpty(parentId)) {
								OrderDinner order = orderDinnerManager.get(Long.parseLong(parentId));
								saveInfo(order, orderInfoList, appUser.getId().toString(), isPay, integral, appUser.getId().toString());
							}
						}
					} else {
						OrderDinner order = new OrderDinner();
						order.setCreateTime(new Date());//操作时间
						order.setCreator(appUser.getId().toString());//操作人
						order.setIsEnabled("1");
						order.setNumber(CodeGenerateUtils.generate(DINNER));
						order.setOrgId(orgId);
						order.setStatus("1");
						if (StringUtils.isNotEmpty(dinnerTime)) {
							order.setDinnerTime(sdf.parse(dinnerTime));//下单时间
						}
						order.setIntegral(integral);
						order.setConsId(userId);//下单人
						order.setParentOrderId(parentId);
						order = orderDinnerManager.save(order);//保存订单信息

						saveInfo(order, orderInfoList, appUser.getId().toString(), isPay, integral, userId);
					}
				} else {
					OrderDinner order = new OrderDinner();
					order.setCreateTime(new Date());//操作时间
					order.setCreator(appUser.getId().toString());//操作人
					order.setIsEnabled("1");
					order.setNumber(CodeGenerateUtils.generate(DINNER));
					order.setOrgId(orgId);
					order.setStatus("1");
					if (StringUtils.isNotEmpty(dinnerTime)) {
						order.setDinnerTime(sdf.parse(dinnerTime));//下单时间
					}
					order.setIntegral(integral);
					order.setConsId(userId);//下单人
					order.setParentOrderId(parentId);
					order = orderDinnerManager.save(order);//保存订单信息
					saveInfo(order, orderInfoList, appUser.getId().toString(), isPay, integral, userId);
				}
			}
		}
	}

	/**
	 * 根据订餐人生成订单详情以及扣除积分
	 *
	 * @param order
	 * @param orderInfoList
	 * @param userId
	 * @param isPay
	 */
	public void saveInfo(OrderDinner order, List<MealCarDto> orderInfoList, String userId, int isPay, int integral, String consId) {
		if (order != null) {
			//保存餐品详情并删除购物车
//			List<MealCarDto> orderInfoList =(List<MealCarDto>) orderMap.get("orderList");
			if (orderInfoList != null && orderInfoList.size() > 0) {
				saveOrderInfo(orderInfoList, userId, order.getId(), order.getOrgId(), order.getDinnerTime());
				if (isPay == 1) {//当操作用户是自己的时候
					if (appUserManager.exists(Integer.parseInt(consId))) {
						AppUser user = appUserManager.get(Integer.parseInt(consId));
						log.info("submitDinnerOrder:integral BEGIN " + user.getIntegral());
						int integrals = user.getIntegral() - integral;
						log.info("submitDinnerOrder:integral END " + integrals);
						//增加操作记录
						IntegralRecodeInfo intRecode = new IntegralRecodeInfo(userId, 3, user.getUserName(), user.getUserMobile(), user.getIntegral(), integrals, new Date(), "-" + integral, order.getOrgId(), user.getId().toString());
						integralRecodeInfoManager.save(intRecode);
						//修改积分
						user.setIntegral(integrals);
						user.setModifier(userId);
						user.setModifyTime(new Date());
						appUserManager.saveOrUpdateAppUser(user);
					}
				}
			}
		}
	}

	/**
	 * 保存订单明细
	 *
	 * @param orderInfoList
	 * @param userId
	 * @param orderId
	 */
	@Transactional
	public void saveOrderInfo(List<MealCarDto> orderInfoList, String userId, Long orderId, String orgId, Date date) {
		for (int i = 0; i < orderInfoList.size(); i++) {
			MealCarDto dto = orderInfoList.get(i);
			saveOrderDinnerInfo(dto, orderId, userId, orgId, date);
		}
	}

	/**
	 * 保存订单详情
	 *
	 * @param orderId
	 * @return
	 */
	@Transactional
	public void saveOrderDinnerInfo(MealCarDto dto, Long orderId, String userId, String orgId, Date date) {
		try {
			if (orderDinnerManager.exists(orderId)) {
				OrderDinnerInfo oInfor = new OrderDinnerInfo();
				oInfor.setCreateTime(new Date());
				oInfor.setCreator(userId);
				oInfor.setOrgId(orgId);
				oInfor.setFoodCount(dto.getFoodCount());
				oInfor.setIsEnabled("1");
				oInfor.setMealId(dto.getMealId());
				String mealName = "";
				if (StringUtils.isNotEmpty(dto.getMealId()) && mealCarManager.exists(Long.parseLong(dto.getMealId()))) {
					Meal meal = mealManager.get(Long.parseLong(dto.getMealId()));
					if (StringUtils.isNotEmpty(meal.getMealCodeId())) {
						ElementDto el = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
						if (el != null) {
							mealName = el.getItemname();
						}
					}
				}
				oInfor.setMealName(mealName);
				oInfor.setOrderId(orderId.toString());
				oInfor.setStapleFood(dto.getStapleFood());
				oInfor.setDinnerTime(date);
				oInfor.setConsId(dto.getUserId());
				oInfor.setIsMeetFood(String.valueOf(dto.getIsMeetingOrder()));
				oInfor.setStapleFoodStr(dto.getStapleFoodStr());
				orderDinnerInfoManager.save(oInfor);
			}
		} catch (Exception e) {
			log.error("提交订单失败:" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 获取购物车列表
	 */
	@Override
	public AppResultDto gainMealCarList(String orgId, String wxUserId, int isOver) {
		AppUser     appUser = appUserManager.get(Integer.parseInt(wxUserId));
		RechargeSet reSet   = rechargeSetManager.findByOrgId(orgId);
		if (reSet == null) {
			return AppResultUtil.createErrorDto("100", "该项目下未设置积分，无法提交");
		}
		Map<String, Object> map      = new HashMap<String, Object>();
		String              userId   = appUser.getId().toString();
		Calendar            cal      = Calendar.getInstance();
		int                 weekDate = cal.get(Calendar.DAY_OF_WEEK) - 1;
		//首先获取周期，然后获取周期下对应的购物车中的数据，如果周期下没有数据，就不需要展示这个周期
		List<WeekMealCarDto> weekDtoList = new ArrayList<WeekMealCarDto>();
//		List<WeekDate>       weekList    = DateUtils.getWeek();//--------------------------20220526-----------------------------------
		List<WeekDate>       weekList    = mealManager.getMealDate(Integer.parseInt(orgId));
		List<MealCar>        mealcarList = mealCarManager.findMealCarListByUserId(userId);
		int                  sumInt      = 0;//总积分
		int                  sumCount    = 0;
		if (weekList != null && weekList.size() > 0) {
			for (int i = 0; i < weekList.size(); i++) {
				WeekMealCarDto dto  = new WeekMealCarDto();
				WeekDate       week = weekList.get(i);
				//根据时间获取购物车中的餐品
//				List<MealCar> mealcarList=mealCarManager.findMealCarListByUserId(userId, week.getDateTime());
				if (mealcarList != null && mealcarList.size() > 0) {
					List<MealCarDto> dtoList = getMealCarDtoList(mealcarList, week.getDateTime());
					//没操作下单前只获取当天及之后购物车数据，已超过下单时间只获取今天之后的购物车数据
					//当下单时间是今天的时候且并没有超过操作时间的数据可以加入到集合中；
					//下单时间的周几大于当天的周几的时候，周三>周二(该为系统当前时间)也可以加入到集合中
//					if ((isOver == 0 && week.getWeekNo() == weekDate) || (week.getWeekNo() > weekDate)) {//--------------------------20220526-----------------------------------
						if (dtoList != null && dtoList.size() > 0) {
							dto.setMealCarList(dtoList);
							dto.setWeekDate(week);
							weekDtoList.add(dto);
							for (int k = 0; k < dtoList.size(); k++) {
								MealCarDto mealCar = dtoList.get(k);
								if (mealCar != null) {
									sumCount = sumCount + mealCar.getFoodCount();
								}
							}
						}
						System.out.println("时间：" + week.getDateTime());
						//获取当天下单人为该用户的购物车，有则记录积分；如果没有则不记录
						int count = mealCarManager.getMealCarByUserIdAndTime(userId, week.getDateTime(), "");
						if (count > 0) {
							sumInt = sumInt + reSet.getDayCount();
						}
//					}//--------------------------20220526-----------------------------------
				}
			}
		}
		//清除无用数据
		if (isOver == 1) {
			mealCarManager.removeMealCarList(userId, 2);
		} else {
			mealCarManager.removeMealCarList(userId, 1);
		}
		if (weekDtoList != null && weekDtoList.size() > 0) {
			map.put("weekDtoList", weekDtoList);
			map.put("sumIntegral", sumInt);//只汇总自己的总积分
			map.put("sumCount", sumCount);//获取所有日期下的总份数
			return AppResultUtil.createSuccesDto(map);
		}
		return AppResultUtil.createSuccesDto();

	}

	public List<MealCarDto> getMealCarDtoList(List<MealCar> list, String time) {
		List<MealCarDto> dtoList = new ArrayList<MealCarDto>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				MealCar mealCar = list.get(i);
				if (mealCar != null) {
					if (!time.equals(mealCar.getDinnerTime())) {
						continue;
					}
					MealCarDto dto = new MealCarDto();
					//数量
					dto.setFoodCount(mealCar.getFoodCount());
					dto.setId(mealCar.getId().toString());
					//餐品
					dto.setMealId(mealCar.getMealId());
					String mealName = "";
					if (StringUtils.isNotEmpty(mealCar.getMealId()) && mealManager.exists(Long.parseLong(mealCar.getMealId()))) {
						Meal meal = mealManager.get(Long.parseLong(mealCar.getMealId()));
						if (StringUtils.isNotEmpty(meal.getMealCodeId())) {
							ElementDto el = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
							if (el != null) {
								mealName = el.getItemname();
							}
						}
					}
					dto.setMealName(mealName);//餐品名
					//是否会议餐
					if (StringUtils.isNotEmpty(mealCar.getIsMeetFood())) {
						dto.setIsMeetingOrder(Integer.parseInt(mealCar.getIsMeetFood()));
					} else {
						dto.setIsMeetingOrder(0);
					}
					//下单人信息
					if (StringUtils.isNotEmpty(mealCar.getConsId()) && appUserManager.exists(Integer.parseInt(mealCar.getConsId()))) {
						dto.setUserId(mealCar.getConsId());//下单人
						AppUser appUser = appUserManager.get(Integer.parseInt(mealCar.getConsId()));
						if (appUser != null) {
							dto.setUserName(appUser.getUserName());
							dto.setMobile(appUser.getUserMobile());
						}
					}
					//餐品主食
					dto.setStapleFood(mealCar.getStapleFood());
					if (StringUtils.isNotEmpty(mealCar.getStapleFood())) {
						String     stapleFoodStr = "";
						ElementDto el            = elementGroupManager.getElementById(Long.parseLong(mealCar.getStapleFood()));
						if (el != null) {
							stapleFoodStr = el.getItemname();
						}
						dto.setStapleFoodStr(stapleFoodStr);
					}
					//餐品图片
					if (StringUtils.isNotEmpty(mealCar.getMealId())) {
						if (mealManager.exists(Long.parseLong(mealCar.getMealId()))) {
							Meal meal = mealManager.get(Long.parseLong(mealCar.getMealId()));
							if (meal != null && StringUtils.isNotEmpty(meal.getMealImages())) {
								String[] urls = meal.getMealImages().split(";");
								if (urls != null && urls.length > 0) {
									dto.setMealImagesUrl(IMAGE_URL + urls[0]);
								}
							}
						}
					}
					dtoList.add(dto);
				}
			}
		}
		return dtoList;
	}

	/**
	 * PC/WECHAT端获取订餐列表
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Page findList(OrderDinnerInputDto dto, int pageSize, int pageNo) {
		Page page = orderDinnerManager.findList(dto, pageSize, pageNo);
		try {
			if (page != null) {
				List list = page.getItems();
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						Map<Object, Object> map = (Map<Object, Object>) list.get(i);
						if (map != null && map.containsKey("orderId")) {
							OrderDinner od = orderDinnerManager.get(Long.parseLong(map.get("orderId").toString()));
							map.put("isCancel", 0);
							if (StringUtils.isNotEmpty(map.get("dinnerTime") == null ? "" : map.get("dinnerTime").toString())) {
								String dinnerTime = map.get("dinnerTime") == null ? "" : map.get("dinnerTime").toString();
								String res        = isPower(od.getOrgId(), dinnerTime);
								if (StringUtils.isEmpty(res)) {//没超出，能展示取消按钮
									map.put("isCancel", 1);
								}
							}
							if (map.get("orderId") != null && StringUtils.isNotEmpty(map.get("orderId").toString())) {

								AppUser             user     = appUserManager.get(Integer.parseInt(od.getConsId()));
								Map<String, Object> orderMap = getOrderInfoList(Long.parseLong(map.get("orderId").toString()), user);
								if (StringUtils.isNotEmpty(map.get("dinnerTime") == null ? "" : map.get("dinnerTime").toString())) {
									map.put("dinnerTime", DateUtils.getWeekOfDates(sdf.parse(map.get("dinnerTime").toString())) + "  " + map.get("dinnerTime"));//添加订餐详情
								}
								if (orderMap.containsKey("isHaveMe")) {//判断是否有自己的单(包含会议餐)，没有自己的单的情况下就不展示取消按钮
									if (orderMap.get("isHaveMe") != null && StringUtils.isNotEmpty(orderMap.get("isHaveMe").toString())) {
										if ("0".equals(orderMap.get("isHaveMe").toString())) {
											//设置显示取消按钮
											map.put("isCancel", 0);
										}
									}
								}
								if (orderMap.containsKey("list")) {
									List<OrderDinnerInfoDto> orderDiList = (List<OrderDinnerInfoDto>) orderMap.get("list");
									if (orderDiList != null && orderDiList.size() > 0) {
										map.put("orderInfoList", orderMap.get("list"));//添加订餐详情
									}
								}
								map.put("orderInfoStr", orderMap.get("orderInfoStr"));//添加订餐详情
								map.put("sumCount", orderMap.get("sumCount"));//添加订餐详情总份数
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return page;
	}

	/**
	 * 获取订单详情列表（当前登录用户是管理员时，需要看该用户下的单下面是否还包含代下的订单详情以及会议餐等等）
	 *
	 * @param orderId
	 * @return
	 */
	public Map<String, Object> getOrderInfoList(Long orderId, AppUser user) {
		if (user == null) {
			return null;
		}
		String      str      = "";
		OrderDinner order    = orderDinnerManager.get(orderId);
		int         isOver   = orderDinnerManager.isOver(order.getOrgId(), "orderTime");
		RechargeSet reSet    = rechargeSetManager.findByOrgId(order.getOrgId());
		int         integral = 12;
		if (reSet != null) {
			integral = reSet.getDayCount();
		}
		Map<String, Object>      map           = new HashMap<String, Object>();
		List<OrderDinnerInfoDto> dtoList       = new ArrayList<OrderDinnerInfoDto>();
		int                      count         = 0;
		int                      meetCount     = 0;
		int                      sumIntegral   = 0;
		int                      isHaveMe      = 0;
		List<OrderDinnerInfo>    orderInfoList = orderDinnerInfoManager.findByOrderId(orderId);
		if (orderInfoList != null && orderInfoList.size() > 0) {
			for (int k = 0; k < orderInfoList.size(); k++) {
				OrderDinnerInfo orderInfo = orderInfoList.get(k);
				if (orderInfo != null) {
					OrderDinnerInfoDto orderInfoDto = new OrderDinnerInfoDto();
					orderInfoDto.setId(orderInfo.getId().toString());
					orderInfoDto.setMealId(orderInfo.getMealId());
					if (StringUtils.isEmpty(orderInfo.getMealName())) {
						if (StringUtil.isNotEmpty(orderInfo.getMealId())) {
							Meal meal = mealManager.get(Long.parseLong(orderInfo.getMealId()));
							if (meal != null) {
								ElementDto el = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
								if (el != null) {
									orderInfoDto.setMealName(el.getItemname());
								}
							}

						}
					} else {
						orderInfoDto.setMealName(orderInfo.getMealName());
					}
					if (order.getIsSumOrder() == 0 && order.getIsTempOrder() == 0) {
						sumIntegral = integral;
					} else {
						if (orderInfo.getCreator().equals(orderInfo.getConsId()) && !"1".equals(orderInfo.getIsMeetFood()) && order.getIsTempOrder() == 0) {
							sumIntegral = sumIntegral + integral;//累计积分
						}
					}
					orderInfoDto.setUserId(orderInfo.getConsId());
					if (StringUtils.isNotEmpty(orderInfo.getConsId()) && appUserManager.exists(Integer.parseInt(orderInfo.getConsId()))) {
						AppUser appUser = appUserManager.get(Integer.parseInt(orderInfo.getConsId()));
						if (appUser != null) {
							orderInfoDto.setUserName(appUser.getUserName());
							orderInfoDto.setMobile(appUser.getUserMobile());
						}
					}
					orderInfoDto.setOrderId(orderInfo.getOrderId());
					orderInfoDto.setStapleFood(orderInfo.getStapleFood());
					orderInfoDto.setStapleFoodStr(orderInfo.getStapleFoodStr());
					orderInfoDto.setFoodCount(orderInfo.getFoodCount());
					if (StringUtils.isNotEmpty(orderInfo.getIsMeetFood())) {//会议餐
						orderInfoDto.setIsMeetFood(Integer.parseInt(orderInfo.getIsMeetFood()));
					}
					if ("1".equals(orderInfo.getIsMeetFood())) {
						isHaveMe = 1;
						meetCount = meetCount + orderInfo.getFoodCount();
					}
					if ("4".equals(order.getStatus())) {
						orderInfoDto.setCancelStatus(1);//已取消状态
					} else {
						orderInfoDto.setCancelStatus(0);//
					}
					try {

						if (DateUtils.checkIsOver(sdf.format(order.getDinnerTime()), isOver)) {
							orderInfoDto.setIsCancel(0);//不展示取消按钮
						} else {
							orderInfoDto.setIsCancel(1);//展示取消按钮
						}
					} catch (Exception e) {
						log.error(e.getMessage());
						e.printStackTrace();
					}

					count = count + orderInfo.getFoodCount();
					String mealFood = "";
					if (StringUtils.isNotEmpty(order.getDinnerTime().toString())) {
						orderInfoDto.setDinnerTime(sdf.format(order.getDinnerTime()));
					}
					if (user.getId().toString().equals(orderInfo.getConsId())) {//当前登录人是否该订单的操作人
						isHaveMe = 1;
					}
					if (StringUtils.isNotEmpty(orderInfo.getMealId())) {
						if (mealManager.exists(Long.parseLong(orderInfo.getMealId()))) {
							Meal meal = mealManager.get(Long.parseLong(orderInfo.getMealId()));
							if (StringUtils.isNotEmpty(meal.getMealCodeId())) {
								ElementDto el = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
								if (el != null) {
									if (StringUtils.isNotEmpty(orderInfo.getStapleFoodStr())) {
										mealFood = el.getItemname() + "(" + orderInfo.getStapleFoodStr() + ")";
										str = str + el.getItemname() + ":" + orderInfo.getStapleFoodStr() + " x" + orderInfo.getFoodCount() + ";";
									} else {
										mealFood = el.getItemname();
										str = str + el.getItemname() + " x" + orderInfo.getFoodCount() + ";";
									}
								}
							}
							orderInfoDto.setMealFood(mealFood);
							if (StringUtils.isNotEmpty(meal.getMealImages())) {
								String[] images = meal.getMealImages().split(";");
								if (images != null && images.length > 0) {
									orderInfoDto.setMealImages(images[0]);
									if (StringUtils.isNotEmpty(images[0])) {
										orderInfoDto.setMealImagesUrl(IMAGE_URL + images[0]);
									}
								}
							}
						}
					}
					dtoList.add(orderInfoDto);
				}
			}
		}

		if ("1".equals(user.getRoleType())) {//是管理员的时候，需要获取订单表中的parentId为这个id的
			List<OrderDinnerInfoDto> list = orderDinnerInfoManager.getOrderInfoByParentOrderId(orderId.toString(), isOver);
			for (int i = 0; i < list.size(); i++) {
				OrderDinnerInfoDto dto = list.get(i);
				count = count + dto.getFoodCount();
				if (StringUtils.isNotEmpty(dto.getStapleFoodStr())) {
					str = str + dto.getMealName() + ":" + dto.getStapleFoodStr() + " x" + dto.getFoodCount() + ";";
				} else {
					str = str + dto.getMealName() + " x" + dto.getFoodCount() + ";";
				}
				dtoList.add(dto);
			}
		}
		map.put("orderInfoStr", str);
		map.put("list", dtoList);
		map.put("sumCount", count);
		map.put("isHaveMe", isHaveMe);
		map.put("meetCount", meetCount);
		map.put("sumIntegral", sumIntegral);
		return map;
	}

	/**
	 * 获取订单详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public AppResultDto findById(Long id) {
		try {
			if (orderDinnerManager.exists(id)) {
				OrderDinner od = orderDinnerManager.get(id);
				if (od != null) {
					//根据订单的下单人判断是否管理员
					if (StringUtils.isEmpty(od.getConsId()) || !appUserManager.exists(Integer.parseInt(od.getConsId()))) {
						return AppResultUtil.createErrorDto("100", "找不到该操作用户信息,请联系管理员");
					}
					AppUser user = appUserManager.get(Integer.parseInt(od.getConsId()));
					if (user == null) {
						return AppResultUtil.createErrorDto("100", "找不到该操作用户信息,请联系管理员");
					}
					OrderDinnerOutPutDto dto = new OrderDinnerOutPutDto();
					//设置订单信息
					dto.setId(id);
					dto.setNumber(od.getNumber());
					if (od.getCreateTime() != null) {
						dto.setCreateTime(DateHelper.formatDate(od.getCreateTime(), DateHelper.DATE_TIME_STRING));
					}
					dto.setStatus(od.getStatus());
					//设置用户信息
					dto.setConsId(od.getConsId());
					String dinnerTime = "";
					if (od.getDinnerTime() != null) {
						dinnerTime = sdf.format(od.getDinnerTime());
						dinnerTime = DateUtils.getWeekOfDates(od.getDinnerTime()) + "  " + dinnerTime;
					}
					dto.setDinnerTime(dinnerTime);
					if (StringUtils.isNotEmpty(od.getConsId())) {
						if (appUserManager.exists(Integer.parseInt(od.getConsId()))) {
							AppUser cons = appUserManager.get(Integer.parseInt(od.getConsId()));
							dto.setUserName(cons.getUserName());
							if (StringUtils.isNotEmpty(cons.getDepartmentId() == null ? "" : cons.getDepartmentId().toString())) {
								if (deptManager.exists(Long.parseLong(cons.getDepartmentId().toString()))) {
									Department dept = deptManager.get(Long.parseLong(cons.getDepartmentId().toString()));
									dto.setDept(dept.getName());
								}
							}


							if (StringUtils.isNotEmpty(cons.getAddress())) {
								ElementDto el = elementGroupManager.getElementById(Long.parseLong(cons.getAddress()));
								if (el != null) {
									dto.setAddress(el.getItemname());
								}

							}
							dto.setMobile(cons.getUserMobile());
						}
					}

					int    isOver = 0;
					String res    = getOrderTime(od.getOrgId(), "orderTime");
					if (StringUtils.isNotEmpty(res)) {//超出
						isOver = 1;
					}
					try {
						if (DateUtils.checkIsOver(sdf.format(od.getDinnerTime()), isOver)) {
							dto.setIsCancel(0);//不展示取消按钮
						} else {
							dto.setIsCancel(1);//展示取消按钮
						}
					} catch (Exception e) {
						log.error(e.getMessage());
						e.printStackTrace();
						return AppResultUtil.createErrorDto("100", "获取订单详情失败");
					}
					//设置订单详情信息
					Map<String, Object> map = getOrderInfoList(id, user);
					if (map != null) {
						if (map.containsKey("list")) {
							List<OrderDinnerInfoDto> list = (List<OrderDinnerInfoDto>) map.get("list");
							if (list != null && list.size() > 0) {
								dto.setOrderInfoList(list);
							}
						}
						if (map.containsKey("sumCount")) {//总份数
							if (map.get("sumCount") != null && StringUtils.isNotEmpty(map.get("sumCount").toString())) {
								dto.setSumCount(Integer.parseInt(map.get("sumCount").toString()));
							}
						}
						if (map.containsKey("isHaveMe")) {//判断是否有自己的单(包含会议餐)，没有自己的单的情况下就不展示取消按钮
							if (map.get("isHaveMe") != null && StringUtils.isNotEmpty(map.get("isHaveMe").toString())) {
								if ("0".equals(map.get("isHaveMe").toString())) {
									//设置显示取消按钮
									dto.setIsCancel(0);
								}
							}
						}
						if (map.containsKey("sumIntegral")) {//总积分
							if (map.get("sumIntegral") != null && StringUtils.isNotEmpty(map.get("sumIntegral").toString())) {
								dto.setSumIntegral(Integer.parseInt(map.get("sumIntegral").toString()));
							}
						}

						if (map.containsKey("meetCount")) {//会议餐
							if (map.get("meetCount") != null && StringUtils.isNotEmpty(map.get("meetCount").toString())) {
								dto.setMeetCount(Integer.parseInt(map.get("meetCount").toString()));
							}
						}

						if (map.containsKey("orderInfoStr")) {//订单描述
							if (map.get("orderInfoStr") != null && StringUtils.isNotEmpty(map.get("orderInfoStr").toString())) {
								dto.setOrderInfoStr(map.get("orderInfoStr").toString());
							}
						}
					}
					if (StringUtil.isNotEmpty(od.getRemark())) {
						dto.setRemark(od.getRemark());
					} else {
						dto.setRemark("无");
					}
					dto.setIsTempOrder(od.getIsTempOrder());//是否临时工作餐0代表非临时工作餐1代表是
					//设置评价信息
					UserEvaluate ue = userEvaluateManager.findByOrderId(id, "2");
					if (ue != null) {
						dto.setComment(ue.getComment());
						if (!";".equals(ue.getEvaluateImages()) && ue.getEvaluateImages().length() > 1) {
							dto.setEvaluateImages(ue.getEvaluateImages());
						}
						dto.setStar(ue.getStar());
					}
					return AppResultUtil.createSuccesDto(dto);
				}
			}
		} catch (Exception e) {
			log.error("获取订单详情失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取订单详情失败");
		}

		return AppResultUtil.createErrorDto("100", "找不到该单据");
	}

	/**
	 * 取消订单(需判断订单的订餐时间是否在当前日期的订餐时间之后的)
	 */
	@Override
	public AppResultDto cancelOrderDinner(Long id, String wxUserId, String orgId) {
		AppUser appUser = appUserManager.get(Integer.parseInt(wxUserId));
		String  userId  = appUser.getId().toString();
		//判断时间有没有超出--首先判断订餐时间有没有超过当前时间，如果订餐时间已经过了当前时间，那么不能取消，如果订餐时间等于当天，那么需要判断是否超过订餐的设置的时间
		try {
			RechargeSet reSet = rechargeSetManager.findByOrgId(orgId);
			if (reSet == null) {
				return AppResultUtil.createErrorDto("100", "该项目下未设置积分，无法提交");
			}
			if (orderDinnerManager.exists(id)) {
				OrderDinner orderDinner = orderDinnerManager.get(id);
				if (orderDinner != null) {
					Date   dinnerTime = orderDinner.getDinnerTime();//下单时间
					String res        = isPower(orgId, sdf.format(dinnerTime));
					if (StringUtils.isNotEmpty(res)) {
						return AppResultUtil.createErrorDto("100", "您不能再次取消订单了哦");
					}
					List<OrderDinnerInfo> list = orderDinnerInfoManager.findByOrderId(id);
					if (list != null && list.size() > 0) {
						for (int i = 0; i < list.size(); i++) {
							OrderDinnerInfo orderInfo = list.get(i);
							if (orderInfo != null) {
								if (!"1".equals(orderInfo.getIsMeetFood())) {
									if (StringUtils.isNotEmpty(orderInfo.getConsId()) && appUserManager.exists(Integer.parseInt(orderInfo.getConsId()))) {
										AppUser consUser = appUserManager.get(Integer.parseInt(orderInfo.getConsId()));
										if (consUser != null) {
											int integral = consUser.getIntegral() + reSet.getDayCount();
											IntegralRecodeInfo intRecode = new IntegralRecodeInfo(userId, 3, consUser.getUserName(), consUser.getUserMobile(), consUser.getIntegral()
													, integral, new Date(), reSet.getDayCount() == null ? "0" : reSet.getDayCount().toString(), orgId, consUser.getId().toString());
											integralRecodeInfoManager.save(intRecode);//保存回转记录
											//修改用户积分
											consUser.setIntegral(integral);
											consUser.setModifier(userId);
											consUser.setModifyTime(new Date());
											appUserManager.saveOrUpdateAppUser(consUser);
										}
									}
								}
							}
						}
					}
					orderDinner.setStatus("4");//取消订单
					orderDinner.setModifier(userId);
					orderDinner.setModifyTime(new Date());
					orderDinnerManager.updateModel(orderDinner);
					cancelOrderDinner(orderDinner, userId);
					return AppResultUtil.createSuccesDto();
				}
			}
		} catch (Exception e) {
			log.error("取消订单失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "取消订单失败");
		}

		return AppResultUtil.createErrorDto("100", "找不到该单据");
	}

	/**
	 * 取消所选单据相对应的父单据
	 *
	 * @param orderDinner
	 */
	public void cancelOrderDinner(OrderDinner orderDinner, String userId) {
		int isCancel = 0;
		if (orderDinner != null && StringUtils.isNotEmpty(orderDinner.getParentOrderId())) {
			if (orderDinnerManager.exists(Long.parseLong(orderDinner.getParentOrderId()))) {
				OrderDinner parentOrder = orderDinnerManager.get(Long.parseLong(orderDinner.getParentOrderId()));
				if ("1".equals(parentOrder.getStatus())) {//只有单据在待送餐的情况下才需要判断这些
					//获取父单据的详情
					List<OrderDinnerInfo> orderInfoList = orderDinnerInfoManager.findByOrderId(parentOrder.getId());
					//当详情为空时，代表父单据下只有代订餐品
					if (orderInfoList == null || orderInfoList.size() <= 0) {
						isCancel = 1;
						//获取parentOrderId为该id的所有状态为1的订单，如果没有，说明都已经取消了
						List<OrderDinner> parentOrderList = orderDinnerManager.getOrderDinnerByParentOrderId(orderDinner.getParentOrderId(), "1");
						if (parentOrderList == null || parentOrderList.size() <= 0) {
							isCancel = 1;
						} else {
							isCancel = 0;
						}
					} else {
						isCancel = 0;
					}
				}
				//允许取消
				if (isCancel == 1) {
					parentOrder.setStatus("4");
					parentOrder.setModifyTime(new Date());
					parentOrder.setModifier(userId);
					orderDinnerManager.updateModel(parentOrder);
				}
			}
		}

	}

	public String isPower(String orgId, String dinnerTime) {
		String res    = "";
		int    isOver = orderDinnerManager.isOver(orgId, "orderTime");
		try {
			if (DateUtils.checkIsOver(dinnerTime, isOver)) {
				res = "抱歉，已超出时间";
			}
		} catch (Exception e) {
			e.printStackTrace();
			res = "时间比较异常:" + e.getMessage();
			log.error(res);
		}
		log.info(res);
		return res;
	}

	/**
	 * 获取当天下的所有的订单详情列表
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public AppResultDto getAllOrderInfo(String orgId, String wxUserId) {
		try {
			List<Map<String, Object>> list    = orderDinnerInfoManager.findBySysdate(orgId);
			List<OrderDinnerInfoDto>  dtoList = new ArrayList<OrderDinnerInfoDto>();
			Map<String, Object>       map     = new HashMap<String, Object>();
			int                       count   = 0;
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> orderInfo = list.get(i);
					if (orderInfo != null) {
						OrderDinnerInfoDto orderInfoDto = new OrderDinnerInfoDto();
//						orderInfoDto.setId(orderInfo.get("id")==null?"":orderInfo.get("id").toString());
						orderInfoDto.setMealId(orderInfo.get("mealId") == null ? "" : orderInfo.get("mealId").toString());
						orderInfoDto.setMealName(orderInfo.get("mealName") == null ? "" : orderInfo.get("mealName").toString());
						orderInfoDto.setStapleFood(orderInfo.get("stapleFood") == null ? "" : orderInfo.get("stapleFood").toString());
						orderInfoDto.setStapleFoodStr(orderInfo.get("stapleFoodStr") == null ? "" : orderInfo.get("stapleFoodStr").toString());
						if (StringUtils.isNotEmpty(orderInfo.get("foodCount") == null ? "" : orderInfo.get("foodCount").toString())) {
							int foodCount = Integer.parseInt(orderInfo.get("foodCount") == null ? "" : orderInfo.get("foodCount").toString());
							orderInfoDto.setFoodCount(foodCount);
							count = count + foodCount;
						}
						if (StringUtils.isNotEmpty(orderInfo.get("mealName") == null ? "" : orderInfo.get("mealName").toString()) && StringUtils.isNotEmpty(orderInfo.get("stapleFood") == null ? "" : orderInfo.get("stapleFood").toString())) {
							orderInfoDto.setMealFood(orderInfo.get("mealName") + "(" + orderInfo.get("stapleFoodStr") + ")");
						} else {
							orderInfoDto.setMealFood(orderInfo.get("mealName") == null ? "" : orderInfo.get("mealName").toString());
						}

						dtoList.add(orderInfoDto);
					}
				}
			} else {
				return AppResultUtil.createErrorDto("100", "当前无待送餐的餐品");
			}
			map.put("sumCount", count);
			map.put("list", dtoList);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			log.error("获取今日订单失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "当前无待送餐的餐品");
		}

	}

	/**
	 * 确认订单
	 */
	@Transactional
	public AppResultDto confirmService(String orgId, String wxUserId) {
		AppUser appUser = appUserManager.get(Integer.parseInt(wxUserId));
		String  userId  = appUser.getId().toString();
		try {
			List<Map<String, Object>> list = orderDinnerInfoManager.findBySysdate(orgId);
			if (list != null && list.size() > 0) {
				orderDinnerManager.updateOrderStatus(orgId, userId);
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "当前无待送餐的餐品");
			}

		} catch (Exception e) {
			log.error("确认送达失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "确认送达失败");
		}
	}

	/**
	 * 发送微信客服消息
	 *
	 * @param orgId
	 * @return
	 */
	@Async
	public void sendWechatMessage(String orgId, List<OrderDinner> list) {
		try {
			List<WxUser> wxList = new ArrayList<WxUser>();
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					OrderDinner order  = list.get(i);
					String      consId = order.getConsId();
					if (StringUtils.isNotEmpty(consId) && appUserManager.exists(Integer.parseInt(consId))) {
						AppUser user = appUserManager.get(Integer.parseInt(consId));
						if (user != null && user.getWxUserId() != null) {
							WxUser wxUser = scWxuserManager.get(user.getWxUserId());
							if (wxUser != null) {
								if (!wxList.contains(wxUser)) {//去除重复的用户
									wxList.add(wxUser);
								}
							}
						}
					}
				}
			}
			//获取有效的用户
			if (wxList != null && wxList.size() > 0) {
				for (int i = 0; i < wxList.size(); i++) {
					WxUser wxUser = wxList.get(i);
					log.info("wechat wxUserId:" + wxUser.getId());
					String str = weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), "您" + DateHelper.formatDate(new Date(), DateHelper.CURRENT_DATE) + "的订餐已于" + DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING) + "送达，请前往领取！");
					log.info("result" + i + ":" + str);
				}
			}
		} catch (Exception e) {
			log.error("消息推送失败:" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 导出今日订餐汇总
	 */
	@Override
	public AppResultDto exportExcel(String orgId) {
		log.info("begin exportExcel:" + orgId);
		String date = DateHelper.formatDate(new Date(),DateHelper.CURRENT_DATE);
		HSSFWorkbook wb = new HSSFWorkbook();
		try {
			List<MealExcelDto>        mealList    = orderDinnerInfoManager.getOrderExcelListByMeal(orgId,date);
			List<MealExcelDto>        deptList    = orderDinnerInfoManager.getOrderExcelListByDept(orgId,date);
			List<Map<String, Object>> userList    = orderDinnerInfoManager.getOrderExcelListByUserName(orgId,date);
			List<MealExcelDto>        addressList = orderDinnerInfoManager.getOrderExcelListByAddress(orgId,date);
//			List<Map<String,Object>> sysList=orderDinnerManager.exportExcelByAddress(orgId);
			List<Map<String, Object>> sysList = orderDinnerManager.exportByAddress(orgId,date);
			if (mealList == null || (mealList != null && mealList.size() == 0)) {
				return AppResultUtil.createErrorDto("100", "今日没有订单，无法导出");
			}
			//		String path=SERVER_ADDRESS+"/upload/OrderExcel.xlsx";
			//		String path=this.getClass().getClassLoader().getResource("./upload/OrderExcel.xlsx").getPath();
			//设置导出的excel路径
			String path = setPath("upload/OrderExcel"+orgId+".xls");
			File   file = new File(new ExcelUtils().getPath(path));
			System.out.println("path:" + path);
			String sheetName = "";
			if (sysList != null && sysList.size() > 0) {
				sheetName = "今日餐品汇总";
				List<Map<String, Object>> mapList = orderDinnerManager.getAllMealName(orgId);
//					String[] titles={"地址","部门/领导","川菜","粤菜","素餐","刀削面","油泼面","杂酱面","河粉","水果餐","鲜奶","卡士","酸奶","咸鸭蛋","换馒头","换花卷","纯馒头","纯花卷","会议餐","合计"};
//					String [] fieldNames={"address","deptname","chuan","yue","su","dao","you","za","he","te","xian","ka","suan","egg","buns","rolls","workBuns","workRoll","meet","heji"};
				String[] titles     = {"地址", "部门/领导"};
				String[] fieldNames = {"address", "deptname"};
				titles = orderDinnerManager.getTitles(mapList, titles, 1);
				titles = StringUtil.insert(titles, "换花卷");
				titles = StringUtil.insert(titles, "换馒头");
				titles = StringUtil.insert(titles, "合计");
				fieldNames = orderDinnerManager.getTitles(mapList, fieldNames, 2);
				fieldNames = StringUtil.insert(fieldNames, CodeConstants.ROLLS);
				fieldNames = StringUtil.insert(fieldNames, CodeConstants.BUNS);
				fieldNames = StringUtil.insert(fieldNames, "heji");
				file = ExcelUtils.exportExcel(file, wb, sheetName, sysList, titles, fieldNames);
			}
			if (mealList != null && mealList.size() > 0) {
				sheetName = "餐品和数量汇总";
				String[] titles     = {"餐品", "数量"};
				String[] fieldNames = {"mName", "other"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, mealList, titles, fieldNames);
			}
			if (addressList != null && addressList.size() > 0) {
				sheetName = "餐品数量和送餐地址汇总";
				String[] titles     = {"送餐地址", "餐品"};
				String[] fieldNames = {"other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, addressList, titles, fieldNames);
			}
			if (deptList != null && deptList.size() > 0) {
				sheetName = "餐品数量和部门汇总";
				String[] titles     = {"部门", "餐品"};
				String[] fieldNames = {"other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, deptList, titles, fieldNames);
			}
			if (userList != null && userList.size() > 0) {
				sheetName = "餐品数量和预订人汇总";
				String[] titles     = {"部门", "订餐人", "餐品"};
				String[] fieldNames = {"deptname", "other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, userList, titles, fieldNames);
			}
			log.info("导出地址：" + path);
			return AppResultUtil.createSuccesDto(path);
		} catch (Exception e) {
			log.error("导出失败" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出失败:" + e.getMessage());
		}
	}


	public AppResultDto exportExcel2(String orgId,String date) {
		log.info("begin exportExcel2:" + orgId+";date:"+date);
		String nextDate = "";
		//系统自动获取，系统判断下一个上菜的日期对应的时间，拿到后取该日期的餐
		if(StringUtils.isEmpty(date)){
			date =  DateHelper.formatDate(new Date(),DateHelper.CURRENT_DATE);
			log.info("begin exportExcel2:" + orgId+";date:"+date);
			nextDate = mealManager.getNextMealDate(Integer.parseInt(orgId),date,1);
			log.info("begin exportExcel2:" + orgId+";date:"+date+";nextDate:"+nextDate);
		}
		//手动拿哪一天的餐，指定日期拿餐
		if(StringUtils.isEmpty(nextDate)){
			nextDate = date;
			log.info("begin exportExcel2:" + orgId+";date:"+date+";nextDate2:"+nextDate);
		}

		HSSFWorkbook wb = new HSSFWorkbook();
		try {
			List<MealExcelDto>        mealList    = orderDinnerInfoManager.getOrderExcelListByMeal(orgId,nextDate);
			List<MealExcelDto>        deptList    = orderDinnerInfoManager.getOrderExcelListByDept(orgId,nextDate);
			List<Map<String, Object>> userList    = orderDinnerInfoManager.getOrderExcelListByUserName(orgId,nextDate);
			List<MealExcelDto>        addressList = orderDinnerInfoManager.getOrderExcelListByAddress(orgId,nextDate);
			List<Map<String, Object>> sysList = orderDinnerManager.exportByAddress(orgId,nextDate);
			if (mealList == null || (mealList != null && mealList.size() == 0)) {
				return AppResultUtil.createErrorDto("100", "今日没有订单，无法导出");
			}
			//设置导出的excel路径
			String path = setPath("upload/OrderExcel"+orgId+".xls");
			File   file = new File(new ExcelUtils().getPath(path));
			System.out.println("path:" + path);
			String sheetName = "";
			if (sysList != null && sysList.size() > 0) {
				sheetName = "今日餐品汇总";
				List<Map<String, Object>> mapList = orderDinnerManager.getAllMealName(orgId);
				String[] titles     = {"地址", "部门/领导"};
				String[] fieldNames = {"address", "deptname"};
				titles = orderDinnerManager.getTitles(mapList, titles, 1);
				titles = StringUtil.insert(titles, "换花卷");
				titles = StringUtil.insert(titles, "换馒头");
				titles = StringUtil.insert(titles, "合计");
				fieldNames = orderDinnerManager.getTitles(mapList, fieldNames, 2);
				fieldNames = StringUtil.insert(fieldNames, CodeConstants.ROLLS);
				fieldNames = StringUtil.insert(fieldNames, CodeConstants.BUNS);
				fieldNames = StringUtil.insert(fieldNames, "heji");
				file = ExcelUtils.exportExcel(file, wb, sheetName, sysList, titles, fieldNames);
			}
			if (mealList != null && mealList.size() > 0) {
				sheetName = "餐品和数量汇总";
				String[] titles     = {"餐品", "数量"};
				String[] fieldNames = {"mName", "other"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, mealList, titles, fieldNames);
			}
			if (addressList != null && addressList.size() > 0) {
				sheetName = "餐品数量和送餐地址汇总";
				String[] titles     = {"送餐地址", "餐品"};
				String[] fieldNames = {"other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, addressList, titles, fieldNames);
			}
			if (deptList != null && deptList.size() > 0) {
				sheetName = "餐品数量和部门汇总";
				String[] titles     = {"部门", "餐品"};
				String[] fieldNames = {"other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, deptList, titles, fieldNames);
			}
			if (userList != null && userList.size() > 0) {
				sheetName = "餐品数量和预订人汇总";
				String[] titles     = {"部门", "订餐人", "餐品"};
				String[] fieldNames = {"deptname", "other", "mName"};
				file = ExcelUtils.exportExcel(file, wb, sheetName, userList, titles, fieldNames);
			}
			log.info("导出地址：" + path);
			return AppResultUtil.createSuccesDto(path);
		} catch (Exception e) {
			log.error("导出失败" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出失败:" + e.getMessage());
		}
	}

	@Override
	public OrderDinner getById(Long id) {
		if (orderDinnerManager.exists(id)) {
			return orderDinnerManager.get(id);
		}
		return null;
	}

	/**
	 * 评价后修改订单表的星级字段
	 *
	 * @param id
	 * @param star
	 * @param consId
	 * @return
	 */
	@Override
	public String updateOrderByStar(Long id, int star, String consId) {
		String res = "FAIL";
		try {
			if (orderDinnerManager.exists(id)) {
				OrderDinner order = orderDinnerManager.get(id);
				order.setModifier(consId);
				order.setModifyTime(new Date());
				order.setStar(star);
				order.setStatus("3");
				orderDinnerManager.updateModel(order);
				res = "SUCCESS";
			}
		} catch (Exception e) {
			log.error("评价失败" + e.getMessage());
			e.printStackTrace();
			return res;
		}
		return res;
	}

	/**
	 * 数据统计
	 */
	@Override
	public WebPageResultDto getDataStatistics(String orgId, int type, int dateType,
											  String year, String time, int operationType, int pageSize, int pageNo) {
		List<Map<String, Object>> list      = new ArrayList<Map<String, Object>>();
		String                    sheetName = "";
		try {
			if (type == 1) {//订餐统计
				list = orderDinnerManager.getSumOrder(orgId, dateType, year, time);
				if (operationType == 2) {
					if (list != null && list.size() > 0) {
						sheetName = "订餐统计";
//						String[] titles={"公司名称","总份数","临时工作餐","订餐率","组合","工作餐","大份米饭","小份米饭","花卷","馒头","会议餐","单品"};
//						String [] fieldNames={"companyName","totalNum","tempWorkFood","rate","groupFood","soupFood","bigRice","smallRice","roll","buns","fruitFood","singleFood"};
						String[] titles     = {"总份数", "订餐率", "组合", "工作餐", "大份米饭", "小份米饭", "花卷", "馒头", "会议餐", "单品"};
						String[] fieldNames = {"totalNum", "rate", "groupFood", "soupFood", "bigRice", "smallRice", "roll", "buns", "fruitFood", "singleFood"};
						String   path       = exportExcelData(list, sheetName, titles, fieldNames);
						return new WebPageResultDto("200", "成功", path);
					} else {
						return new WebPageResultDto("100", "数据为空，无法导出", null);
					}
				}
			} else if (type == 2) {//评价统计
				list = orderDinnerManager.getStarOrderList(orgId, dateType, year, time);
				if (operationType == 2) {
					if (list != null && list.size() > 0) {
						sheetName = "评价统计";
						String[] titles     = {"评星", "订单数", "占比"};
						String[] fieldNames = {"starStr", "sumCount", "rate"};
						String   path       = exportExcelData(list, sheetName, titles, fieldNames);
						return new WebPageResultDto("200", "成功", path);
					} else {
						return new WebPageResultDto("100", "数据为空，无法导出", null);
					}

				}
			} else if (type == 3) {//部门统计
				list = orderDinnerManager.getDeptOrderList(orgId, dateType, year, time);
				if (operationType == 2) {
					if (list != null && list.size() > 0) {
						sheetName = "部门统计";
//						String[] titles={"公司名称","部门","餐品份数","组合","临时工作餐","工作餐","大份米饭","小份米饭","花卷","馒头","会议餐","单品"};
//						String [] fieldNames={"companyName","dept","totalNum","groupFood","tempWorkFood","soupFood","bigRice","smallRice","roll","buns","fruitFood","singleFood"};
						String[] titles     = {"部门", "餐品份数", "组合", "工作餐", "大份米饭", "小份米饭", "花卷", "馒头", "会议餐", "单品"};
						String[] fieldNames = {"dept", "totalNum", "groupFood", "soupFood", "bigRice", "smallRice", "roll", "buns", "fruitFood", "singleFood"};
						String   path       = exportExcelData(list, sheetName, titles, fieldNames);
						return new WebPageResultDto("200", "成功", path);
					} else {
						return new WebPageResultDto("100", "数据为空，无法导出", null);
					}

				}
			} else if (type == 4) {//个人统计
				list = orderDinnerManager.getConsOrderList(orgId, dateType, year, time);
				if (operationType == 2) {
					if (list != null && list.size() > 0) {
						sheetName = "个人统计";
						String[] titles     = {"公司名称", "手机号", "姓名", "部门", "餐品份数", "会议餐", "临时工作餐"};
						String[] fieldNames = {"companyName", "mobile", "userName", "dept", "sumCount", "fruitFood", "tempWorkFood"};
						String   path       = exportExcelData(list, sheetName, titles, fieldNames);
						return new WebPageResultDto("200", "成功", path);
					} else {
						return new WebPageResultDto("100", "数据为空，无法导出", null);
					}

				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto("100", "数据异常，请联系管理员", null);
		}
		ListPage         page = PageUtils.getListPage(list, pageNo, pageSize);
		WebPageResultDto dto  = new WebPageResultDto("200", "成功", page.getDataList());
		if (list != null && list.size() > 0) {
			dto.setCount(Long.parseLong(String.valueOf(list.size())));
		} else {
			dto.setCount(Long.parseLong("0"));
		}

		return dto;
	}

	public String exportExcelData(List<Map<String, Object>> list, String sheetName, String[] titles, String[] fieldNames) throws IOException {
		HSSFWorkbook wb   = new HSSFWorkbook();
		String       path = setPath("upload/OrderDataExcel.xls");
		File         file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);

		ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames);
		return path;
	}

	/**
	 * 获取该项目下最开始新增数据的创建时间
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public String getTopCreateTime(String orgId) {
		return orderDinnerManager.getTopCreateTime(orgId);
	}

	@Override
	public String getOrderTime(String orgId, String elName) {
		return orderDinnerManager.getOrderTime(orgId, elName);
	}

	@Override
	public int getMealCarList(String userId, String orgId) {
		return mealCarManager.getMealCarList(userId, orgId);
	}

	@Override
	public List<OrderDinner> findByCons(String consId, String orgId,
										String status) {
		return orderDinnerManager.findByCons(consId, orgId, status);
	}

	@Override
	public int getMealCarCountByMealId(String orgId, String userId,
									   String time, String mealId) {
		return mealCarManager.getMealCarCountByMealId(userId, time, mealId);
	}

	@Override
	public AppResultDto submitTempOrder(Map<String, Object> parement) {
		String                   orgId   = parement.get("orgId").toString();
		String                   userId  = parement.get("userId").toString();
		String                   time    = parement.get("time").toString();
		String                   remark  = parement.get("remark") == null ? "" : parement.get("remark").toString();
		List<TempOrderDinnerDto> dtoList = (List<TempOrderDinnerDto>) parement.get("dtoList");
		try {
			OrderDinner      orderDinner = saveParentOrder(userId, orgId, time, 0, remark);
			List<MealCarDto> mealDtoList = getMCDtoList(dtoList, userId);
			if (mealDtoList != null && mealDtoList.size() > 0) {
				for (int i = 0; i < mealDtoList.size(); i++) {
					MealCarDto mealDto = mealDtoList.get(i);
					saveOrderDinnerInfo(mealDto, orderDinner.getId(), userId, orgId, sdf.parse(time));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			log.error("创建临时工作餐失败:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "提交失败，请联系管理员");
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 转换类型
	 *
	 * @param dtoList
	 * @param userId
	 * @return
	 */
	private List<MealCarDto> getMCDtoList(List<TempOrderDinnerDto> dtoList, String userId) {
		List<MealCarDto> mealDtoList = new ArrayList<MealCarDto>();
		if (dtoList != null && dtoList.size() > 0) {
			for (int i = 0; i < dtoList.size(); i++) {
				TempOrderDinnerDto tempDto = dtoList.get(i);
				MealCarDto         mealDto = new MealCarDto();
				mealDto.setFoodCount(tempDto.getFoodCount());
				mealDto.setIsMeetingOrder(0);
				mealDto.setMealId(tempDto.getMealId());
				mealDto.setUserId(userId);
				if (StringUtils.isNotEmpty(tempDto.getStapleFood())) {
					String     stapleFoodStr = "";
					ElementDto el            = elementGroupManager.getElementById(Long.parseLong(tempDto.getStapleFood()));
					if (el != null) {
						stapleFoodStr = el.getItemname();
					}
					mealDto.setStapleFoodStr(stapleFoodStr);
				}
				mealDtoList.add(mealDto);
			}
		}
		return mealDtoList;
	}

	@Override
	public AppResultDto getMealRanking(String orgId) {
		Date   currentDate = new Date();
		String monthStr    = DateUtils.getPrevMonth(DateUtils.getDate(currentDate, "yyyy-MM-dd"), "yyyy-MM");
		List   list        = new ArrayList();
		String mealJson    = baseRedisService.get(CodeConstants.ORG_MEAL_RANK + orgId + "_" + monthStr);
		if (StringUtils.isNotEmpty(mealJson)) {
			list = (List) JSONArray.parseArray(mealJson);
		} else {
			list = orderDinnerManager.getMealRanking(orgId);
			baseRedisService.set(CodeConstants.ORG_MEAL_RANK + orgId + "_" + monthStr, JSONArray.toJSONString(list));
		}
		return AppResultUtil.createSuccesDto(list);
	}

	@Override
	public String setPath(String fileName) {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		//"upload/OrderExcel.xls"
		String path = webappRoot + fileName;
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		return path;
	}

	@Override
	public void getOrderInfoTask(String orgId) {
		if (StringUtils.isNotEmpty(orgId)) {
			String res = getOrderTime(orgId, "importTime");
			if (StringUtils.isEmpty(res)) {
			} else {
				exportExcel(orgId);
			}
		} else {
			String orgIds = serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
			log.info("getOrderInfoTask/orgIds:" + orgIds);
			if (StringUtils.isNotEmpty(orgIds)) {
				String[] orgArr = orgIds.split(",");
				for (String org : orgArr) {
					log.info("getOrderInfoTask/orgId:" + org);
					if (StringUtils.isNotEmpty(org)) {
						String res = getOrderTime(org, "importTime");
						log.info("getOrderInfoTask/res:" + res);
						if (StringUtils.isEmpty(res)) {
						} else {
							redisExport(org);
						}
					}
				}

			}
		}
	}

	@Override
	public void getOrderInfoTask2(String orgId,String sysDate) {
		if (StringUtils.isNotEmpty(orgId)) {
			String res = getOrderTime(orgId, "importTime");
			log.info("getOrderInfoTask2-res:{}",res);
			if (StringUtils.isEmpty(res)) {
			} else {
				exportExcel2(orgId,sysDate);
			}
		} else {
			String orgIds = serviceProjectAllocationManager.getServiceProjectByServiceCode("DCFW");
			log.info("getOrderInfoTask/orgIds:" + orgIds);
			if (StringUtils.isNotEmpty(orgIds)) {
				String[] orgArr = orgIds.split(",");
				for (String org : orgArr) {
					log.info("getOrderInfoTask/orgId:" + org);
					if (StringUtils.isEmpty(org)) {
						continue;
					}
					String res = getOrderTime(org, "importTime");
					log.info("getOrderInfoTask/res:" + res);
					if (StringUtils.isEmpty(res)) {
					} else {
						redisExport2(org,sysDate);
					}
				}

			}
		}
	}

	private void redisExport(String orgId) {
		String time = DateHelper.formatDate(new Date(), DateHelper.DATE);
		log.info("-------------redisExport---time:" + time + "--------------------------");
		String key = "getOrder_" + orgId +"_"+ time;
		log.info("-------------redisExport---key:" + key + "--------------------------");
		String mealJson = baseRedisService.get(key);
		log.info("-------------redisExport---mealJson:" + mealJson + "--------------------------");
		int count = 0;
		if (StringUtils.isNotEmpty(mealJson)) {
			log.info("-------------redisExport---redis获取:" + mealJson + "--------------------------");
			count = Integer.parseInt(mealJson);
			count++;
			baseRedisService.set(key, count + "");
		} else {
			count++;
			log.info("-------------redisExport---设置redis---count:" + count + "-----------------------");
			baseRedisService.set(key, count + "");
			log.info("-------------redisExport---设置redis--------------------------");
		}
		log.info("-----------redisExport-----count:" + count + "--------------------------");
		if (count <= 5) {
			log.info("-----------redisExport-----执行导出开始------------------------");
			exportExcel(orgId);
			log.info("-----------redisExport-----执行导出结束------------------------");
		}
	}


	private void redisExport2(String orgId,String date) {
		String time = DateHelper.formatDate(new Date(), DateHelper.DATE);
		log.info("-------------redisExport---time:" + time + "--------------------------");
		String key = "getOrder_" + orgId +"_"+ time;
		log.info("-------------redisExport---key:" + key + "--------------------------");
		String mealJson = baseRedisService.get(key);
		log.info("-------------redisExport---mealJson:" + mealJson + "--------------------------");
		int count = 0;
		if (StringUtils.isNotEmpty(mealJson)) {
			log.info("-------------redisExport---redis获取:" + mealJson + "--------------------------");
			count = Integer.parseInt(mealJson);
			count++;
			baseRedisService.set(key, count + "");
		} else {
			count++;
			log.info("-------------redisExport---设置redis---count:" + count + "-----------------------");
			baseRedisService.set(key, count + "");
			log.info("-------------redisExport---设置redis--------------------------");
		}
		log.info("-----------redisExport-----count:" + count + "--------------------------");
		if (count <= 10) {
			log.info("-----------redisExport-----执行导出开始------------------------");
			exportExcel2(orgId,date);
			log.info("-----------redisExport-----执行导出结束------------------------");
		}
	}
}
