package com.izouma.nineth.web;

import com.izouma.nineth.domain.DestroyRecord;
import com.izouma.nineth.domain.RecordRank;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.DestroyRecordRepo;
import com.izouma.nineth.service.DestroyRecordService;
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.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("/destroyRecord")
@AllArgsConstructor
public class DestroyRecordController extends BaseController {
    private DestroyRecordService destroyRecordService;
    private DestroyRecordRepo    destroyRecordRepo;

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


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

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

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

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

    @PostMapping("/my")
    public Page<DestroyRecord> my(@RequestBody PageQuery pageQuery) {
        pageQuery.getQuery().put("userId", SecurityUtils.getAuthenticatedUser().getId());
        return destroyRecordService.all(pageQuery);
    }

    @GetMapping("/rank/{rare}")
    public List<RecordRank> destroyRecordRank(@PathVariable String rare) {
        return destroyRecordService.destroyRecordRank(rare);
    }
}

