package com.remy.order.controller;

import com.remy.common.helper.BeanHelper;
import com.remy.order.entity.Comment;
import com.remy.order.entity.Order;
import com.remy.order.service.CommentService;
import com.remy.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("comments")
public class CommentsController {

    @Autowired
    CommentService commentService;

    @Autowired
    OrderService orderService;

    @RequestMapping()
    public List<Comment> findAll() {
        return commentService.findAll();
    }

    @RequestMapping("{orderNo}")
    public Comment findByOrderNo(@PathVariable("orderNo") String orderNo) {
        return commentService.findCommentByOrderNo(orderNo);
    }

    @RequestMapping("query")
    public List<Comment> findAllByCondition(@RequestParam Map<String, String> params) {
        log.info("query comments by condition: {}", BeanHelper.toJSON(params));
        Comment comment = BeanHelper.fromJSON(BeanHelper.toJSON(params), Comment.class);
        return commentService.findByCondition(comment);
    }

    @PostMapping()
    public Comment save(@RequestBody Comment comment) throws Exception {
        Comment existComment = commentService.findCommentByOrderNo(comment.getOrderNo());
        if (null != existComment) {
            throw new Exception("已经评论过了");
        }
        Order order = orderService.findByOrderNo(comment.getOrderNo());
        comment.setGoodsSerialNo(order.getGoodsSerialNo());
        comment.setUserID(order.getUserID());
        return commentService.save(comment);
    }
}
