package com.izouma.nineth.web;

import com.izouma.nineth.converter.LongArrayConverter;
import com.izouma.nineth.domain.MintOrder;
import com.izouma.nineth.dto.MintOrderDTO;
import com.izouma.nineth.service.MintOrderService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.MintOrderRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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("/mintOrder")
@AllArgsConstructor
public class MintOrderController extends BaseController {
    private MintOrderService mintOrderService;
    private MintOrderRepo    mintOrderRepo;

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


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

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

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

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

    @PostMapping("/create")
    public void create(@RequestParam String assets) {
        LongArrayConverter lc = new LongArrayConverter();
        List<Long> assetIds = lc.convertToEntityAttribute(assets);
        mintOrderService.create(SecurityUtils.getAuthenticatedUser().getId(), assetIds);
    }

    @ApiOperation("导出尼尔斯")
    @PostMapping("/excelPhone")
    public void excelPhone(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<MintOrderDTO> data = all(pageQuery).map(MintOrderDTO::new).getContent();
        ExcelUtils.export(response, data);
    }

    @GetMapping("/finish/{id}")
    public void finish(@PathVariable Long id) {
        mintOrderService.finish(id);
    }
}

