package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.UserSetFlow;
import com.izouma.jiashanxia.service.UserSetFlowService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.UserSetFlowRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.SecurityUtils;
import com.izouma.jiashanxia.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("/userSetFlow")
@AllArgsConstructor
public class UserSetFlowController extends BaseController {
    private UserSetFlowService userSetFlowService;
    private UserSetFlowRepo    userSetFlowRepo;

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


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

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

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

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

    @GetMapping("/my")
    public List<UserSetFlow> my() {
        return userSetFlowRepo.findAllByUserId(SecurityUtils.getAuthenticatedUser().getId());
    }
}

