package com.cxyxiaomo.epp.shop.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cxyxiaomo.epp.common.enums.OrderStatus;
import com.cxyxiaomo.epp.common.pojo.Order;
import com.cxyxiaomo.epp.common.pojo.OrderDetail;
import com.cxyxiaomo.epp.common.response.Res;
import com.cxyxiaomo.epp.common.vo.GoodVO;
import com.cxyxiaomo.epp.common.vo.OrderDetailVO;
import com.cxyxiaomo.epp.common.vo.OrderVO;
import com.cxyxiaomo.epp.shop.service.GoodsService;
import com.cxyxiaomo.epp.shop.service.OrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/shop/order")
public class OrderController {

    @Resource
    OrderService orderService;

    @Resource
    GoodsService goodsService;

    /**
     * 小程序端创建订单
     *
     * @param userId    下单用户
     * @param orderList 下单商品 [ { goodId, count }, ... ]
     * @return
     */
    @PostMapping("/miniprogram/createOrder")
    @ResponseBody
    public Res createOrder(@RequestBody JSONObject params) {
        Integer userId = params.getInteger("userId");
        JSONArray orderList = params.getJSONArray("orderList");
        if (userId == null || orderList == null) {
            return Res.error("参数错误");
        }

        LinkedList<OrderDetail> orderDetailList = new LinkedList<>();
        for (Object o : orderList) {
            if (o == null || o instanceof JSONObject) {
                return Res.error("参数错误");
            }
            JSONObject order = new JSONObject((Map) o);
            Long goodId = order.getLong("goodId");
            Integer count = order.getInteger("count");
            if (goodId == null || goodId < 1 || count == null || count < 1) {
                return Res.error("参数错误");
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setGoodId(goodId);
            orderDetail.setGoodCount(count);
            orderDetailList.add(orderDetail);
        }

        if (orderDetailList.size() == 0) {
            return Res.error("订单中不包含商品，不能创建空订单");
        }

        try {
            long orderId = orderService.createOrder(userId, orderDetailList);
            return Res.success(String.valueOf(orderId)); // 转为 String 避免前端丢失精度
        } catch (Exception e) {
            String message = e.getMessage();
            if (message.contains("Exception")) {
                // 内部异常不打印出去
                return Res.error("创建订单失败，请重试");
            } else {
                return Res.error(message);
            }
        }
    }

    /**
     * 获取指定订单的详情
     *
     * @param orderId
     * @return
     */
    @GetMapping("/miniprogram/orderDetail")
    @ResponseBody
    public Res orderDetail(@RequestParam Long orderId) {
        if (orderId == null) {
            return Res.error("订单不存在");
        }

        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return Res.error("订单不存在");
            }
            List<OrderDetailVO> orderDetailVOList = orderService.getOrderDetailById(orderId);

            List<Long> goodIdList = orderDetailVOList.stream().map(orderDetailVO -> {
                String goodId = orderDetailVO.getGoodId();
                return Long.parseLong(goodId);
            }).collect(Collectors.toList());

            List<GoodVO> goodVOList = goodsService.listByIds(goodIdList);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("order", OrderVO.convertFrom(order));
            resultMap.put("orderItem", orderDetailVOList);
            resultMap.put("goods", goodVOList);
            return Res.success(resultMap);
        } catch (Exception e) {
            String message = e.getMessage();
            if (message.contains("Exception")) {
                // 内部异常不打印出去
                return Res.error("查询订单失败，请重试");
            } else {
                return Res.error(message);
            }
        }
    }

    /**
     * 获取用户的订单列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/miniprogram/listUserOrder")
    @ResponseBody
    public Res listUserOrder(@RequestParam Integer userId,
                             @RequestParam(value = "filter", required = false) String orderStatusFilter) {
        if (userId == null) {
            return Res.error("参数错误");
        }
        List<Order> orders = orderService.listUserOrder(userId, orderStatusFilter);
        List<OrderVO> orderVOS = OrderVO.convertFrom(orders);

        HashMap<String, Object> map = new HashMap<>();


        JSONObject filter = new JSONObject();
        Arrays.stream(OrderStatus.values())
                .forEach(orderStatus -> filter.put(orderStatus.getValue(), orderStatus.toString()));
        // List<String> filter = Arrays.stream(OrderStatus.values())
        //         .map(OrderStatus::toString).collect(Collectors.toList());

        map.put("filter", filter);
        map.put("orders", orderVOS);
        return Res.success(map);
    }

    @PostMapping("/miniprogram/payOrder")
    @ResponseBody
    public Res payOrder(@RequestBody JSONObject params) {
        Long orderId = params.getLong("orderId");
        if (orderId == null) {
            return Res.error("参数错误");
        }

        // 查询订单详情
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return Res.error("订单不存在");
        }

        //判断是否可以支付
        OrderStatus orderStatus = OrderStatus.get(order.getOrderStatus());
        switch (orderStatus) {
            case PENDING:
                // 可以支付
                break;
            case PROCESSING:
                return Res.error("订单已支付，无需重复支付");
            case CANCELLED:
                return Res.error("订单已取消，无法支付");
            default:
                return Res.error("当前订单状态无法支付");
        }

        // 更新支付信息
        Boolean success = orderService.updateOrderStatus(orderId, OrderStatus.PROCESSING);

        return Res.success(success ? "支付成功" : "支付失败");
    }

    @PostMapping("/miniprogram/cancelOrder")
    @ResponseBody
    public Res cancelOrder(@RequestBody JSONObject params) {
        Long orderId = params.getLong("orderId");
        if (orderId == null) {
            return Res.error("参数错误");
        }

        // 查询订单详情
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return Res.error("订单不存在");
        }

        //判断是否可以取消
        OrderStatus orderStatus = OrderStatus.get(order.getOrderStatus());
        switch (orderStatus) {
            case PENDING:
                // 可以取消
                break;
            case PROCESSING:
                // 可以取消
                // return Res.error("订单已支付，不可取消");
                break;
            case SHIPPED:
                return Res.error("订单已发货，不可取消");
            case DELIVERED:
                return Res.error("订单已送达，不可取消");
            case CANCELLED:
                return Res.error("订单已取消");
            default:
                return Res.error("当前订单状态无法取消");
        }

        // 更新支付信息
        Boolean success = orderService.updateOrderStatus(orderId, OrderStatus.CANCELLED);

        return Res.success(success ? "取消成功" : "取消失败");
    }
}
