package com.goafanti.demand.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.common.dao.DemandInterestMapper;
import com.goafanti.common.model.DemandInterest;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.service.DemandInterestService;
import com.goafanti.portal.bo.DemandInterestListBo;

@Service
public class DemandInterestServiceImpl extends BaseMybatisDao<DemandInterestMapper> implements DemandInterestService {
	@Autowired
	private DemandInterestMapper demandInterestMapper;

	@Override
	public int saveCancelDemandInterest(String id) {
		return demandInterestMapper.deleteByPrimaryKey(id,TokenManager.getUserId());
	}

	@Override
	public String saveAchievementInterest(String id) {
		DemandInterest di = new DemandInterest();
		di.setId(UUID.randomUUID().toString());
		di.setDemandId(id);
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		di.setCreateTime(now.getTime());
		di.setUid(TokenManager.getUserId());
		if (StringUtils.isBlank(di.getUid())){
			return null;
		}
		demandInterestMapper.insert(di);
		return di.getId();
	}

	@Override
	public DemandInterest selectDemandInterestByUidAndDemandId(String uid, String id) {
		return demandInterestMapper.selectDemandInterestByUidAndDemandId(uid, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandInterestListBo> listDemandInterest(Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		if (TokenManager.getToken() instanceof User) {
			params.put("uid", TokenManager.getUserId());
		}
		return (Pagination<DemandInterestListBo>) findPage("findDemandInterestListByPage",
				"findDemandInterestCount", params, pNo, pSize);
	}

	@Override
	public int countDemandInterest(String id) {
		return demandInterestMapper.countInterestById(id);
	}
}
