package com.izouma.nineth.web;

import com.izouma.nineth.domain.RecordRank;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.RecordRankRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.service.RecordRankService;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/recordRank")
@AllArgsConstructor
public class RecordRankController extends BaseController {
    private RecordRankService recordRankService;
    private RecordRankRepo recordRankRepo;

    private UserRepo userRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public RecordRank save(@RequestBody RecordRank record) {
        RecordRank recordRank = recordRankRepo.findByUserIdAndBlindBoxIdAndRareAndDel(record.getUserId(), record.getBlindBoxId(), record.getRare(), false);
        if (Objects.nonNull(recordRank) && !Objects.equals(recordRank.getId(), record.getId())) {
            throw new BusinessException("该用户已经存在该盲盒id和稀有度的信息！");
        }
        User user = userRepo.findById(record.getUserId()).orElseThrow(new BusinessException("用户信息未空"));
        record.setAvatar(user.getAvatar());
        record.setNickname(user.getNickname());
        if (record.getId() != null) {
            RecordRank orig = recordRankRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return recordRankRepo.save(orig);
        }
        return recordRankRepo.save(record);
    }


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

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

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

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

