package com.izouma.zhirongip.web.resource;

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

@RestController
@RequestMapping("/purchase")
@AllArgsConstructor
public class PurchaseController extends BaseController {
    private final PurchaseService purchaseService;
    private final PurchaseRepo    purchaseRepo;

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


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

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

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

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

    @ApiOperation("相关推荐")
    @GetMapping("/recommend")
    public Page<Purchase> recommend(@RequestParam Long id) {
        return purchaseService.recommend(id);
    }
}

