package com.example.demo.controller;

import com.example.demo.model.*;
import com.example.demo.service.OrderService;
import com.example.demo.service.PaymentService;
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.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/orders")
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private PaymentService paymentService;
    
    /**
     * 显示订单列表
     */
    @GetMapping
    public String orderList(@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,
                           Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<Order> orders;
            if (status != null) {
                orders = orderService.findByStatus(status, pageable);
            } else {
                orders = orderService.findByUserId(user.getId(), pageable);
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", orders.getTotalPages());
            model.addAttribute("totalElements", orders.getTotalElements());
            model.addAttribute("status", status);
            model.addAttribute("search", search);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortDir", sortDir);
            model.addAttribute("orderStatuses", OrderStatus.values());
            
            return "orders/list";
            
        } catch (Exception e) {
            logger.error("获取订单列表失败：", e);
            model.addAttribute("error", "获取订单列表失败：" + e.getMessage());
            return "orders/list";
        }
    }
    
    /**
     * 显示订单详情
     */
    @GetMapping("/{id}")
    public String orderDetail(@PathVariable Long id, 
                            Authentication authentication, 
                            Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            Optional<Order> orderOpt = orderService.findById(id);
            
            if (!orderOpt.isPresent()) {
                model.addAttribute("error", "订单不存在");
                return "orders/detail";
            }
            
            Order order = orderOpt.get();
            
            // 检查权限：用户只能查看自己的订单，管理员可以查看所有订单
            if (!user.getRole().equals("ROLE_ADMIN") && !order.getUser().getId().equals(user.getId())) {
                model.addAttribute("error", "无权限访问此订单");
                return "orders/detail";
            }
            
            model.addAttribute("order", order);
            model.addAttribute("orderStatuses", OrderStatus.values());
            
            return "orders/detail";
            
        } catch (Exception e) {
            logger.error("获取订单详情失败：", e);
            model.addAttribute("error", "获取订单详情失败：" + e.getMessage());
            return "orders/detail";
        }
    }
    
    /**
     * 显示创建订单表单
     */
    @GetMapping("/create")
    public String showCreateOrderForm(Model model) {
        Order order = new Order();
        order.setOrderItems(new ArrayList<>());
        order.setOrderItems(new ArrayList<>());
        
        // 添加一个空的订单项
        OrderItem item = new OrderItem();
        item.setQuantity(1);
        item.setUnitPrice(BigDecimal.ZERO);
        order.getOrderItems().add(item);
        
        model.addAttribute("order", order);
        model.addAttribute("orderTypes", OrderType.values());
        model.addAttribute("orderStatuses", OrderStatus.values());
        
        return "orders/form";
    }
    
    /**
     * 处理创建订单
     */
    @PostMapping("/create")
    public String createOrder(@Valid @ModelAttribute Order order, 
                            BindingResult result,
                            Authentication authentication,
                            Model model) {
        try {
            if (result.hasErrors()) {
                model.addAttribute("orderTypes", OrderType.values());
                model.addAttribute("orderStatuses", OrderStatus.values());
                return "orders/form";
            }
            
            User user = (User) authentication.getPrincipal();
            order.setUser(user);
            
            // 验证订单项
            if (order.getOrderItems() == null || order.getOrderItems().isEmpty()) {
                model.addAttribute("error", "订单必须包含至少一个商品");
                model.addAttribute("orderTypes", OrderType.values());
                model.addAttribute("orderStatuses", OrderStatus.values());
                return "orders/form";
            }
            
            // 过滤掉空的订单项
            order.getOrderItems().removeIf(item -> 
                item.getProductName() == null || item.getProductName().trim().isEmpty() ||
                item.getQuantity() == null || item.getQuantity() <= 0 ||
                item.getUnitPrice() == null || item.getUnitPrice().compareTo(BigDecimal.ZERO) <= 0);
            
            if (order.getOrderItems().isEmpty()) {
                model.addAttribute("error", "订单必须包含至少一个有效商品");
                model.addAttribute("orderTypes", OrderType.values());
                model.addAttribute("orderStatuses", OrderStatus.values());
                return "orders/form";
            }
            
            Order createdOrder = orderService.createOrder(order);
            model.addAttribute("success", "订单创建成功，订单号：" + createdOrder.getOrderNumber());
            
            return "redirect:/orders/" + createdOrder.getId();
            
        } catch (Exception e) {
            logger.error("创建订单失败：", e);
            model.addAttribute("error", "创建订单失败：" + e.getMessage());
            model.addAttribute("orderTypes", OrderType.values());
            model.addAttribute("orderStatuses", OrderStatus.values());
            return "orders/form";
        }
    }
    
    /**
     * 更新订单状态
     */
    @PostMapping("/{id}/status")
    public String updateOrderStatus(@PathVariable Long id,
                                  @RequestParam OrderStatus status,
                                  @RequestParam(required = false) String notes,
                                  Authentication authentication,
                                  Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            Optional<Order> orderOpt = orderService.findById(id);
            
            if (!orderOpt.isPresent()) {
                model.addAttribute("error", "订单不存在");
                return "redirect:/orders";
            }
            
            Order order = orderOpt.get();
            
            // 检查权限
            if (!user.getRole().equals("ROLE_ADMIN") && !order.getUser().getId().equals(user.getId())) {
                model.addAttribute("error", "无权限操作此订单");
                return "redirect:/orders";
            }
            
            Order updatedOrder = orderService.updateOrderStatus(id, status);
            
            if (notes != null && !notes.trim().isEmpty()) {
                updatedOrder.setNotes((updatedOrder.getNotes() != null ? updatedOrder.getNotes() + "\n" : "") + notes);
                orderService.createOrder(updatedOrder); // 保存备注
            }
            
            model.addAttribute("success", "订单状态更新成功");
            return "redirect:/orders/" + id;
            
        } catch (Exception e) {
            logger.error("更新订单状态失败：", e);
            model.addAttribute("error", "更新订单状态失败：" + e.getMessage());
            return "redirect:/orders/" + id;
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public String cancelOrder(@PathVariable Long id,
                            @RequestParam(required = false) String reason,
                            Authentication authentication,
                            Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            Optional<Order> orderOpt = orderService.findById(id);
            
            if (!orderOpt.isPresent()) {
                model.addAttribute("error", "订单不存在");
                return "redirect:/orders";
            }
            
            Order order = orderOpt.get();
            
            // 检查权限
            if (!user.getRole().equals("ROLE_ADMIN") && !order.getUser().getId().equals(user.getId())) {
                model.addAttribute("error", "无权限操作此订单");
                return "redirect:/orders";
            }
            
            Order cancelledOrder = orderService.cancelOrder(id, reason);
            model.addAttribute("success", "订单取消成功");
            
            return "redirect:/orders/" + id;
            
        } catch (Exception e) {
            logger.error("取消订单失败：", e);
            model.addAttribute("error", "取消订单失败：" + e.getMessage());
            return "redirect:/orders/" + id;
        }
    }
    
    /**
     * 发货
     */
    @PostMapping("/{id}/ship")
    public String shipOrder(@PathVariable Long id,
                           @RequestParam(required = false) String trackingNumber,
                           Authentication authentication,
                           Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            
            // 只有管理员可以发货
            if (!user.getRole().equals("ROLE_ADMIN")) {
                model.addAttribute("error", "无权限操作此订单");
                return "redirect:/orders/" + id;
            }
            
            Order shippedOrder = orderService.shipOrder(id, trackingNumber);
            model.addAttribute("success", "订单发货成功");
            
            return "redirect:/orders/" + id;
            
        } catch (Exception e) {
            logger.error("订单发货失败：", e);
            model.addAttribute("error", "订单发货失败：" + e.getMessage());
            return "redirect:/orders/" + id;
        }
    }
    
    /**
     * 完成订单
     */
    @PostMapping("/{id}/complete")
    public String completeOrder(@PathVariable Long id,
                              Authentication authentication,
                              Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            
            // 只有管理员可以完成订单
            if (!user.getRole().equals("ROLE_ADMIN")) {
                model.addAttribute("error", "无权限操作此订单");
                return "redirect:/orders/" + id;
            }
            
            Order completedOrder = orderService.completeOrder(id);
            model.addAttribute("success", "订单完成成功");
            
            return "redirect:/orders/" + id;
            
        } catch (Exception e) {
            logger.error("完成订单失败：", e);
            model.addAttribute("error", "完成订单失败：" + e.getMessage());
            return "redirect:/orders/" + id;
        }
    }
    
    /**
     * 为订单创建支付
     */
    @PostMapping("/{id}/pay")
    public String createPaymentForOrder(@PathVariable Long id,
                                      @RequestParam PaymentMethod paymentMethod,
                                      Authentication authentication,
                                      Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            Optional<Order> orderOpt = orderService.findById(id);
            
            if (!orderOpt.isPresent()) {
                model.addAttribute("error", "订单不存在");
                return "redirect:/orders";
            }
            
            Order order = orderOpt.get();
            
            // 检查权限
            if (!order.getUser().getId().equals(user.getId())) {
                model.addAttribute("error", "无权限操作此订单");
                return "redirect:/orders";
            }
            
            // 检查订单状态
            if (!order.canPay()) {
                model.addAttribute("error", "订单当前状态不允许支付");
                return "redirect:/orders/" + id;
            }
            
            // 创建支付记录
            Payment savedPayment = paymentService.createOrderPayment(order, paymentMethod);
            
            // 根据支付方式跳转到相应的支付页面
            if (paymentMethod == PaymentMethod.ALIPAY) {
                return "redirect:/payment/alipay/create?paymentId=" + savedPayment.getId();
            } else if (paymentMethod == PaymentMethod.PAYPAL) {
                return "redirect:/payment/paypal/create?paymentId=" + savedPayment.getId();
            } else {
                model.addAttribute("error", "不支持的支付方式");
                return "redirect:/orders/" + id;
            }
            
        } catch (Exception e) {
            logger.error("创建订单支付失败：", e);
            model.addAttribute("error", "创建订单支付失败：" + e.getMessage());
            return "redirect:/orders/" + id;
        }
    }
    
    /**
     * 管理员订单管理页面
     */
    @GetMapping("/admin")
    public String adminOrderList(@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,
                                Model model) {
        try {
            User user = (User) authentication.getPrincipal();
            
            // 只有管理员可以访问
            if (!user.getRole().equals("ROLE_ADMIN")) {
                model.addAttribute("error", "无权限访问");
                return "redirect:/orders";
            }
            
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<Order> orders;
            if (status != null) {
                orders = orderService.findByStatus(status, pageable);
            } else {
                orders = orderService.findAll(pageable);
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", orders.getTotalPages());
            model.addAttribute("totalElements", orders.getTotalElements());
            model.addAttribute("status", status);
            model.addAttribute("search", search);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortDir", sortDir);
            model.addAttribute("orderStatuses", OrderStatus.values());
            model.addAttribute("isAdmin", true);
            
            return "orders/admin";
            
        } catch (Exception e) {
            logger.error("获取管理员订单列表失败：", e);
            model.addAttribute("error", "获取订单列表失败：" + e.getMessage());
            return "orders/admin";
        }
    }
}
