package com.fs.app.controller;


import com.fs.app.annotation.Login;
import com.fs.common.core.domain.R;
import com.fs.common.utils.ServletUtils;
import com.fs.course.domain.FsUserTalentFollow;
import com.fs.course.param.FsUserTalentFollowParam;
import com.fs.course.service.IFsUserTalentFollowService;
import com.fs.course.service.IFsUserTalentService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api("达人接口")
@RestController
@RequestMapping(value="/app/talent")
public class TalentController extends  AppBaseController{
    @Autowired
    private IFsUserTalentFollowService userTalentFollowService;
    @Autowired
    private IFsUserTalentService userTalentService;


    @ApiOperation("获取达人详情")
    @GetMapping("/getTalentById")
    private R getTalentById(@RequestParam("talentId")Long talentId){

        return R.ok();
    }

    @Login
    @ApiOperation("获取是否关注")
    @GetMapping("/checkFollow")
    public R checkFollow(@RequestParam("talentId")Long talentId, HttpServletRequest request){
        String headValue =  ServletUtils.getRequest().getHeader("APPToken");
        Claims claims=jwtUtils.getClaimByToken(headValue);
        if(claims!=null){
            String userId = claims.getSubject().toString();
            R r=userTalentFollowService.checkFollow(talentId,Long.parseLong(userId));
            if (r.get("code").equals(200)){
                return R.ok().put("isFollow",1);
            }else {
                return R.ok().put("isFollow",0);
            }
//            return courseFollowService.checkFollow(courseId,Long.parseLong(userId));
        }
        else{
            return R.error("未登录");
        }

    }
    @Login
    @ApiOperation("关注")
    @PostMapping("/doFollow")
    @Transactional
    @Synchronized
    public R doFollow(@RequestBody FsUserTalentFollowParam param, HttpServletRequest request){
        R r=userTalentFollowService.checkFollow(param.getTalentId(),Long.parseLong(getUserId()));
        if(r.get("code").equals(200)){
            //取消关注
            userTalentFollowService.deleteFollow(param.getTalentId(),Long.parseLong(getUserId()));
            userTalentService.updateFans(param.getTalentId(),1);
            return R.ok("已取消关注");
        }
        else{
            //关注
            FsUserTalentFollow map=new FsUserTalentFollow();
            map.setTalentId(param.getTalentId());
            map.setUserId(Long.parseLong(getUserId()));
            map.setCreateTime(new Date());
            userTalentFollowService.insertFsUserTalentFollow(map);
            userTalentService.updateFans(param.getTalentId(),-1);
            return R.ok("已关注");
        }
    }
}
