package com.gpf.pethospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gpf.pethospital.common.ApiResponse;
import com.gpf.pethospital.entity.Order;
import com.gpf.pethospital.entity.Prescription;
import com.gpf.pethospital.entity.PrescriptionItem;
import com.gpf.pethospital.entity.Visit;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.OrderService;
import com.gpf.pethospital.service.PrescriptionItemService;
import com.gpf.pethospital.service.PrescriptionService;
import com.gpf.pethospital.service.VisitService;
import com.gpf.pethospital.util.SecurityUtils;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {
    private final OrderService orderService;
    private final PrescriptionService prescriptionService;
    private final PrescriptionItemService prescriptionItemService;
    private final VisitService visitService;

    public OrderController(OrderService orderService, 
                          PrescriptionService prescriptionService,
                          PrescriptionItemService prescriptionItemService,
                          VisitService visitService) {
        this.orderService = orderService;
        this.prescriptionService = prescriptionService;
        this.prescriptionItemService = prescriptionItemService;
        this.visitService = visitService;
    }

    /**
     * 根据处方生成订单
     */
    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PostMapping("/from-prescription/{prescriptionId}")
    public ApiResponse<?> createFromPrescription(@PathVariable Long prescriptionId) {
        // 1. 查询处方
        Prescription prescription = prescriptionService.getById(prescriptionId);
        if (prescription == null) {
            return ApiResponse.error(404, "处方不存在");
        }
        
        // 2. 检查处方状态，只有草稿状态可以生成订单
        if (!"DRAFT".equals(prescription.getStatus())) {
            return ApiResponse.error(400, "该处方已提交或已处理，无法重复生成订单");
        }
        
        // 3. 检查是否已有关联订单
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(Order::getPrescriptionId, prescriptionId);
        Order existingOrder = orderService.getOne(orderWrapper);
        if (existingOrder != null) {
            return ApiResponse.error(400, "该处方已生成订单");
        }
        
        // 4. 查询就诊记录获取顾客ID
        Visit visit = visitService.getById(prescription.getVisitId());
        if (visit == null) {
            return ApiResponse.error(404, "关联的就诊记录不存在");
        }
        
        // 5. 查询处方明细计算总金额
        LambdaQueryWrapper<PrescriptionItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(PrescriptionItem::getPrescriptionId, prescriptionId);
        List<PrescriptionItem> items = prescriptionItemService.list(itemWrapper);
        
        if (items.isEmpty()) {
            return ApiResponse.error(400, "处方中没有药品明细");
        }
        
        BigDecimal totalAmount = items.stream()
            .map(PrescriptionItem::getSubtotal)
            .filter(subtotal -> subtotal != null)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 6. 生成订单号：ORD + 年月日 + 6位随机数
        String orderNo = generateOrderNo();
        
        // 7. 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setPrescriptionId(prescriptionId);
        order.setVisitId(prescription.getVisitId());
        order.setCustomerId(visit.getCustomerId());
        order.setAmount(totalAmount);
        order.setStatus("UNPAID");
        order.setRemark("由处方自动生成");
        
        orderService.save(order);
        
        // 8. 更新处方状态为已提交
        prescription.setStatus("SUBMITTED");
        prescriptionService.updateById(prescription);
        
        return ApiResponse.success("订单生成成功", order);
    }

    /**
     * 获取订单详情（包含处方明细）
     */
    @GetMapping("/{id}")
    public ApiResponse<?> detail(@PathVariable Long id) {
        Order order = orderService.getById(id);
        if (order == null) {
            return ApiResponse.error(404, "订单不存在");
        }
        
        // 权限检查：顾客只能查看自己的订单
        AuthUser user = SecurityUtils.currentUser();
        if (user != null && "CUSTOMER".equals(user.getRole()) 
            && !user.getId().equals(order.getCustomerId())) {
            return ApiResponse.error(403, "无权查看此订单");
        }
        
        // 查询关联的处方明细
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        
        if (order.getPrescriptionId() != null) {
            LambdaQueryWrapper<PrescriptionItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PrescriptionItem::getPrescriptionId, order.getPrescriptionId());
            List<PrescriptionItem> items = prescriptionItemService.list(wrapper);
            result.put("items", items);
        }
        
        return ApiResponse.success(result);
    }

    @PostMapping
    public ApiResponse<?> create(@RequestBody Order order) {
        AuthUser user = SecurityUtils.currentUser();
        if (user != null && "CUSTOMER".equals(user.getRole())) {
            order.setCustomerId(user.getId());
        }
        if (order.getStatus() == null) {
            order.setStatus("UNPAID");
        }
        orderService.save(order);
        return ApiResponse.success("created", null);
    }

    @GetMapping
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size) {
        AuthUser user = SecurityUtils.currentUser();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        if (user != null && "CUSTOMER".equals(user.getRole())) {
            wrapper.eq(Order::getCustomerId, user.getId());
        }
        wrapper.orderByDesc(Order::getCreateTime);
        return ApiResponse.success(orderService.page(new Page<>(page, size), wrapper));
    }

    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PutMapping("/{id}")
    public ApiResponse<?> update(@PathVariable Long id, @RequestBody Order order) {
        order.setId(id);
        orderService.updateById(order);
        return ApiResponse.success("updated", null);
    }

    @PutMapping("/{id}/pay")
    public ApiResponse<?> pay(@PathVariable Long id, @RequestParam String paymentMethod) {
        Order order = orderService.getById(id);
        if (order == null) {
            return ApiResponse.error(404, "订单不存在");
        }
        
        if (!"UNPAID".equals(order.getStatus())) {
            return ApiResponse.error(400, "订单状态不允许支付");
        }
        
        order.setStatus("PAID");
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTime(LocalDateTime.now());
        orderService.updateById(order);
        
        return ApiResponse.success("支付成功", null);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomStr = String.format("%06d", (int)(Math.random() * 1000000));
        return "ORD" + dateStr + randomStr;
    }
}
