package com.izouma.zhirongip.web.resource;

import cn.hutool.core.convert.Convert;
import com.izouma.zhirongip.web.BaseController;
import com.izouma.zhirongip.domain.resource.SuccessCase;
import com.izouma.zhirongip.service.resource.SuccessCaseService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.resource.SuccessCaseRepo;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.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;
import java.util.Map;

@RestController
@RequestMapping("/successCase")
@AllArgsConstructor
public class SuccessCaseController extends BaseController {
    private final SuccessCaseService successCaseService;
    private final SuccessCaseRepo    successCaseRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<SuccessCase> all(@RequestBody PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        Object moneyObj = query.get("money");
        String money = Convert.convert(String.class, moneyObj);
        return successCaseService.all(pageQuery, money);
    }

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

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

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

