package com.izouma.zhirongip.web;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.zhirongip.domain.Navigation;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.enums.NavType;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.NavigationRepo;
import com.izouma.zhirongip.service.NavigationService;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/navigation")
@AllArgsConstructor
public class NavigationController extends BaseController {
    private final NavigationService navigationService;
    private final NavigationRepo    navigationRepo;

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


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

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

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

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

    @PostMapping("/type")
    public List<Navigation> type(NavType type) {
        return navigationService.getTree(navigationRepo.findAllByType(type));
    }

    @PostMapping("/backAll")
    public List<Navigation> backAll(NavType type) {
        if (ObjectUtil.isNotNull(type)) {
            return this.type(type);
        }
        return navigationService.getTree(navigationRepo.findAll());
    }

    @ApiOperation("供给侧子菜单")
    @PostMapping("/supply")
    public List<Navigation> supply() {
        return navigationService.getChildren(156L);
    }

    @ApiOperation("需求侧子菜单")
    @PostMapping("/demand")
    public List<Navigation> demand() {
        return navigationService.getChildren(166L);
    }
}

