package com.izouma.uwip.web;

import com.izouma.uwip.domain.Maintenance;
import com.izouma.uwip.service.MaintenanceService;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.MaintenanceRepo;
import com.izouma.uwip.utils.ObjUtils;
import com.izouma.uwip.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("/maintenance")
@AllArgsConstructor
public class MaintenanceController extends BaseController {
    private MaintenanceService maintenanceService;
    private MaintenanceRepo    maintenanceRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Maintenance save(@RequestBody Maintenance record) {
        if (record.getDescription() == null) {
            throw new BusinessException("父级描述不能为空");
        }
        if (record.getId() != null) {
            Maintenance orig = maintenanceRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return maintenanceRepo.save(orig);
        }
        if (record.getParent() == null) {
            record.setFlag(record.getDescription());
        }
        return maintenanceRepo.save(record);
    }


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

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

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

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

    @PostMapping("/getTree")
    public List<Maintenance> getTree() {
        return maintenanceService.getTree(maintenanceRepo.findAll(), null);
    }

    @PostMapping("/byDesc")
    public List<Maintenance> byDesc(@RequestParam String description) {
        return maintenanceService.getTree(maintenanceRepo.findAllByFlag(description),null);
    }
}

