package me.zhengjie.modules.flow.rest;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.flow.domain.Flow;
import me.zhengjie.modules.flow.service.FlowService;
import me.zhengjie.modules.flow.service.dto.FlowDto;
import me.zhengjie.modules.flow.service.dto.FlowQueryCriteria;
import me.zhengjie.utils.PageResult;

@RestController
@RequiredArgsConstructor
@Api(tags = "/system/flow/管理")
@RequestMapping("/api/flow")
public class FlowController {

    private final FlowService flowService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('flow:list')")
    public void exportFlow(HttpServletResponse response, FlowQueryCriteria criteria) throws IOException {
        flowService.download(flowService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询/system/flow/")
    @ApiOperation("查询/system/flow/")
    @PreAuthorize("@el.check('flow:list')")
    public ResponseEntity<PageResult<FlowDto>> queryFlow(FlowQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(flowService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增/system/flow/")
    @ApiOperation("新增/system/flow/")
    @PreAuthorize("@el.check('flow:add')")
    public ResponseEntity<Object> createFlow(@Validated @RequestBody Flow resources) {
        flowService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改/system/flow/")
    @ApiOperation("修改/system/flow/")
    @PreAuthorize("@el.check('flow:edit')")
    public ResponseEntity<Object> updateFlow(@Validated @RequestBody Flow resources) {
        flowService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除/system/flow/")
    @ApiOperation("删除/system/flow/")
    @PreAuthorize("@el.check('flow:del')")
    public ResponseEntity<Object> deleteFlow(@RequestBody Long[] ids) {
        flowService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}