package com.rf.psychological.miniapp.comment.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.miniapp.collect.model.CollectEntity;
import com.rf.psychological.miniapp.comment.model.CommentEntity;
import com.rf.psychological.miniapp.comment.service.CommentService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.dao.model.UserFileEntity;
import com.rf.psychological.user.service.UserFileService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.JWTUtil;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:用户评论接口
 * @Author: mimang
 * @Date: 2023/5/17
 */
@Slf4j
@RestController
@RequestMapping("/comment")
@Api(tags = "用户评论管理")
public class CommentController extends BaseController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserFileService userFileService;

    @SafetyProcess
    @ApiOperation(value = "评论保存",notes = "json字符串形式传参(加密)，" +
            "data参数中包括(必传)：userId:用户id,flag:量表或者认知任务flag,type:类型0量表1认知任务,commentContent:评论内容")
    @PostMapping("/save")
    public Result save(@RequestBody String paramJson){
        try {
            String paramData = AesEncryptUtils.decrypt(JSONObject.parseObject(paramJson).getString("data"));
            log.info(paramData);
            if (StringUtils.isEmpty(paramData)){
                return fail(null,"参数不能为空");
            }
            CommentEntity entity = JSONObject.parseObject(paramData, CommentEntity.class);
            entity = commentService.save(entity);
            return success(entity);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }

    @SafetyProcess
    @ApiOperation(value = "根据flag查询某量表或认知任务评论记录",notes = " flag:量表或认知任务flag,pageNum:页码,pageSize:数量")
    @GetMapping("/query")
    public Result queryByFlag(@RequestParam String flag,@RequestParam int pageNum,@RequestParam int pageSize){
        try {
            Page<CommentEntity> entities = commentService.queryByFlag(flag, Constant.DEFAULT_VALUE_ONE, pageNum, pageSize);
            List<CommentEntity> commentEntityList = entities.getContent();
            List<CommentEntity> commentEntities = new ArrayList<>();
            for (CommentEntity commentEntity : commentEntityList){
                UserEntity userInfo = userService.findUserById(commentEntity.getUserId());
                commentEntity.setUserName(userInfo.getPetName());
                UserFileEntity userFileEntity = this.userFileService.findByUserId(commentEntity.getUserId());
                if (userFileEntity != null){
                    commentEntity.setAvatarUrl(userFileEntity.getPath());
                }
                commentEntities.add(commentEntity);
            }
            JSONObject result = new JSONObject();
            result.put("userEntities", commentEntities);
            result.put("num", entities.getTotalElements());
            return success(result, "查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }

    @SafetyProcess
    @ApiOperation(value = "根据flag查询某量表或认知任务评论记录数量",notes = " flag:量表或认知任务flag")
    @GetMapping("/queryNum")
    public Result queryNumByFlag(@RequestParam String flag){
        try {
            List<CommentEntity> commentEntityList = this.commentService.findAllByFlagAndStatus(flag, Constant.DEFAULT_VALUE_ONE);
            return success(commentEntityList.size(), "查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }

    @SafetyProcess
    @ApiOperation(value = "删除评论",notes = "id评论id")
    @GetMapping("/delete")
    public Result deleteById(@RequestParam String id, HttpServletRequest request){
        try {
            if (StringUtils.isEmpty(id)){
                return fail(null,"参数不能为空");
            }
            CommentEntity commentEntity = commentService.findById(id);
            if (commentEntity == null){
                return fail(null,"ID有误");
            }
            String token = request.getHeader("Authorization");
            token = token.split(" ")[1];//以空格划分Bearer token，获取token
            //从请求头中获取token
            DecodedJWT verify = JWTUtil.verify(token);
            String userId = verify.getClaim("userId").asString();
            if (!userId.equals(commentEntity.getUserId())){
                return fail(null,"不能删除他人评论");
            }
            commentEntity = commentService.deleteById(commentEntity);
            return success(commentEntity);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }
}
