package com.izouma.uwip.web;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.izouma.uwip.domain.Docking;
import com.izouma.uwip.service.DockingService;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.DockingRepo;
import com.izouma.uwip.utils.ObjUtils;
import com.izouma.uwip.utils.SecurityUtils;
import com.izouma.uwip.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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("/docking")
@AllArgsConstructor
public class DockingController extends BaseController {
    private DockingService dockingService;
    private DockingRepo    dockingRepo;

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


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

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

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

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

    @PostMapping("/batchSave")
    @ApiOperation("批量保存")
    public void batchSave(String dockings) {
        if (StringUtils.isNotEmpty(dockings)) {
            List<Docking> dockingList = JSONObject.parseArray(dockings, Docking.class);
            dockingService.batchSave(dockingList);
        }
    }
}

