package com.izouma.nineth.web;

import com.izouma.nineth.domain.Invite;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.InviteRepo;
import com.izouma.nineth.service.InviteService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/invite")
@AllArgsConstructor
public class InviteController extends BaseController {
    private InviteService inviteService;
    private InviteRepo    inviteRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Invite save(@RequestBody Invite record) {
        if (record.getId() != null) {
            Invite orig = inviteRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            inviteRepo.findFirstByCode(record.getCode()).ifPresent((i) -> {
                if (!i.getId().equals(record.getId())) {
                    throw new BusinessException("此邀请码已存在");
                }
            });
            ObjUtils.merge(orig, record);
            return inviteRepo.save(orig);
        }
        inviteRepo.findFirstByCode(record.getCode()).ifPresent((i) -> {
            throw new BusinessException("此邀请码已存在");
        });
        return inviteRepo.save(record);
    }


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

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

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

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

    @GetMapping("/clean")
    public void clean() {
        if ("xingadmin".equals(SecurityUtils.getAuthenticatedUser().getUsername())) {
            inviteService.cleanInvite();
        }
    }
}

