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

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.ConsumerDto;
import com.palmnest.application.dto.MealExcelDto;
import com.palmnest.application.dto.output.OrderDinnerInfoDto;
import com.palmnest.dao.ElementGroupDao;
import com.palmnest.dao.dinner.MealDao;
import com.palmnest.dao.dinner.OrderDinnerInfoDao;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.model.Element;
import com.palmnest.model.dinner.Meal;
import com.palmnest.model.dinner.OrderDinnerInfo;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.service.dinner.manager.OrderDinnerInfoManager;
import com.palmnest.service.impl.GenericManagerImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("orderDinnerInfoManager")
public class OrderDinnerInfoManagerImpl extends GenericManagerImpl<OrderDinnerInfo, Long> implements OrderDinnerInfoManager {


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

	private OrderDinnerInfoDao orderDinnerInfoDao;

	@Autowired
	public void setOrderDinnerInfoDao(OrderDinnerInfoDao orderDinnerInfoDao) {
		this.orderDinnerInfoDao = orderDinnerInfoDao;
		this.dao = orderDinnerInfoDao;
	}

	@Autowired
	private AppUserDao      appUserDao;
	@Autowired
	private MealDao         mealDao;
	@Autowired
	private ElementGroupDao elementGroupDao;

	/**
	 * 根据订单id获取订单的详情
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public List<OrderDinnerInfo> findByOrderId(Long orderId) {
		return orderDinnerInfoDao.findByOrderId(orderId);
	}

	@Override
	public int updateByIsEnabled(Long orderId) {
		return orderDinnerInfoDao.updateByIsEnabled(orderId);
	}

	/**
	 * 获取当天所有的订单详情
	 */
	@Override
	public List<Map<String, Object>> findBySysdate(String orgId) {
		return orderDinnerInfoDao.findBySysdate(orgId);
	}

	@Override
	public List<MealExcelDto> getOrderExcelListByMeal(String orgId,String date) {
		List<Map<String, Object>> list = orderDinnerInfoDao.getOrderExcelListByMeal(orgId,date);
		return getExcelList(list);
	}

	@Override
	public List<MealExcelDto> getOrderExcelListByDept(String orgId,String date) {
		List<Map<String, Object>> list = orderDinnerInfoDao.getOrderExcelListByDept(orgId,date);
		return getExcelList(list);
	}

	@Override
	public List<Map<String, Object>> getOrderExcelListByUserName(String orgId,String date) {
		List<Map<String, Object>> list = orderDinnerInfoDao.getOrderExcelListByUserName(orgId,date);
		return list;
	}

