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

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.OutAddressDao;
import com.uas.platform.b2b.mobile.model.OutAddress;
import com.uas.platform.b2b.mobile.service.OutAddressService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;

@Service
public class OutAddressServiceImpl implements OutAddressService {

	@Autowired
	private OutAddressDao outAddressDao;

	@Override
	public ModelMap saveOutAddress(OutAddress outAddress) {
		ModelMap map = new ModelMap();
		OutAddress old = outAddressDao.findByCompany(outAddress.getCompany());
		if (old != null) {
			old.setMd_visitcount(old.getMd_visitcount() + 1);
			outAddress = outAddressDao.save(old);
		} else {
			outAddress = outAddressDao.save(outAddress);
		}
		if (outAddress.getMd_id() != null) {
			map.put("success", true);
			map.put("md_id", outAddress.getMd_id());
		} else {
			map.put("success", false);
		}
		return map;
	}

	@Override
	public ModelMap getOutAddress(Long enuu, Integer pageNumber, Integer pageSize) {
		ModelMap map = new ModelMap();
		PageParams params = new PageParams();
		params.setCount(pageSize);
		if (pageNumber != null) {
			params.setPage(pageNumber);
		} else {
			params.setPage(Integer.valueOf(1));
		}
		final PageInfo pageInfo = new PageInfo(params);
		pageInfo.filter("enuu", enuu);
		Page<OutAddress> news = outAddressDao.findAll(new Specification<OutAddress>() {
			@Override
            public Predicate toPredicate(Root<OutAddress> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		map.put("data", news.getContent());
		return map;
	}

}
