package com.izouma.nineth.web;

import com.izouma.nineth.domain.Order;
import com.izouma.nineth.dto.OrderDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.CollectionType;
import com.izouma.nineth.enums.OrderStatus;
import com.izouma.nineth.enums.PayMethod;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.OrderRepo;
import com.izouma.nineth.service.OrderService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@AllArgsConstructor
public class OrderController extends BaseController {
    private OrderService orderService;
    private OrderRepo    orderRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Order> all(@RequestBody PageQuery pageQuery) {
        return orderService.all(pageQuery);
    }

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

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

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Order> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data.stream().map(order -> {
            OrderDTO dto = new OrderDTO();
            BeanUtils.copyProperties(order, dto);
            dto.setStatus(Optional.ofNullable(order.getStatus()).map(OrderStatus::getDescription).orElse(null));
            dto.setPayMethod(Optional.ofNullable(order.getPayMethod()).map(PayMethod::getDescription).orElse(null));
            dto.setType(Optional.ofNullable(order.getType()).map(CollectionType::getDescription).orElse(null));
            return dto;
        }).collect(Collectors.toList()));
    }

    @PostMapping("/create")
    public Order create(@RequestParam Long collectionId, @RequestParam int qty, @RequestParam(required = false) Long addressId, @RequestParam(required = false) Long couponId) {
        return orderService.create(SecurityUtils.getAuthenticatedUser().getId(),
                collectionId, qty, addressId, couponId);
    }

    @PostMapping("/hide")
    public void hide(@RequestParam Long id) {
        Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
        order.setHide(true);
        orderRepo.save(order);
    }
}

