package com.uas.platform.b2b.mobile.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.uas.platform.b2b.mobile.dao.SignCardDao;
import com.uas.platform.b2b.mobile.model.SignCard;
import com.uas.platform.b2b.mobile.service.SignCardLogService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;
import com.uas.platform.core.persistence.criteria.PredicateUtils;

@Service
public class SignCardLogServiceImpl implements SignCardLogService {

	@Autowired
	private SignCardDao signCardDao;

	@Override
	public ModelMap getListData(Long emcode, Long enuu, Integer pageNumber, Integer pageSize, String date)
			throws ParseException {
		ModelMap map = new ModelMap();
		PageParams params = new PageParams();
		params.setCount(pageSize);
		params.setPage(pageNumber);
		final PageInfo pageInfo = new PageInfo(params);
		pageInfo.filter("emcode", emcode);
		pageInfo.filter("enuu", enuu);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		if (date != null) {
            pageInfo.expression(PredicateUtils.gte("cl_date", sdf.parse(date), false));
        }
			pageInfo.expression(PredicateUtils.lt("cl_date", sdf.parse(String.valueOf(Long.valueOf(date) + 1)), false));

		Page<SignCard> sigLogs = signCardDao.findAll(new Specification<SignCard>() {
			@Override
            public Predicate toPredicate(Root<SignCard> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		map.put("listdata", sigLogs.getContent());
		map.put("success", true);
		return map;
	}

	@Override
	public ModelMap saveSignCard(SignCard signCard) {
		ModelMap map = new ModelMap();
		if (signCard.getCl_date() == null) {
			signCard.setCl_date(new Date());
		}
		signCard = signCardDao.save(signCard);
		if (signCard.getId() != null) {
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		return map;
	}
}
