package com.izouma.nineth.web;

import com.izouma.nineth.domain.RarityLabel;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.Rarity;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.RarityLabelRepo;
import com.izouma.nineth.service.RarityLabelService;
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("/rarityLabel")
@AllArgsConstructor
public class RarityLabelController extends BaseController {
    private RarityLabelService rarityLabelService;
    private RarityLabelRepo rarityLabelRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public RarityLabel save(@RequestBody RarityLabel record) {
        RarityLabel rarityLabel = rarityLabelRepo.findByNameAndDel(record.getName(), false);
        if (Objects.nonNull(rarityLabel) && !Objects.equals(rarityLabel.getId(), record.getId())) {
            throw new BusinessException("已经存在该name的相关label配置！");
        }
        if (record.getId() != null) {
            RarityLabel orig = rarityLabelRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return rarityLabelRepo.save(orig);
        }
        return rarityLabelRepo.save(record);
    }


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

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

    @GetMapping("/label/{name}")
    public List<Rarity> findByName(@PathVariable String name) {
        RarityLabel rarityLabel = rarityLabelRepo.findByNameAndDel(name, false);
        if (Objects.isNull(rarityLabel)) {
            return null;
        }
        return rarityLabel.getLabel();
    }

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

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

