package com.izouma.dingdong.web;

import com.izouma.dingdong.domain.Chat;
import com.izouma.dingdong.service.ChatService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.ChatRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/chat")
@AllArgsConstructor
public class ChatController extends BaseController {
    private ChatService chatService;
    private ChatRepo chatRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Chat save(@RequestBody Chat record) {
        record.setSendTime(LocalDateTime.now());

        if (record.getId() != null) {
            Chat orig = chatRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return chatRepo.save(orig);
        }
        return chatRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Chat> all(PageQuery pageQuery) {
        return chatRepo.findAll(toSpecification(pageQuery, Chat.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public Chat get(@PathVariable Long id) {
        return chatRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        chatRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Chat> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @ApiOperation("显示个人聊天列表")
    @GetMapping("/my")
    public List<Chat> my(){
        return chatService.my(SecurityUtils.getAuthenticatedUser().getId());
    }

    @ApiOperation("显示两个人的所有聊天内容")
    @GetMapping("/showChat")
    public List<Chat> showChat(Long userOne, Long userTwo) {
        return chatService.showChat(userOne,userTwo);
    }
}

