package com.example.demo.controller;

import com.example.demo.model.*;
import com.example.demo.service.OrderService;
import jakarta.validation.Valid;
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.*;

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

@RestController
@RequestMapping("/api/orders")
public class OrderApiController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderApiController.class);
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 获取订单列表
     */
    @GetMapping
    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 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);
            }
            
            User user = (User) authentication.getPrincipal();
            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);
            Pageable pageable = PageRequest.of(page, size, sort);
            
            // 获取订单列表
            Page<Order> orderPage;
            if (user.getRole().equals("ROLE_ADMIN")) {
                // 管理员可以查看所有订单
                orderPage = orderService.findAllOrders(pageable, status, search);
            } else {
                // 普通用户只能查看自己的订单
                orderPage = orderService.findOrdersByUser(user, pageable, status, search);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", orderPage);
            
            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 {
            User user = (User) authentication.getPrincipal();
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!user.getRole().equals("ROLE_ADMIN") && !order.getUser().getId().equals(user.getId())) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("无权限访问此订单"));
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", order);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取订单详情失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取订单详情失败：" + e.getMessage()));
        }
    }
    
    /**
     * 创建订单
     */
    @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);
            }
            
            User user = (User) authentication.getPrincipal();
            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 {
            User user = (User) authentication.getPrincipal();
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!user.getRole().equals("ROLE_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 {
            User user = (User) authentication.getPrincipal();
            Order order = orderService.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 检查权限
            if (!user.getRole().equals("ROLE_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 {
            User user = (User) authentication.getPrincipal();
            
            // 只有管理员可以发货
            if (!user.getRole().equals("ROLE_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 {
            User user = (User) authentication.getPrincipal();
            
            // 只有管理员可以完成订单
            if (!user.getRole().equals("ROLE_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) {
        try {
            User user = (User) authentication.getPrincipal();
            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("订单当前状态不允许支付"));
            }
            
            PaymentMethod paymentMethod = PaymentMethod.valueOf(request.get("paymentMethod"));
            
            // 这里应该调用支付服务创建支付
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付创建成功");
            
            // 模拟支付URL
            Map<String, Object> data = new HashMap<>();
            data.put("paymentId", "payment-" + System.currentTimeMillis());
            data.put("paymentUrl", "/payment/" + paymentMethod.name().toLowerCase() + "/create?orderId=" + id);
            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);
            }
            
            User user = (User) authentication.getPrincipal();
            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")) {
                // 管理员查看所有订单统计
                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()));
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}
