package com.palmnest.dao.dinner.impl;

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

import com.palmnest.application.core.util.DateHelper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import cn.jiguang.common.utils.StringUtils;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.input.MealSearchDto;
import com.palmnest.dao.dinner.MealDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.dinner.Meal;
import org.springframework.util.CollectionUtils;

/**
 * 餐品DAO实现类
 *
 * @author longmeizhen
 */
@Slf4j
@Repository("mealDao")
public class MealDaoImpl extends GenericDaoHibernate<Meal, Long> implements MealDao {
	private static Logger LOG = LoggerFactory.getLogger(MealDaoImpl.class);

	public MealDaoImpl() {
		super(Meal.class);
	}

	/**
	 * 获取餐品列表
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Page findList(MealSearchDto dto) {
		StringBuilder sql = new StringBuilder("");
		sql.append("select m.id,ifnull(doi.itemname,di.itemname)  mealName,m.spec,ifnull(dol.itemname,ifnull(dl.itemname,'单品')) specStr,m.isMeetingFood isMeetFood,m.isModel,m.stapleFood,m.mealDescribe,m.deliveryTimeStr,m.supplyType,m.supplyTime,m.status ");
		sql.append(" from tb_meal m   ");
		sql.append(" left join tb_dictionary_item di on di.id=m.mealCodeId  ");
		sql.append(" left join tb_dictionary_item dl on dl.id=m.spec  ");
		sql.append(" left join tb_dictionary_org_item doi on doi.id=m.mealCodeId  ");
		sql.append(" left join tb_dictionary_org_item dol on dol.id=m.spec  ");
		sql.append(" where m.isEnabled='1'  ");
		if (StringUtils.isNotEmpty(dto.getOrgId())) {
			sql.append(" and m.orgId in (" + dto.getOrgId() + ") ");
		}
		if (StringUtils.isNotEmpty(dto.getStatus())) {
			sql.append("  and  m.status='" + dto.getStatus() + "' ");
		}
		if (StringUtils.isNotEmpty(dto.getMealName()) || StringUtils.isNotEmpty(dto.getMealNameOrg())) {
			sql.append("  and  (di.id='" + dto.getMealName() + "' or doi.id='" + dto.getMealNameOrg() + "') ");
		}
		if (StringUtils.isNotEmpty(dto.getBeginTime())) {
			if (StringUtils.isNotEmpty(dto.getEndTime())) {
				sql.append(" and (m.supplyTime>='" + dto.getBeginTime() + "' and m.supplyTime<='" + dto.getEndTime() + "' or m.supplyType='1') ");
			} else {
				sql.append(" and (m.supplyTime>='" + dto.getBeginTime() + "' or m.supplyType='1') ");
			}
		} else if (StringUtils.isNotEmpty(dto.getEndTime())) {
			sql.append(" and (m.supplyTime<='" + dto.getEndTime() + "' or m.supplyType='1') ");
		}
		sql.append(" order by m.isModel desc,m.createTime desc ");

		return pagedQueryByJdbcTemplate(sql.toString(), dto.getPageNo(), dto.getPageSize());
	}

	/**
	 * 获取餐品列表
	 * （获取当天且是上架的餐品）
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Meal> findMealList(String orgId) {
		StringBuilder sql = new StringBuilder("from Meal ");
		sql.append(" where isEnabled='1' ");
		sql.append(" and status='1' ");
		sql.append(" and (supplyTime=date_format(NOW(),'%Y-%m-%d') or supplyType=1) ");

		if (StringUtil.isNotEmpty(orgId)) {
			sql.append(" and orgId in (" + orgId + ")");
		}
		return getSession().createQuery(sql.toString()).list();
	}

	@Override
	public List<Meal> findMealList(String orgId, String time) {
		StringBuilder sql = new StringBuilder("from Meal ");
		sql.append(" where isEnabled='1' ");
		sql.append(" and status='1' ");
		sql.append(" and (supplyTime=? or supplyType=1) ");
		sql.append(" and orgId=? ");
		sql.append(" order by  (case when spec>1 then 2 else 1 end) desc ");
		return getSession().createQuery(sql.toString()).setString(0, time).setString(1, orgId).list();
	}

	@Override
	public List<Meal> getMealList(String orgId, String time) {
		StringBuilder sql = new StringBuilder("from Meal ");
		sql.append(" where isEnabled='1' ");
		sql.append(" and status='1' ");
		sql.append(" and supplyTime=? ");
		sql.append(" and orgId=? ");
		return getSession().createQuery(sql.toString()).setString(0, time).setString(1, orgId).list();
	}

	@Override
	public List<Meal> findMealByMealCodeId(String orgId, String mealCodeId, String mealCodeOrgId) {
		StringBuilder sql = new StringBuilder("from Meal ");
		sql.append(" where isEnabled='1' ");
		sql.append(" and status='1' ");
		sql.append(" and orgId=? ");
		sql.append(" and isModel=1 ");
		sql.append(" and (mealCodeId=?  or mealCodeId=? )");
		return getSession().createQuery(sql.toString()).setString(0, orgId).setString(1, mealCodeId).setString(2, mealCodeOrgId).list();
	}


	@Override
	public List<Map<String,Object>> getMealDate(Integer orgId) {
		StringBuilder sql = new StringBuilder(" SELECT DISTINCT supplyTime ");
		sql.append(" ,( CASE WHEN DAYOFWEEK( supplyTime) = 1 THEN 7 WHEN DAYOFWEEK( supplyTime ) > 1 THEN DAYOFWEEK( supplyTime )- 1 END ) weekNo ");
		sql.append(" , ( CASE WHEN DAYOFWEEK( supplyTime ) = 1 THEN '星期日' WHEN DAYOFWEEK( supplyTime ) = 2 THEN '星期一' WHEN DAYOFWEEK( supplyTime ) = 3 THEN '星期二' WHEN DAYOFWEEK( supplyTime ) = 4 THEN '星期三' WHEN DAYOFWEEK( supplyTime ) = 5 THEN '星期四' WHEN DAYOFWEEK( supplyTime ) = 6 THEN '星期五' WHEN DAYOFWEEK( supplyTime ) = 7 THEN '星期六' END ) weekName ");
		sql.append(" , ( CASE WHEN supplyTime = DATE_FORMAT( SYSDATE(), '%Y-%m-%d' ) THEN 1 ELSE 0 END ) isToday ");
		sql.append(" FROM tb_meal  ");
		sql.append(" WHERE supplyTime >= DATE_FORMAT( SYSDATE(), '%Y-%m-%d' ) AND orgId = "+orgId+" AND isEnabled = 1 AND `status` = 1 ORDER BY supplyTime ");
		return getJdbcTemplate().queryForList(sql.toString());
	}

	@Override
	public String getNextMealDate(Integer orgId, String date, int type) {
		StringBuilder sql = new StringBuilder(" SELECT DISTINCT supplyTime ");
		sql.append(" FROM tb_meal  ");
		if(1 == type){
			sql.append(" WHERE supplyTime > DATE_FORMAT( '"+date+"', '%Y-%m-%d' ) AND orgId = "+orgId+" AND isEnabled = 1 AND `status` = 1 ORDER BY supplyTime LIMIT 1");
		}else if(2 == type){
			sql.append(" WHERE supplyTime >= DATE_FORMAT( '"+date+"', '%Y-%m-%d' ) AND orgId = "+orgId+" AND isEnabled = 1 AND `status` = 1 ORDER BY supplyTime LIMIT 1");
		}
		log.info("getNextMealDate-sql:{}",sql);
		List<Map<String,Object>> list = getJdbcTemplate().queryForList(sql.toString());
		if(CollectionUtils.isEmpty(list)){
			return "";
		}
		Map<String, Object> map = list.get(0);
		if (map == null || !map.containsKey("supplyTime") || null == map.get("supplyTime") || StringUtils.isEmpty(map.get("supplyTime").toString())) {
			return "";
		}
		return map.get("supplyTime").toString();
	}
}
