package com.izouma.nineth.web;

import com.izouma.nineth.domain.Tag;
import com.izouma.nineth.service.TagService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.TagRepo;
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.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("/tag")
@AllArgsConstructor
public class TagController extends BaseController {
    private TagService tagService;
    private TagRepo    tagRepo;

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

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public Tag create(@RequestParam String name, String remark, boolean addForExist, String addMode, String pattern) {
        return tagService.create(name, remark, addForExist, addMode, pattern);
    }


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

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

    @PostMapping("/del/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public void del(@PathVariable Long id) {
        tagRepo.deleteById(id);
    }

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

    @GetMapping("/checkAdd")
    @PreAuthorize("hasRole('ADMIN')")
    public Object checkAdd(String addMode, String pattern) {
        return tagService.checkAdd(addMode, pattern);
    }
}

