package com.haha.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.haha.common.vo.Result;
import com.haha.entity.Order;
import com.haha.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 订单相关接口
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 获取订单列表
     *
     * 业务流程：
     * 1. 获取当前登录用户ID
     * 2. 根据状态筛选查询订单列表
     * 3. 解析订单商品信息
     * 4. 返回订单列表
     *
     * @param params 包含 status（可选，订单状态：0-待支付，1-已完成，2-已取消）
     * @return 订单列表
     */
    @PostMapping("/list")
    public Result<List<Map<String, Object>>> getOrderList(@RequestBody(required = false) Map<String, Object> params) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            log.info("用户 {} 请求订单列表", userId);

            Integer status = null;
            if (params != null && params.containsKey("status")) {
                status = Integer.valueOf(params.get("status").toString());
            }

            List<Order> orders = orderService.getOrderListByUserId(userId, status);

            List<Map<String, Object>> orderList = new ArrayList<>();
            for (Order order : orders) {
                Map<String, Object> orderMap = new HashMap<>();
                orderMap.put("id", order.getId());
                orderMap.put("orderNo", order.getOrderNo());
                orderMap.put("outTradeNo", order.getOutTradeNo());
                orderMap.put("deviceId", order.getDeviceId());
                orderMap.put("totalAmount", order.getTotalAmount());
                orderMap.put("payStatus", order.getPayStatus());
                orderMap.put("status", order.getStatus());
                orderMap.put("createTime", order.getCreateTime());
                orderMap.put("payTime", order.getPayTime());
                orderMap.put("confidence", order.getConfidence());

                if (order.getItems() != null && !order.getItems().isEmpty()) {
                    try {
                        JSONArray items = JSON.parseArray(order.getItems());
                        List<Map<String, Object>> products = new ArrayList<>();
                        for (int i = 0; i < items.size(); i++) {
                            JSONObject item = items.getJSONObject(i);
                            Map<String, Object> product = new HashMap<>();
                            product.put("id", item.getString("goodsId"));
                            product.put("name", item.getString("goodsName"));
                            product.put("price", item.getDouble("price"));
                            product.put("quantity", item.getInteger("quantity"));
                            product.put("image", item.getString("image"));
                            products.add(product);
                        }
                        orderMap.put("products", products);
                    } catch (Exception e) {
                        log.warn("解析订单 {} 的商品信息失败: {}", order.getId(), e.getMessage());
                        orderMap.put("products", new ArrayList<>());
                    }
                } else {
                    orderMap.put("products", new ArrayList<>());
                }

                orderList.add(orderMap);
            }

            log.info("用户 {} 查询到 {} 条订单", userId, orderList.size());
            return Result.success("查询成功", orderList);

        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return Result.error("查询订单列表失败");
        }
    }

    /**
     * 获取订单详情
     *
     * 业务流程：
     * 1. 参数校验
     * 2. 获取当前登录用户ID
     * 3. 查询订单详情
     * 4. 验证订单归属
     * 5. 解析订单商品信息
     * 6. 返回订单详情
     *
     * @param params 包含 orderId（订单ID）或 orderNo（订单号）或 outTradeNo（商户订单号）
     * @return 订单详情
     */
    @PostMapping("/detail")
    public Result<Map<String, Object>> getOrderDetail(@RequestBody Map<String, Object> params) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            Order order = null;

            if (params.containsKey("orderId")) {
                Long orderId = Long.valueOf(params.get("orderId").toString());
                order = orderService.getById(orderId);
                log.info("用户 {} 通过订单ID {} 查询订单详情", userId, orderId);
            } else if (params.containsKey("orderNo")) {
                String orderNo = params.get("orderNo").toString();
                order = orderService.lambdaQuery()
                    .eq(Order::getOrderNo, orderNo)
                    .one();
                log.info("用户 {} 通过订单号 {} 查询订单详情", userId, orderNo);
            } else if (params.containsKey("outTradeNo")) {
                String outTradeNo = params.get("outTradeNo").toString();
                order = orderService.getOrderByOutTradeNo(outTradeNo);
                log.info("用户 {} 通过商户订单号 {} 查询订单详情", userId, outTradeNo);
            } else {
                return Result.error(400, "参数错误：必须提供 orderId、orderNo 或 outTradeNo");
            }

            if (order == null) {
                return Result.error(404, "订单不存在");
            }

            if (!order.getUserId().equals(userId)) {
                log.warn("用户 {} 尝试访问不属于自己的订单 {}", userId, order.getId());
                return Result.error(403, "无权访问该订单");
            }

            Map<String, Object> orderDetail = new HashMap<>();
            orderDetail.put("id", order.getId());
            orderDetail.put("orderNo", order.getOrderNo());
            orderDetail.put("outTradeNo", order.getOutTradeNo());
            orderDetail.put("deviceId", order.getDeviceId());
            orderDetail.put("totalAmount", order.getTotalAmount());
            orderDetail.put("payStatus", order.getPayStatus());
            orderDetail.put("status", order.getStatus());
            orderDetail.put("createTime", order.getCreateTime());
            orderDetail.put("payTime", order.getPayTime());
            orderDetail.put("confidence", order.getConfidence());

            if (order.getItems() != null && !order.getItems().isEmpty()) {
                try {
                    JSONArray items = JSON.parseArray(order.getItems());
                    List<Map<String, Object>> products = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        JSONObject item = items.getJSONObject(i);
                        Map<String, Object> product = new HashMap<>();
                        product.put("id", item.getString("goodsId"));
                        product.put("name", item.getString("goodsName"));
                        product.put("price", item.getDouble("price"));
                        product.put("quantity", item.getInteger("quantity"));
                        product.put("image", item.getString("image"));
                        product.put("subtotal", item.getDouble("price") * item.getInteger("quantity"));
                        products.add(product);
                    }
                    orderDetail.put("products", products);
                } catch (Exception e) {
                    log.warn("解析订单 {} 的商品信息失败: {}", order.getId(), e.getMessage());
                    orderDetail.put("products", new ArrayList<>());
                }
            } else {
                orderDetail.put("products", new ArrayList<>());
            }

            String statusText = getStatusText(order.getStatus());
            orderDetail.put("statusText", statusText);

            log.info("用户 {} 查询订单详情成功: {}", userId, order.getOrderNo());
            return Result.success("查询成功", orderDetail);

        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            return Result.error("查询订单详情失败");
        }
    }

    /**
     * 取消订单
     *
     * @param params 包含 orderId（订单ID）
     * @return 操作结果
     */
    @PostMapping("/cancel")
    public Result<Void> cancelOrder(@RequestBody Map<String, Object> params) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            if (!params.containsKey("orderId")) {
                return Result.error(400, "参数错误：orderId 不能为空");
            }

            Long orderId = Long.valueOf(params.get("orderId").toString());

            Order order = orderService.getById(orderId);
            if (order == null) {
                return Result.error(404, "订单不存在");
            }

            if (!order.getUserId().equals(userId)) {
                log.warn("用户 {} 尝试取消不属于自己的订单 {}", userId, orderId);
                return Result.error(403, "无权操作该订单");
            }

            if (order.getStatus() != 0) {
                return Result.error(400, "该订单不能取消");
            }

            boolean success = orderService.cancelOrder(orderId);

            if (success) {
                log.info("用户 {} 取消订单 {} 成功", userId, orderId);
                return Result.success("订单已取消", null);
            } else {
                return Result.error("取消订单失败");
            }

        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.error("取消订单失败");
        }
    }

    /**
     * 获取订单状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 0:
                return "待支付";
            case 1:
                return "已完成";
            case 2:
                return "已取消";
            default:
                return "未知";
        }
    }
}
