package com.izouma.dingdong.web.backstage;

import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.Email;
import com.izouma.dingdong.service.backstage.EmailService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.EmailRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;

import lombok.AllArgsConstructor;
import org.apache.catalina.security.SecurityUtil;
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("/email")
@AllArgsConstructor
public class EmailController extends BaseController {
    private EmailService emailService;
    private EmailRepo emailRepo;

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


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

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

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

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

    @GetMapping("/my")
    public List<Email> my(){
        return emailRepo.findAllByReceiveUserId(SecurityUtils.getAuthenticatedUser().getId());
    }
}

