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());
        }
    }
}

