package com.izouma.nineth.web;

import com.izouma.nineth.domain.MintActivity;
import com.izouma.nineth.service.MintActivityService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.MintActivityRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
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("/mintActivity")
@AllArgsConstructor
public class MintActivityController extends BaseController {
    private MintActivityService mintActivityService;
    private MintActivityRepo    mintActivityRepo;

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


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

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

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

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

