package com.izouma.nineth.web;

import com.izouma.nineth.domain.GiftOrder;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.GiftOrderDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.PageWrapDTO;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.GiftOrderRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.service.GiftOrderService;
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.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/giftOrder")
@AllArgsConstructor
public class GiftOrderController extends BaseController {
    private GiftOrderService giftOrderService;
    private GiftOrderRepo    giftOrderRepo;
    private UserRepo         userRepo;


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public PageWrapDTO<GiftOrderDTO> all(@RequestBody PageQuery pageQuery) {
        PageWrapDTO<GiftOrder> all = giftOrderService.all(pageQuery);
        Set<Long> userIds = new HashSet<>();
        all.getContent().forEach(go -> {
            userIds.add(go.getUserId());
            userIds.add(go.getToUserId());
        });
        Map<Long, String> userMap = userRepo.findByIdInAndDelFalse(userIds)
                .stream()
                .collect(Collectors.toMap(User::getId, User::getNickname));
        List<GiftOrderDTO> newContent = new ArrayList<>();
        all.getContent().forEach(go -> {
            GiftOrderDTO dto = new GiftOrderDTO(go);
            dto.setNickname(userMap.get(go.getUserId()));
            dto.setToNickname(userMap.get(go.getToUserId()));
            dto.setStatus(go.getStatus() == null ? "" :go.getStatus().getDescription());
            dto.setPayMethod(go.getPayMethod() == null ? "" : go.getPayMethod().getDescription());
            newContent.add(dto);
        });

        PageWrapDTO<GiftOrderDTO> newPage = new PageWrapDTO<>(newContent, all.getPageable(), all.getTotalElements());
        newPage.setTotalAmount(all.getTotalAmount());
        return newPage;
    }

    @GetMapping("/get/{id}")
    public GiftOrder get(@PathVariable Long id) {
        return giftOrderRepo.findById(id).orElseThrow(new BusinessException("转赠无记录"));
    }

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

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



}

