package com.izouma.zhirongip.web.supply;

import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.utils.SecurityUtils;
import com.izouma.zhirongip.web.BaseController;
import com.izouma.zhirongip.domain.supply.Copyright;
import com.izouma.zhirongip.service.supply.CopyrightService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.supply.CopyrightRepo;
import com.izouma.zhirongip.utils.ObjUtils;
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("/copyright")
@AllArgsConstructor
public class CopyrightController extends BaseController {
    private final CopyrightService copyrightService;
    private final CopyrightRepo    copyrightRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Copyright save(@RequestBody Copyright record) {
        if (record.getId() != null) {
            Copyright orig = copyrightRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return copyrightRepo.save(orig);
        }
        record.setStatus(ApplyStatus.PENDING);
        record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        return copyrightRepo.save(record);
    }


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

    @GetMapping("/get/{id}")
    public Copyright get(@PathVariable Long id) {
        return copyrightService.get(id);
    }

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

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

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("审核")
    @PostMapping("/audit")
    public void audit(@RequestParam Long id, @RequestParam boolean pass, String remark) {
        copyrightService.audit(id, pass, remark);
    }
}

