package com.izouma.nineth.web;

import com.izouma.nineth.domain.OnOff;
import com.izouma.nineth.dto.MetaRestResult;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.OnOffRepo;
import com.izouma.nineth.service.OnOffService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.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;
import java.util.Objects;

@RestController
@RequestMapping("/onOff")
@AllArgsConstructor
public class OnOffController extends BaseController {
    private OnOffService onOffService;
    private OnOffRepo onOffRepo;

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


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

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

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

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

    @GetMapping("/{id}/detail")
    public MetaRestResult<OnOff> detail(@PathVariable Long id) {
        OnOff onOff = onOffRepo.findById(id).orElse(null);
        if (Objects.isNull(onOff)) {
            return MetaRestResult.returnError(String.format("没有id为：%S的开关信息", id));
        }
        return MetaRestResult.returnSuccess(onOff);
    }
    @PostMapping("/meta/save")
    public MetaRestResult<OnOff> metaSave(@RequestBody OnOff onOff) {
        if (Objects.isNull(onOff.getStatus())) {
            return MetaRestResult.returnError("参数不合法，缺少开关状态");
        }
        if(Objects.isNull(onOff.getId())) {
            return MetaRestResult.returnSuccess("新增成功", onOffRepo.save(onOff));
        }
        OnOff orig = onOffRepo.findById(onOff.getId()).orElse(null);
        if (Objects.isNull(orig)) {
            return MetaRestResult.returnError(String.format("没有id为：%S的开关信息", onOff.getId()));
        }
        ObjUtils.merge(orig, onOff);
        return MetaRestResult.returnSuccess("修改成功", onOffRepo.save(orig));
    }
}

