package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.DataType;
import com.izouma.jmrh.service.DataTypeService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.DataTypeRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.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("/dataType")
@AllArgsConstructor
public class DataTypeController extends BaseController {
    private DataTypeService dataTypeService;
    private DataTypeRepo    dataTypeRepo;

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


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

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

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

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

