package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.Setting;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.SettingRepo;
import com.izouma.jmrh.service.SettingService;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/setting")
@AllArgsConstructor
public class SettingController extends BaseController {
    private final SettingService settingService;
    private final SettingRepo settingRepo;

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


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

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

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

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

    @PostMapping("/allList")
    public List<Setting> allList() {
        return settingService.getTree(settingRepo.findAll());
    }

    @PostMapping("/byFlag")
    public List<Setting> byFlag(int flag) {
        List<Setting> tree = settingService.getTree(settingRepo.findAllByFlag(flag));
        return tree.get(0).getChildren();
    }
}

