package com.webchat.controller.client;

import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.helper.SessionHelper;
import com.webchat.config.annotation.ValidateLogin;
import com.webchat.domain.vo.request.ResourceBehaviorRequestVO;
import com.webchat.service.UserService;
import com.webchat.service.behavior.AbstractResourceBehaviorService;
import com.webchat.service.behavior.ResourceBehaviorFactory;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "【客户端】基础通用互动服务接口")
@RestController
@RequestMapping("/api/resource")
public class ResourceBehaviorController {

    @Autowired
    private UserService userService;

    /**
     * coderutil.com 资源互动接口
     * 同时支持：点赞、收藏、关注、取关、订阅、取消订阅、浏览……
     *
     * @param request 互动请求参数
     * @return 返回互动结束后的最新互动数据
     */
    // 校验来自web请求
    // 校验是否登录
    @ValidateLogin
    @PostMapping("/behavior")
    public APIResponseBean<Long> behavior(@RequestBody ResourceBehaviorRequestVO request) {
        // 参数校验
        request.validRequestParam();
        // 获取当前登录人userid（ThreadLocal中获取当前登录用户id）
        String userId = SessionHelper.getCurrentUserId();
        Long resourceId = request.getResourceId();
        String behaviorType = request.getBehaviorType();
        String resourceType = request.getResourceType();
        // 互动行为，工厂模式，获取当前互动服务具体实现
        AbstractResourceBehaviorService behaviorService =
                ResourceBehaviorFactory.getBehaviorService(behaviorType);
        // 触发互动
        Long count = behaviorService.behavior(userId, resourceId, resourceType);
        // 返回互动完成后的最新互动数据
        return APIResponseBeanUtil.success(count);
    }

    /***
     * 取消行为
     * @param request
     * @return
     */
    @ValidateLogin
    @PostMapping("/cancelBehavior")
    public APIResponseBean cancelBehavior(@RequestBody ResourceBehaviorRequestVO request) {
        request.validRequestParam();
        String behaviorType = request.getBehaviorType();
        AbstractResourceBehaviorService behaviorService = ResourceBehaviorFactory.getBehaviorService(behaviorType);
        String userId = userService.getLoginCurrentUserIdOrElseThrowUnLoginExp();
        Long ctn = behaviorService.cancelBehavior(userId, request.getResourceId(), request.getResourceType());
        return APIResponseBeanUtil.success(ctn);
    }
}
