package com.palmnest.dao.dinner.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import cn.jiguang.common.utils.StringUtils;

import com.palmnest.dao.dinner.MealCarDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.dinner.MealCar;
@Repository("mealCarDao")
public class MealCarDaoImpl extends GenericDaoHibernate<MealCar, Long>implements MealCarDao{

private static Logger LOG = LoggerFactory.getLogger(MealCarDaoImpl.class);
	
	public MealCarDaoImpl(){
		super(MealCar.class);
	}

	/**
	 * 清空购物车
	 * @param consId 登录用户
	 * @return
	 */
	@Override
	public int removeMealCar(String consId) {
		String sql="delete from MealCar where creator=? ";
		return this.getSession().createQuery(sql).setString(0, consId).executeUpdate();
	}
    /**
     * 获取当前用户购物车中的餐品
     * @param consId
     * @return
     */
	@Override
	public List<MealCar> findMealCarListByConsId(String consId,String isEnabled) {
		StringBuilder sql=new StringBuilder("from MealCar where creator='"+consId+"'   ");
		if(StringUtils.isNotEmpty(isEnabled)){
			sql.append(" and isEnabled='"+isEnabled+"' ");
		}
		sql.append(" and foodCount>0 ");
		return getSession().createQuery(sql.toString()).list();
	}

	@Override
	public int removeMealCarById(Long id) {
		String sql="delete from MealCar where id=? ";
		return this.getSession().createQuery(sql).setLong(0, id).executeUpdate();
	}
	 /**
     * 判断该用户订餐时间下是否有加入购物车的订单（个人）
     * 判断该用户订餐时间下操作人是否有加入购物车的订单(管理员)
     * 1购物车中有数据
     * 0购物车中没数据
     * @param userId
     * @param time
     * @param operator
     * @return
     */
	@Override
	public int getMealCarByUserIdAndTime(String userId, String time,
			String operator) {
		StringBuilder sql=new StringBuilder("from MealCar  where consId='"+userId+"' and date_format(dinnerTime,'%Y-%m-%d')='"+time+"' and isMeetFood=0 ");
		if(StringUtils.isNotEmpty(operator)){//管理员代订
			sql.append(" and creator='"+operator+"'  ");
		}
		List<MealCar> list=getSession().createQuery(sql.toString()).list();
		if(list!=null&&list.size()>0){
			return 1;
		}
		return 0;
	}

