package com.izouma.dingdong.web.backstage;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.BlackList;
import com.izouma.dingdong.service.backstage.BlackListService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.BlackListRepo;
import com.izouma.dingdong.utils.ObjUtils;
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.util.List;

@RestController
@RequestMapping("/blackList")
@AllArgsConstructor
public class BlackListController extends BaseController {
    private BlackListService blackListService;
    private BlackListRepo blackListRepo;

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


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

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

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

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

    @PostMapping("/move")
    @ApiOperation("移入黑名单")
    public BlackList move(@RequestParam Long userId, @RequestParam String reason) {
        return blackListService.move(userId, reason);
    }

    @GetMapping("/remove")
    @ApiOperation("移出黑名单")
    public void remove(Long id) {
        blackListService.remove(id);
    }
}

