package com.izouma.zhirongip.web;

import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Message;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.service.MessageService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.MessageRepo;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.SecurityUtils;
import com.izouma.zhirongip.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.util.List;

@RestController
@RequestMapping("/message")
@AllArgsConstructor
public class MessageController extends BaseController {
    private final MessageService  messageService;
    private final MessageRepo     messageRepo;
    private final InformationRepo informationRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Message save(@RequestBody Message record) {
        Long userId = SecurityUtils.getAuthenticatedUser().getId();
        if (record.getId() != null) {
            Message orig = messageRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return messageRepo.save(orig);
        }
        record.setUserId(userId);
        record = messageRepo.save(record);
        informationRepo.save(Information.builder()
                .messageId(record.getId())
                .receiveUserId(userId)
                .content("已收到您的留言：" + record.getTitle() + "，请耐心等待回复！")
                .build());
        return record;
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Message> all(@RequestBody PageQuery pageQuery) {
        return messageService.all(pageQuery);
    }

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

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        messageRepo.softDelete(id);
        //删除相关留言消息
        informationRepo.batchSoftDeleteByMessageId(id);
    }

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

    @ApiOperation("回复")
    @PostMapping("/reply")
    public Message reply(Long id, String content) {
        return messageService.reply(id, content);
    }
}