	/**
	 * 获取指定时间内该用户创建的有效数据
	 */
	@Override
	public List<MealCar> findMealCarListByUserId(String userId, String time) {
		StringBuilder sql=new StringBuilder("from MealCar where creator='"+userId+"'  and  date_format(dinnerTime,'%Y-%m-%d')='"+time+"'  ");
		sql.append(" and foodCount>0 ");
		return getSession().createQuery(sql.toString()).list();
	}
	@Override
		public List<MealCar> findMealCarListByUserId(String userId) {
		StringBuilder sql=new StringBuilder("from MealCar where creator='"+userId+"'   ");
		sql.append(" and foodCount>0 ");
		sql.append(" order by  dinnerTime ");
		return getSession().createQuery(sql.toString()).list();
		}
	@Override
	public int findMealCarListByUserId(String userId, String time,
			String mealId) {
		StringBuilder sql=new StringBuilder("select sum(foodCount) count from tb_mealcar where creator='"+userId+"'  and  date_format(dinnerTime,'%Y-%m-%d')='"+time+"'  ");
		sql.append(" and foodCount>0 ");
		sql.append(" and mealId='"+mealId+"' ");
		List<Map<String, Object>> list=getJdbcTemplate().queryForList(sql.toString());
		int count=0;
		try {
			if(list!=null&&list.size()>0){
				Map<String, Object> map=list.get(0);
				if(map.containsKey("count")&&StringUtils.isNotEmpty(map.get("count")==null?"":map.get("count").toString())){
					count=Integer.parseInt(map.get("count").toString());
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public List<MealCar> getMealCarByParemens(Map<String, String> parements) {
		StringBuilder sql=new StringBuilder("from MealCar where creator='"+parements.get("userId")+"'    ");
		sql.append(" and  date_format(dinnerTime,'%Y-%m-%d')='"+parements.get("time")+"' ");
		sql.append(" and isEnabled='1' ");
//		sql.append(" and mealId='"+parements.get("mealId")+"' ");
		sql.append(" and foodCount>0 ");
		return getSession().createQuery(sql.toString()).list();
	}

	@Override
	public List<Map<String, Object>> getMealCarGroupFood(
			Map<String, String> parements) {
//		StringBuilder sql=new StringBuilder("select mc.mealId,mc.stapleFood,GROUP_CONCAT(mc.consId) users from tb_mealcar mc   ");
//		sql.append(" left join tb_meal m on mc.mealId=m.id ");
//		sql.append(" where mc.creator='"+parements.get("userId")+"'   ");
//	//	sql.append(" and  date_format(mc.dinnerTime,'%Y-%m-%d')='"+parements.get("time")+"' ");
//		sql.append(" and mc.isEnabled='1' ");
//		sql.append(" and (m.supplyTime>='"+parements.get("time")+"' or m.supplyType='1') ");
//		sql.append(" and mc.foodCount>0 ");
//		sql.append(" and mc.isMeetFood=0 ");
//		sql.append(" group by mc.mealId,mc.stapleFood ");
		StringBuilder sql=new StringBuilder("");
		sql.append(" select mc.mealId,mc.stapleFood,GROUP_CONCAT(mc.consId) users  ");
		sql.append(" from tb_mealcar mc  ");
		sql.append(" where mc.isEnabled='1' and mc.isMeetFood=0 and mc.creator='"+parements.get("userId")+"'  ");
		sql.append(" and date_format(mc.dinnerTime,'%Y-%m-%d')='"+parements.get("time")+"'  ");
		sql.append(" and mealId='"+parements.get("mealId")+"'  ");
		if(StringUtils.isNotEmpty(parements.get("stapleFood"))){
			sql.append("  and stapleFood='"+parements.get("stapleFood")+"'   ");
		}
		sql.append(" group by mc.mealId,mc.stapleFood ");
		return getJdbcTemplate().queryForList(sql.toString());
	}

	@Override
	public int removeMealCarList(String userId,int type) {
		StringBuilder sql=new StringBuilder("delete from MealCar where creator=? ");
		if(type==1){//删除小于当前系统时间的数据
			sql.append(" and date_format(dinnerTime,'%Y-%m-%d')<date_format(SYSDATE(),'%Y-%m-%d') ");
		}else if(type==2){//删除等于当前系统时间的数据
			sql.append(" and date_format(dinnerTime,'%Y-%m-%d')<=date_format(SYSDATE(),'%Y-%m-%d') ");
		}
		return this.getSession().createQuery(sql.toString()).setString(0, userId).executeUpdate();
	}

	@Override
	public int findByUserId(String userId, String time) {
		StringBuilder sql=new StringBuilder("select sum(foodCount) count from tb_mealcar where creator='"+userId+"'  and  date_format(dinnerTime,'%Y-%m-%d')='"+time+"'  ");
		sql.append(" and foodCount>0 ");
		List<Map<String, Object>> list=getJdbcTemplate().queryForList(sql.toString());
		int count=0;
		try {
			if(list!=null&&list.size()>0){
				Map<String, Object> map=list.get(0);
				if(map.containsKey("count")&&StringUtils.isNotEmpty(map.get("count")==null?"":map.get("count").toString())){
					count=Integer.parseInt(map.get("count").toString());
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public List<Map<String, Object>> getMealCarByStapleFood(
			Map<String, String> parements) {
//		StringBuilder sql=new StringBuilder("select GROUP_CONCAT(mc.consId) grayUsers from tb_mealcar mc   ");
//		sql.append(" left join tb_meal m   on mc.mealId=m.id  ");
//		sql.append(" where mc.creator='"+parements.get("userId")+"'   ");
//		//sql.append(" and  date_format(mc.dinnerTime,'%Y-%m-%d')='"+parements.get("time")+"' ");
//		sql.append(" and mc.isEnabled='1' ");
//		sql.append(" and (m.supplyTime>='"+parements.get("time")+"' or m.supplyType='1') ");
//		sql.append(" and mc.foodCount>0 ");
//		sql.append(" and mc.isMeetFood=0 ");
//		if(StringUtils.isNotEmpty(parements.get("users"))){
//			sql.append(" and  mc.consId not in ("+parements.get("users")+") ");
//		}
		//sql.append(" group by mc.mealId,mc.stapleFood ");
		
		StringBuilder sql=new StringBuilder("");
		sql.append(" select GROUP_CONCAT(mc.consId) grayUsers  ");
		sql.append(" from tb_mealcar mc  ");
		sql.append(" where mc.isEnabled='1' and mc.isMeetFood=0 and mc.creator='"+parements.get("userId")+"'  ");
		sql.append(" and date_format(mc.dinnerTime,'%Y-%m-%d')='"+parements.get("time")+"'  ");
		if(StringUtils.isNotEmpty(parements.get("users"))){
			sql.append(" and  mc.consId not in ("+parements.get("users")+") ");
		}
		return getJdbcTemplate().queryForList(sql.toString());
	}

	@Override
	public int getMealCarList(String userId, String orgId) {
		StringBuilder sql=new StringBuilder("select sum(foodCount) count from tb_mealcar where creator='"+userId+"' ");
		sql.append(" and foodCount>0 ");
		List<Map<String, Object>> list=getJdbcTemplate().queryForList(sql.toString());
		int count=0;
		try {
			if(list!=null&&list.size()>0){
				Map<String, Object> map=list.get(0);
				if(map.containsKey("count")&&StringUtils.isNotEmpty(map.get("count")==null?"":map.get("count").toString())){
					count=Integer.parseInt(map.get("count").toString());
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public int getMealCarCountByMealId(String userId,
			String time, String mealId) {
		StringBuilder sql=new StringBuilder("select sum(foodCount) count from tb_mealcar where creator='"+userId+"' and mealId='"+mealId+"' ");
		sql.append(" and foodCount>0 ");
		sql.append(" and dinnerTime='"+time+"' ");
		List<Map<String, Object>> list=getJdbcTemplate().queryForList(sql.toString());
		int count=0;
		try {
			if(list!=null&&list.size()>0){
				Map<String, Object> map=list.get(0);
				if(map.containsKey("count")&&StringUtils.isNotEmpty(map.get("count")==null?"":map.get("count").toString())){
					count=Integer.parseInt(map.get("count").toString());
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return count;
	}
}
