package com.nbclass.activity.controller.frontapi;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

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

import com.nbclass.activity.service.ContentService;
import com.nbclass.exception.LogicalException;
import com.nbclass.exception.ParameterException;
import com.nbclass.exception.ServiceException;
import com.nbclass.system.controller.BaseController;
import com.nbclass.util.WebUtils;
import com.nbclass.vo.base.Result;

/**
 * i案例库阅读数点赞数功能
 * @author Leon
 * @datetime 2020年5月22日 下午2:02:13
 */
@RestController
public class FrontContentLikeNumController extends BaseController {
	
	@Resource
	private ContentService service;

	/**
	 * 提交阅读数点赞数
	 * @param type 提交类型[view:阅读数, like:点赞数]
	 * @param id 点赞记录id
	 * @param response
	 * @return
	 */
	@PostMapping("/front/api/content/addNum")
	public Result updateContentNum(String type, Long id, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			if(StringUtils.isBlank(type))throw new ParameterException("参数type不能为空");
			if(id == null || id < 1)throw new ParameterException("案例id不能为空");
			
			String cookieNum = WebUtils.getValueFromCookie(getRequest(), "case_content_num_"+type+"_"+id);
			if(StringUtils.isNotBlank(cookieNum)){
				if("view".equals(type)){
					return Result.success();
				}else{
					throw new ParameterException("你已经点过赞了");
				}
			}
			int num = service.updateContentNum(type, id);;
	
			WebUtils.addCookie(response, "case_content_num_"+type+"_"+id, String.valueOf(type+id), 3600 * 24 * 1);
			return Result.success(num);
		} catch (Exception e) {
			String errmsg = "保存失败";
			if(e instanceof ParameterException || e instanceof ServiceException || e instanceof LogicalException){
				errmsg = e.getMessage();
			}else{
				logger.error("提交阅读数点赞数失败", e);
			}
			return Result.error(errmsg);
		}
	}
	
}