	public List<MealExcelDto> getExcelList(List<Map<String, Object>> list) {
		List<MealExcelDto> mealList = new ArrayList<MealExcelDto>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				if (map != null) {
					MealExcelDto dto = new MealExcelDto();
					if (map.containsKey("other")) {
						dto.setOther(map.get("other") == null ? "" : map.get("other").toString());
					}
					if (map.containsKey("mName")) {
						dto.setmName(map.get("mName") == null ? "" : map.get("mName").toString());
					}
					mealList.add(dto);
				}
			}
		}
		return mealList;
	}

	@Override
	public List<MealExcelDto> getOrderExcelListByAddress(String orgId,String date) {
		List<Map<String, Object>> list = orderDinnerInfoDao.getOrderExcelListByAddress(orgId,date);
		return getExcelList(list);
	}

	@Override
	public Map<String, List<ConsumerDto>> getUserByTime(String orgId,
														String time) {
		Map<String, List<ConsumerDto>> listMap    = new HashMap<String, List<ConsumerDto>>();
		List<ConsumerDto>              haveDto    = new ArrayList<ConsumerDto>();
		List<ConsumerDto>              notHaveDto = new ArrayList<ConsumerDto>();
		List<AppUser>                  list       = appUserDao.getUserByOrgIdAndRoleType(orgId, "'1','3'");//获取所有该项目下代订账号
		listMap.put("haveOrderList", haveDto);
		listMap.put("notHaveOrderList", notHaveDto);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				AppUser cons = list.get(i);
				if (cons != null) {
					ConsumerDto               dto       = new ConsumerDto(cons.getId().toString(), cons.getUserName(), cons.getUserMobile());
					List<Map<String, Object>> orderList = orderDinnerInfoDao.getOrderInfoByTime(String.valueOf(cons.getId()), time);//判断该用户是否有下过订单，在指定下单时间内
					if (orderList != null && orderList.size() > 0) {//有下单，就存入已下过单据的集合中
						dto.setIsOrdering(1);
						haveDto.add(dto);
					} else {//没有下单，就存入没有下过订单的集合中
						dto.setIsOrdering(0);
						notHaveDto.add(dto);
					}
				}
			}
			listMap.put("haveOrderList", haveDto);
			listMap.put("notHaveOrderList", notHaveDto);
		}
		return listMap;
	}

	@Override
	public List<Map<String, Object>> getOrderInfoByTime(String consId,
														String time) {
		return orderDinnerInfoDao.getOrderInfoByTime(consId, time);
	}

	@Override
	public List<Map<String, Object>> getMeetFood(String orgId, String time) {
		return orderDinnerInfoDao.getMeetFood(orgId, time);
	}

	@Override
	public List<Map<String, Object>> getTempOrder(String orgId, String time) {
		return orderDinnerInfoDao.getTempOrder(orgId, time);
	}

	@Override
	public List<OrderDinnerInfoDto> getOrderInfoByParentOrderId(String orderId, int isOver) {
		List<OrderDinnerInfoDto>  dtoList = new ArrayList<OrderDinnerInfoDto>();
		List<Map<String, Object>> list    = orderDinnerInfoDao.getOrderInfoByParentOrderId(orderId);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				OrderDinnerInfoDto  orderInfoDto  = new OrderDinnerInfoDto();
				Map<String, Object> map           = list.get(i);
				String              id            = map.get("id") == null ? "" : map.get("id").toString();
				String              mealId        = map.get("mealId") == null ? "" : map.get("mealId").toString();
				String              mealName      = map.get("mealName") == null ? "" : map.get("mealName").toString();
				String              isMeetFood    = map.get("isMeetFood") == null ? "" : map.get("isMeetFood").toString();
				String              mealFood      = "";
				String              stapleFood    = map.get("stapleFood") == null ? "" : map.get("stapleFood").toString();
				String              stapleFoodStr = map.get("stapleFoodStr") == null ? "" : map.get("stapleFoodStr").toString();
				String              dinnerTime    = map.get("dinnerTime") == null ? "" : map.get("dinnerTime").toString();
				String              orderIds      = map.get("orderId") == null ? "" : map.get("orderId").toString();
				int                 foodCount     = Integer.parseInt(map.get("foodCount") == null ? "0" : map.get("foodCount").toString());
				int                 status        = Integer.parseInt(map.get("status") == null ? "0" : map.get("status").toString());
				if (StringUtils.isNotEmpty(stapleFoodStr)) {
					mealFood = mealName + "(" + stapleFoodStr + ")";
				} else {
					mealFood = mealName;
				}
				orderInfoDto.setMealFood(mealFood);
				if (StringUtils.isNotEmpty(mealId)) {
					if (mealDao.exists(Long.parseLong(mealId))) {
						Meal meal = mealDao.get(Long.parseLong(mealId));
						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]);
								}
							}
						}
					}
				}
				String userId   = map.get("userId") == null ? "" : map.get("userId").toString();//订餐人
				String userName = map.get("userName") == null ? "" : map.get("userName").toString();//订餐人姓名
				String mobile   = map.get("mobile") == null ? "" : map.get("mobile").toString();//订餐人电话

				orderInfoDto.setId(id);
				orderInfoDto.setMealId(mealId);
				if (isMeetFood != null) {
					orderInfoDto.setIsMeetFood(Integer.parseInt(isMeetFood));
				}
				orderInfoDto.setOrderId(orderIds);
				if (StringUtils.isEmpty(mealName)) {
					Meal meal = mealDao.get(Long.parseLong(mealId));
					if (meal != null) {
						Element el = elementGroupDao.getElementId(Long.parseLong(meal.getMealCodeId()));
						if (el != null) {
							orderInfoDto.setMealName(el.getItemname());
						}
					}
				} else {
					orderInfoDto.setMealName(mealName);
				}
				orderInfoDto.setStapleFood(stapleFood);
				orderInfoDto.setStapleFoodStr(stapleFoodStr);
				orderInfoDto.setFoodCount(foodCount);
				orderInfoDto.setUserId(userId);
				orderInfoDto.setUserName(userName);
				orderInfoDto.setMobile(mobile);
				if (status == 4) {
					orderInfoDto.setCancelStatus(1);//已取消状态
				} else {
					orderInfoDto.setCancelStatus(0);//
				}
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					if (StringUtils.isNotEmpty(dinnerTime)) {
//						dinnerTime=sdf.format(sdf.parse(dinnerTime));
						orderInfoDto.setDinnerTime(dinnerTime);
						if (DateUtils.checkIsOver(dinnerTime, isOver)) {//返回true，代表超时了，不应该展示取消按钮
							orderInfoDto.setIsCancel(0);//不展示取消按钮
						} else {
							orderInfoDto.setIsCancel(1);//展示取消按钮
						}
//						Date dateTime=sdf.parse(sdf.format(new Date()));
//						Date weekDate=sdf.parse(dinnerTime);
//						if(dateTime.compareTo(weekDate)==0){
//							if(isOver==1){
//								orderInfoDto.setIsCancel(0);//不展示取消按钮
//							}else{
//								orderInfoDto.setIsCancel(1);//展示取消按钮
//							}
//						}else if(dateTime.after(weekDate)){//当前时间大于订餐时间
//							orderInfoDto.setIsCancel(0);
//						}else{
//							orderInfoDto.setIsCancel(1);//展示取消按钮
//						}
					}
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
				}
				dtoList.add(orderInfoDto);
			}
		}
		return dtoList;
	}

	@Override
	public int getOrderCount(String consId, String time) {
		return orderDinnerInfoDao.getOrderCount(consId, time);
	}

	@Override
	public List<Map<String, Object>> getSysdateByOrgId(String orgId) {
		return orderDinnerInfoDao.getSysdateByOrgId(orgId);
	}
}
