package com.goafanti.user.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.UserType;
import com.goafanti.common.model.UserInterest;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.user.service.UserInterestService;

@RestController
@RequestMapping(value = "/api/user/interest")
public class UserInterestApiController extends CertifyApiController {
	@Resource
	private UserInterestService userInterestService;

	/**
	 * 关注用户列表
	 */
	@RequestMapping(value = "/interestUserList", method = RequestMethod.GET)
	public Result interestUserList(String pageNo, String pageSize, String type) {
		Result res = new Result();
		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		Integer userType = StringUtils.isBlank(type) ? null : UserType.getStatus(type).getCode();
		res.setData(userInterestService.listInterestUser(pNo, pSize, userType));
		return res;
	}

	/**
	 * 关注用户
	 */
	@RequestMapping(value = "/interestUser", method = RequestMethod.POST)
	public Result interestUser(String toUid) {
		Result res = new Result();
		if (StringUtils.isBlank(toUid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "被关注用户ID"));
			return res;
		}
		UserInterest ui = userInterestService.findByFromUidAndToUid(TokenManager.getUserId(), toUid);
		if (null != ui) {
			res.getError().add(buildError("", "当前用户已关注！"));
			return res;
		}

		res.setData(userInterestService.insert(toUid));
		return res;
	}

	/**
	 * 取消关注
	 */
	@RequestMapping(value = "/cancelInterest", method = RequestMethod.POST)
	public Result cancelInterest(String interestId) {
		Result res = new Result();
		if (StringUtils.isBlank(interestId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "关注ID"));
			return res;
		}
		UserInterest ui = userInterestService.findByPrimaryKey(interestId);
		if (null == ui || !TokenManager.getUserId().equals(ui.getFromUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关注ID"));
			return res;
		}
		res.setData(userInterestService.deleteByPrimaryKey(interestId));
		return res;
	}
}
