package com.izouma.zhirongip.web;

import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.service.InformationService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
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("/information")
@AllArgsConstructor
public class InformationController extends BaseController {
    private final InformationService informationService;
    private final InformationRepo    informationRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Information save(@RequestBody Information record) {
        if (record.getId() != null) {
            Information orig = informationRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return informationRepo.save(orig);
        }
        return informationRepo.save(record);
    }


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

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

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

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

    @PostMapping("/batchRead")
    @ApiOperation("批量已读")
    public void batchRead() {
        informationRepo.batchRead(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PostMapping("/batchDel")
    @ApiOperation("批量所有")
    public void batchDel() {
        informationRepo.batchSoftDelete(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PostMapping("/numOfUnread")
    @ApiOperation("未读数量")
    public int numOfUnread() {
        return informationRepo.countByReceiveUserIdAndIsReadFalse(SecurityUtils.getAuthenticatedUser().getId());
    }
}

