package com.izouma.nineth.web;

import com.alibaba.excel.util.CollectionUtils;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.UserHoldDTO;
import com.izouma.nineth.service.UserHoldCountService;
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.Comparator;
import java.util.List;

@RestController
@RequestMapping("/userHold")
@AllArgsConstructor
public class UserHoldCountController {

    private UserHoldCountService userHoldCountService;

    @PostMapping("/all")
    public Page<UserHoldDTO> all(@RequestBody PageQuery pageQuery) {
        return userHoldCountService.all(pageQuery).toPage();
    }

    @GetMapping("/top")
    public List<UserHoldDTO> top() {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPage(0);
        pageQuery.setSize(50);
        List<UserHoldDTO> userHoldDTOs = userHoldCountService.all(pageQuery).getContent();
        userHoldDTOs.sort(Comparator.comparing(UserHoldDTO::getPrice).reversed());
        return userHoldDTOs;
    }

    @GetMapping("/app/top")
    public List<UserHoldDTO> appTop() {
        List<UserHoldDTO> top = top();
        if (CollectionUtils.isEmpty(top)) {
            return null;
        }
        top.forEach(userHoldDTO -> {
            userHoldDTO.setNum(0);
            userHoldDTO.setUsername(null);
            userHoldDTO.setPrefixName(null);
            userHoldDTO.setName(null);
            userHoldDTO.setPrice(null);
            userHoldDTO.setUserId(null);
        });
        return top;
    }

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