package com.izouma.dingdong.web;

import com.izouma.dingdong.domain.PlatformFlow;
import com.izouma.dingdong.enums.FlowType;
import com.izouma.dingdong.service.PlatformFlowService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.PlatformFlowRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/platformFlow")
@AllArgsConstructor
public class PlatformFlowController extends BaseController {
    private PlatformFlowService platformFlowService;
    private PlatformFlowRepo    platformFlowRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<PlatformFlow> all(PageQuery pageQuery) {
        return platformFlowRepo.findAll(toSpecification(pageQuery, PlatformFlow.class), toPageRequest(pageQuery));
    }

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

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

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

    @GetMapping("/getDashboard")
    public Map<String, Object> getDashboard() {
        return platformFlowService.getDashboard();
    }

    @GetMapping("/statistics")
    public Map<Object, BigDecimal> statistics(String type, FlowType flowType) {
        return platformFlowService.statistics(type, flowType);
    }
}

