package com.izouma.nineth.web;

import com.izouma.nineth.domain.TradingAccount;
import com.izouma.nineth.service.TradingAccountService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.TradingAccountRepo;
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("/tradingAccount")
@AllArgsConstructor
public class TradingAccountController extends BaseController {
    private TradingAccountService tradingAccountService;
    private TradingAccountRepo    tradingAccountRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public TradingAccount save(@RequestBody TradingAccount record) {
        return tradingAccountRepo.save(record);
    }


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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public TradingAccount get(@PathVariable Long id) {
        return tradingAccountRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        tradingAccountRepo.deleteById(id);
    }

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

