package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.Order;
import com.example.demo.model.OrderStatus;
import com.example.demo.model.PaymentMethod;
import com.example.demo.model.User;
import com.example.demo.service.OrderService;
import com.example.demo.service.UserService;
import com.example.demo.service.PaymentService;
import com.example.demo.service.AlipayService;
import com.example.demo.service.LuluPayService;
import com.example.demo.service.PayPalService;

import jakarta.validation.Valid;
import org.springframework.transaction.annotation.Transactional;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/orders")
public class OrderApiController {

    private static final Logger logger = LoggerFactory.getLogger(OrderApiController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private LuluPayService luluPayService;

    @Autowired(required = false)
    private PayPalService payPalService;
    
    /**
     * 获取订单列表
     */
    @GetMapping
    @Transactional(readOnly = true)
    public ResponseEntity<Map<String, Object>> getOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) OrderStatus status,
            @RequestParam(required = false) String paymentMethod,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String search,
            Authentication authentication) {
        try {
            // 检查认证信息
            if (authentication == null || !authentication.isAuthenticated()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户未认证，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            String username = authentication.getName();
            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户信息获取失败，请重新登录");
                return ResponseEntity.status(401).body(response);
            }
            
            // 创建排序
            Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
            
            // 如果有支付方式筛选，需要获取所有数据后在内存中筛选和分页
            final String filterPaymentMethod = paymentMethod;
            boolean hasPaymentMethodFilter = filterPaymentMethod != null && !filterPaymentMethod.isEmpty();
            
            // 获取订单列表
            Page<Order> orderPage;
            List<Order> allOrders = null;
            
            if (hasPaymentMethodFilter) {
                // 有支付方式筛选时，获取所有订单（不分页）
                Pageable unpaged = PageRequest.of(0, Integer.MAX_VALUE, sort);
                if ((user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                    orderPage = orderService.findAllOrders(unpaged, status, type, search);
                } else {
                    orderPage = orderService.findOrdersByUser(user, unpaged, status, type, search);
                }
                allOrders = orderPage.getContent();
            } else {
                // 无支付方式筛选时，正常分页
                Pageable pageable = PageRequest.of(page, size, sort);
                if ((user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                    orderPage = orderService.findAllOrders(pageable, status, type, search);
                } else {
                    orderPage = orderService.findOrdersByUser(user, pageable, status, type, search);
                }
            }

            // 转换订单数据，添加支付方式信息
            java.util.function.Function<Order, Map<String, Object>> orderMapper = order -> {
                Map<String, Object> orderData = new HashMap<>();
                orderData.put("id", order.getId());
                orderData.put("orderNumber", order.getOrderNumber());
                orderData.put("totalAmount", order.getTotalAmount());
                orderData.put("currency", order.getCurrency());
                orderData.put("status", order.getStatus());
                orderData.put("orderType", order.getOrderType());
                orderData.put("description", order.getDescription());
                orderData.put("createdAt", order.getCreatedAt());
                orderData.put("updatedAt", order.getUpdatedAt());
                orderData.put("paidAt", order.getPaidAt());

                // 添加用户信息
                if (order.getUser() != null) {
                    Map<String, Object> userData = new HashMap<>();
                    userData.put("id", order.getUser().getId());
                    userData.put("username", order.getUser().getUsername());
                    orderData.put("user", userData);
                }

                // 从订单关联的Payment中获取支付方式
                String orderPaymentMethod = null;
                if (order.getPayments() != null && !order.getPayments().isEmpty()) {
                    // 获取最新的支付记录
                    var latestPayment = order.getPayments().stream()
                        .filter(p -> p.getPaymentMethod() != null)
                        .findFirst();
                    if (latestPayment.isPresent()) {
                        orderPaymentMethod = latestPayment.get().getPaymentMethod().name();
                    }
                }
                orderData.put("paymentMethod", orderPaymentMethod);

                return orderData;
            };
            
            List<Map<String, Object>> resultContent;
            long totalElements;
            int totalPages;
            
            if (hasPaymentMethodFilter && allOrders != null) {
                // 有支付方式筛选：先转换，再筛选，最后手动分页
                List<Map<String, Object>> allMapped = allOrders.stream()
                    .map(orderMapper)
                    .filter(orderData -> filterPaymentMethod.equals(orderData.get("paymentMethod")))
                    .collect(java.util.stream.Collectors.toList());
                
                totalElements = allMapped.size();
                totalPages = (int) Math.ceil((double) totalElements / size);
                
                // 手动分页
                int fromIndex = page * size;
                int toIndex = Math.min(fromIndex + size, allMapped.size());
                if (fromIndex < allMapped.size()) {
                    resultContent = allMapped.subList(fromIndex, toIndex);
                } else {
                    resultContent = new java.util.ArrayList<>();
                }
            } else {
                // 无支付方式筛选：直接使用分页结果
                resultContent = orderPage.getContent().stream()
                    .map(orderMapper)
                    .collect(java.util.stream.Collectors.toList());
                totalElements = orderPage.getTotalElements();
                totalPages = orderPage.getTotalPages();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            
            // 构建返回的分页数据
            Map<String, Object> pageData = new HashMap<>();
            pageData.put("content", resultContent);
            pageData.put("totalElements", totalElements);
            pageData.put("totalPages", totalPages);
            pageData.put("number", page);
            pageData.put("size", size);
            response.put("data", pageData);

            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取订单列表失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取订单列表失败：" + e.getMessage()));
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getOrderById(@PathVariable Long id, 
                                                          Authentication authentication) {
        try {
            // 检查认证信息
            if (authentication == null || !authentication.isAuthenticated()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户未认证，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            String username = authentication.getName();
            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户信息获取失败，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            Order order = orderService.findById(id)
                .orElse(null);
            
            if (order == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "订单不存在");
                return ResponseEntity.status(404).body(response);
            }
            
            // 检查权限
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN")) && !order.getUser().getId().equals(user.getId())) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权限访问此订单");
                return ResponseEntity.status(403).body(response);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", order);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取订单详情失败：", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取订单详情失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createOrder(@Valid @RequestBody Order order,
                                                         Authentication authentication) {
        try {
            // 检查认证信息
            if (authentication == null || !authentication.isAuthenticated()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户未认证，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            String username = authentication.getName();
            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户信息获取失败，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            order.setUser(user);
            
            Order createdOrder = orderService.createOrder(order);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单创建成功");
            response.put("data", createdOrder);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("创建订单失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建订单失败：" + e.getMessage()));
        }
    }
    
    /**
     * 更新订单状态
     */
    @PostMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updateOrderStatus(@PathVariable Long id,
                                                              @RequestBody Map<String, String> request,
                                                              Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN")) && !order.getUser().getId().equals(user.getId())) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限操作此订单"));
            }
            
            OrderStatus status = OrderStatus.valueOf(request.get("status"));
            String notes = request.get("notes");
            
            Order updatedOrder = orderService.updateOrderStatus(id, status);
            
            if (notes != null && !notes.trim().isEmpty()) {
                updatedOrder.setNotes((updatedOrder.getNotes() != null ? updatedOrder.getNotes() + "\n" : "") + notes);
                orderService.createOrder(updatedOrder);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单状态更新成功");
            response.put("data", updatedOrder);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新订单状态失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("更新订单状态失败：" + e.getMessage()));
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public ResponseEntity<Map<String, Object>> cancelOrder(@PathVariable Long id,
                                                         @RequestBody Map<String, String> request,
                                                         Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN")) && !order.getUser().getId().equals(user.getId())) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限操作此订单"));
            }
            
            String reason = request.get("reason");
            Order cancelledOrder = orderService.cancelOrder(id, reason);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单取消成功");
            response.put("data", cancelledOrder);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("取消订单失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("取消订单失败：" + e.getMessage()));
        }
    }
    
    /**
     * 发货
     */
    @PostMapping("/{id}/ship")
    public ResponseEntity<Map<String, Object>> shipOrder(@PathVariable Long id,
                                                        @RequestBody Map<String, String> request,
                                                        Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);

            // 只有管理员可以发货
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限操作此订单"));
            }
            
            String trackingNumber = request.get("trackingNumber");
            Order shippedOrder = orderService.shipOrder(id, trackingNumber);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单发货成功");
            response.put("data", shippedOrder);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("订单发货失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("订单发货失败：" + e.getMessage()));
        }
    }
    
    /**
     * 完成订单
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<Map<String, Object>> completeOrder(@PathVariable Long id,
                                                           Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);

            // 只有管理员可以完成订单
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限操作此订单"));
            }
            
            Order completedOrder = orderService.completeOrder(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单完成成功");
            response.put("data", completedOrder);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("完成订单失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("完成订单失败：" + e.getMessage()));
        }
    }
    
    /**
     * 创建订单支付
     */
    @PostMapping("/{id}/pay")
    public ResponseEntity<Map<String, Object>> createOrderPayment(@PathVariable Long id,
                                                                 @RequestBody Map<String, String> request,
                                                                 Authentication authentication,
                                                                 HttpServletRequest httpRequest) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!order.getUser().getId().equals(user.getId())) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限操作此订单"));
            }
            
            // 检查订单状态
            if (!order.canPay()) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("订单当前状态不允许支付"));
            }
            
            String pm = request.get("paymentMethod");
            if (pm == null || pm.isBlank()) {
                return ResponseEntity.badRequest().body(createErrorResponse("paymentMethod不能为空"));
            }
            PaymentMethod paymentMethod = PaymentMethod.valueOf(pm);

            // 1) 创建支付记录并绑定订单
            var payment = paymentService.createOrderPayment(order, paymentMethod);

            // 2) 根据支付方式创建第三方支付
            String clientIp = httpRequest != null ? httpRequest.getRemoteAddr() : null;
            Map<String, Object> providerData = new HashMap<>();

            if (paymentMethod == PaymentMethod.PAYPAL) {
                if (payPalService == null) {
                    return ResponseEntity.badRequest().body(createErrorResponse("PayPal服务未配置"));
                }
                providerData = payPalService.createPayment(payment);
            } else if (paymentMethod == PaymentMethod.ALIPAY) {
                providerData = alipayService.createPayment(payment, clientIp);
            } else {
                // 其他方式走噜噜支付（wxpay/qqpay/bank等）
                String payType = request.getOrDefault("payType", "alipay");
                providerData = luluPayService.createPayment(payment, payType, clientIp);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付创建成功");

            Map<String, Object> data = new HashMap<>();
            data.put("paymentId", payment.getId());
            data.put("orderId", order.getId());
            data.put("orderNumber", order.getOrderNumber());
            data.put("provider", providerData);
            response.put("data", data);

            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("创建订单支付失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建订单支付失败：" + e.getMessage()));
        }
    }
    
    /**
     * 获取订单统计
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getOrderStats(Authentication authentication) {
        try {
            // 检查认证信息
            if (authentication == null || !authentication.isAuthenticated()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户未认证，请重新登录");
                return ResponseEntity.status(401).body(response);
            }

            String username = authentication.getName();
            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户信息获取失败，请重新登录");
                return ResponseEntity.status(401).body(response);
            }
            
            // 获取统计数据
            Map<String, Object> stats;
            if ((user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                // 管理员查看所有订单统计
                stats = orderService.getOrderStats();
            } else {
                // 普通用户查看自己的订单统计
                stats = orderService.getOrderStatsByUser(user);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取订单统计失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取订单统计失败：" + e.getMessage()));
        }
    }
    
    /**
     * 删除订单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteOrder(@PathVariable Long id,
                                                         Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN")) && !order.getUser().getId().equals(user.getId())) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限删除此订单"));
            }
            
            orderService.deleteOrder(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除订单失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("删除订单失败：" + e.getMessage()));
        }
    }
    
    /**
     * 批量删除订单
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteOrders(@RequestBody List<Long> orderIds,
                                                           Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);

            // 只有管理员可以批量删除
            if (!(user.getRole().equals("ROLE_ADMIN") || user.getRole().equals("ROLE_SUPER_ADMIN"))) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限批量删除订单"));
            }
            
            int deletedCount = orderService.deleteOrdersByIds(orderIds);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量删除成功，共删除 " + deletedCount + " 个订单");
            response.put("deletedCount", deletedCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("批量删除订单失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("批量删除订单失败：" + e.getMessage()));
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}
