package com.izouma.dingdong.web;

import com.izouma.dingdong.domain.BankCard;
import com.izouma.dingdong.service.BankCardService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.BankCardRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
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("/bankCard")
@AllArgsConstructor
public class BankCardController extends BaseController {
    private BankCardService bankCardService;
    private BankCardRepo bankCardRepo;

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


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

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

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

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

    @GetMapping("/my")
    @ApiOperation("我的银行卡信息(包括商家和骑手)")
    public Page<BankCard> my(PageQuery pageQuery) {
        return new PageImpl<>(bankCardRepo.findAllByUserIdAndEnabledTrue(SecurityUtils.getAuthenticatedUser().getId()), toPageRequest(pageQuery), pageQuery.getSize());
    }

}

