package com.izouma.nineth.web;

import com.izouma.nineth.domain.AuctionActivity;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.auction.AuctionInputDTO;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AuctionActivityRepo;
import com.izouma.nineth.repo.NewsLikeRepo;
import com.izouma.nineth.service.AuctionActivityService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
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("/auctionActivity")
@AllArgsConstructor
public class AuctionActivityController extends BaseController {
    private AuctionActivityService auctionActivityService;
    private AuctionActivityRepo    auctionActivityRepo;
    private NewsLikeRepo           newsLikeRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public AuctionActivity save(@RequestBody AuctionActivity record, @RequestParam(required = false) String code) {
        if (record.getId() != null) {
            AuctionActivity orig = auctionActivityRepo.findById(record.getId())
                    .orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return auctionActivityService.save(orig, code);
        }
        return auctionActivityService.save(record, code);
    }

    @PostMapping("/create")
    public AuctionActivity createFromAsset(@RequestBody AuctionInputDTO dto) {
        return auctionActivityService.createFromAsset(dto);
    }

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

    @GetMapping("/get/{id}")
    public AuctionActivity get(@PathVariable Long id) {
        AuctionActivity auctionActivity = auctionActivityRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        if (SecurityUtils.getAuthenticatedUser() != null) {
            if (newsLikeRepo.findByUserIdAndAuctionId(SecurityUtils.getAuthenticatedUser().getId(), id).size() > 0) {
                auctionActivity.setLiked(true);
                return auctionActivity;
            }
        }
        auctionActivity.setLiked(false);
        return auctionActivity;
    }

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

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

