package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.service.IOrderService;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 订单管理控制器
 *
 * @author System
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IOrderService orderService;

    /**
     * 查询订单列表（分页+搜索）
     */
    @SaCheckPermission("order:list")
    @PostMapping("/list")
    public PageResultResponse<Order> list(@RequestBody Map<String, Object> params) {
        try {
            logger.info("查询订单列表，参数：{}", params);
            PageResultResponse<Order> result = orderService.pageQuery(params);
            logger.info("查询成功，共{}条记录", result.getData().getTotal());
            return result;
        } catch (Exception e) {
            logger.error("查询订单列表失败：{}", e.getMessage(), e);
            return new PageResultResponse<>(0, new ArrayList<>());
        }
    }

    /**
     * 新增订单
     */
    @SaCheckPermission("order:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Order order) {
        try {
            logger.info("新增订单，买方：{}，卖方：{}，结算方式：{}", order.getBuyerId(), order.getSellerId(), order.getSettlementType());
            
            // 参数验证
            if (order.getSettlementType() == null) {
                logger.error("新增失败：结算方式不能为空");
                return AjaxResult.error("结算方式不能为空");
            }

            return orderService.addOrder(order);
        } catch (Exception e) {
            logger.error("新增订单失败：{}", e.getMessage(), e);
            return AjaxResult.error("新增订单失败：" + e.getMessage());
        }
    }

    /**
     * 编辑订单
     */
    @SaCheckPermission("order:edit")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Order order) {
        try {
            logger.info("编辑订单，订单ID：{}", order.getId());
            
            // 参数验证
            if (order.getId() == null) {
                logger.error("编辑失败：订单ID不能为空");
                return AjaxResult.error("订单ID不能为空");
            }

            return orderService.updateOrder(order);
        } catch (Exception e) {
            logger.error("编辑订单失败：{}", e.getMessage(), e);
            return AjaxResult.error("编辑订单失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单（逻辑删除）
     */
    @SaCheckPermission("order:delete")
    @GetMapping("/delete")
    public AjaxResult delete(@RequestParam Integer id) {
        try {
            logger.info("删除订单，订单ID：{}", id);

            if (id == null) {
                logger.error("删除失败：订单ID不能为空");
                return AjaxResult.error("订单ID不能为空");
            }

            return orderService.deleteOrder(id);
        } catch (Exception e) {
            logger.error("删除订单失败：{}", e.getMessage(), e);
            return AjaxResult.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单详情
     */
    @SaCheckPermission("order:view")
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Integer id) {
        try {
            logger.info("查询订单详情，订单ID：{}", id);

            if (id == null) {
                logger.error("查询失败：订单ID不能为空");
                return AjaxResult.error("订单ID不能为空");
            }

            return orderService.getOrderDetail(id);
        } catch (Exception e) {
            logger.error("查询订单详情失败：{}", e.getMessage(), e);
            return AjaxResult.error("查询订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 批量导入订单
     */
    @SaCheckPermission("order:import")
    @PostMapping("/batchImport")
    public AjaxResult batchImport(@RequestBody Map<String, Object> params) {
        try {
            logger.info("批量导入订单，参数：{}", params);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> orders = (List<Map<String, Object>>) params.get("orders");
            
            if (orders == null || orders.isEmpty()) {
                logger.error("批量导入失败：订单列表不能为空");
                return AjaxResult.error("订单列表不能为空");
            }

            return orderService.batchImportOrders(orders);
        } catch (Exception e) {
            logger.error("批量导入订单失败：{}", e.getMessage(), e);
            return AjaxResult.error("批量导入订单失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新订单的delivery_id字段
     */
    @SaCheckPermission("order:edit")
    @PostMapping("/updateDeliveryId")
    public AjaxResult updateDeliveryId(@RequestBody Map<String, Object> params) {
        try {
            logger.info("批量更新订单delivery_id，参数：{}", params);

            Integer deliveryId = null;
            if (params.get("deliveryId") != null) {
                Object deliveryIdObj = params.get("deliveryId");
                if (deliveryIdObj instanceof Integer) {
                    deliveryId = (Integer) deliveryIdObj;
                } else if (deliveryIdObj instanceof String) {
                    try {
                        deliveryId = Integer.parseInt((String) deliveryIdObj);
                    } catch (NumberFormatException e) {
                        logger.error("deliveryId格式不正确：{}", deliveryIdObj);
                        return AjaxResult.error("deliveryId格式不正确");
                    }
                }
            }

            // 处理orderIds参数：支持整数数组和字符串数组
            List<Integer> orderIds = new ArrayList<>();
            Object orderIdsObj = params.get("orderIds");
            if (orderIdsObj != null) {
                if (orderIdsObj instanceof List) {
                    @SuppressWarnings("unchecked")
                    List<Object> orderIdsList = (List<Object>) orderIdsObj;
                    for (Object item : orderIdsList) {
                        if (item instanceof Integer) {
                            orderIds.add((Integer) item);
                        } else if (item instanceof String) {
                            try {
                                orderIds.add(Integer.parseInt((String) item));
                            } catch (NumberFormatException e) {
                                logger.error("订单ID格式不正确：{}", item);
                                return AjaxResult.error("订单ID格式不正确：" + item);
                            }
                        } else if (item instanceof Number) {
                            orderIds.add(((Number) item).intValue());
                        } else {
                            logger.error("订单ID类型不支持：{}", item.getClass().getName());
                            return AjaxResult.error("订单ID类型不支持");
                        }
                    }
                } else if (orderIdsObj instanceof String) {
                    // 如果是逗号分隔的字符串，按逗号分割
                    String orderIdsStr = (String) orderIdsObj;
                    String[] ids = orderIdsStr.split(",");
                    for (String id : ids) {
                        try {
                            orderIds.add(Integer.parseInt(id.trim()));
                        } catch (NumberFormatException e) {
                            logger.error("订单ID格式不正确：{}", id);
                            return AjaxResult.error("订单ID格式不正确：" + id);
                        }
                    }
                } else {
                    logger.error("orderIds参数类型不正确：{}", orderIdsObj.getClass().getName());
                    return AjaxResult.error("orderIds参数类型不正确");
                }
            }
            
            if (deliveryId == null) {
                logger.error("更新失败：运送清单ID不能为空");
                return AjaxResult.error("运送清单ID不能为空");
            }

            if (orderIds == null || orderIds.isEmpty()) {
                logger.warn("订单ID列表为空，跳过更新");
                return AjaxResult.success("订单ID列表为空，无需更新");
            }

            return orderService.updateOrderDeliveryId(deliveryId, orderIds);
        } catch (Exception e) {
            logger.error("批量更新订单delivery_id失败：{}", e.getMessage(), e);
            return AjaxResult.error("批量更新订单delivery_id失败：" + e.getMessage());
        }
    }

    /**
     * 解除订单与运送清单的关联
     */
    @SaCheckPermission("order:edit")
    @PostMapping("/unbindFromDelivery")
    public AjaxResult unbindFromDelivery(@RequestBody Map<String, Object> params) {
        try {
            logger.info("解除订单与运送清单关联，参数：{}", params);

            Integer orderId = null;
            if (params.get("orderId") != null) {
                Object orderIdObj = params.get("orderId");
                if (orderIdObj instanceof Integer) {
                    orderId = (Integer) orderIdObj;
                } else if (orderIdObj instanceof String) {
                    try {
                        orderId = Integer.parseInt((String) orderIdObj);
                    } catch (NumberFormatException e) {
                        logger.error("orderId格式不正确：{}", orderIdObj);
                        return AjaxResult.error("orderId格式不正确");
                    }
                }
            }

            if (orderId == null) {
                logger.error("解除关联失败：订单ID不能为空");
                return AjaxResult.error("订单ID不能为空");
            }

            return orderService.unbindOrderFromDelivery(orderId);
        } catch (Exception e) {
            logger.error("解除订单与运送清单关联失败：{}", e.getMessage(), e);
            return AjaxResult.error("解除关联失败：" + e.getMessage());
        }
    }
}

