package com.izouma.dingdong.web.backstage;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.TimeTag;
import com.izouma.dingdong.service.backstage.TimeTagService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.TimeTagRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/timeTag")
@AllArgsConstructor
public class TimeTagController extends BaseController {
    private TimeTagService timeTagService;
    private TimeTagRepo timeTagRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<TimeTag> all(PageQuery pageQuery) {
        return timeTagRepo.findAll(toSpecification(pageQuery,TimeTag.class), toPageRequest(pageQuery));
    }

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

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

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

