package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.SysUser;
import com.aiotagro.cattletrade.business.mapper.OrderMapper;
import com.aiotagro.cattletrade.business.mapper.MemberMapper;
import com.aiotagro.cattletrade.business.mapper.SysUserMapper;
import com.aiotagro.cattletrade.business.service.IOrderService;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单管理服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

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

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 分页查询订单列表
     */
    @Override
    public PageResultResponse<Order> pageQuery(Map<String, Object> params) {
        Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;
        Integer settlementType = params.get("settlementType") != null ? (Integer) params.get("settlementType") : null;
        String buyerName = params.get("buyerName") != null ? (String) params.get("buyerName") : null;
        String sellerName = params.get("sellerName") != null ? (String) params.get("sellerName") : null;
        String startTime = params.get("startTime") != null ? (String) params.get("startTime") : null;
        String endTime = params.get("endTime") != null ? (String) params.get("endTime") : null;

        logger.info("分页查询订单列表，页码：{}，每页数量：{}，买方：{}，卖方：{}，结算方式：{}", 
                    pageNum, pageSize, buyerName, sellerName, settlementType);

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(settlementType != null, Order::getSettlementType, settlementType);
        
        // 时间范围查询
        if (startTime != null && !startTime.isEmpty()) {
            // 如果没有时间部分，添加00:00:00
            String startTimeStr = startTime;
            if (startTimeStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
                startTimeStr = startTimeStr + " 00:00:00";
            }
            queryWrapper.ge(Order::getCreateTime, startTimeStr);
        }
        if (endTime != null && !endTime.isEmpty()) {
            // 如果没有时间部分，添加23:59:59
            String endTimeStr = endTime;
            if (endTimeStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
                endTimeStr = endTimeStr + " 23:59:59";
            }
            queryWrapper.le(Order::getCreateTime, endTimeStr);
        }
        
        queryWrapper.orderByDesc(Order::getCreateTime);

        // 判断是否需要先过滤再分页（如果提供了买方或卖方名称搜索）
        boolean needFilter = (buyerName != null && !buyerName.trim().isEmpty()) || 
                            (sellerName != null && !sellerName.trim().isEmpty());
        
        List<Order> filteredList;
        long total;
        
        if (needFilter) {
            // 需要过滤的情况：先查询所有数据，填充信息，过滤，然后手动分页
            List<Order> allList = orderMapper.selectList(queryWrapper);
            
            // 批量填充关联信息（优化性能）
            fillOrderInfoBatch(allList);
            
            // 进行过滤
            filteredList = allList;
            if (buyerName != null && !buyerName.trim().isEmpty()) {
                filteredList = filteredList.stream()
                    .filter(order -> order.getBuyerName() != null && order.getBuyerName().contains(buyerName.trim()))
                    .collect(java.util.stream.Collectors.toList());
            }
            if (sellerName != null && !sellerName.trim().isEmpty()) {
                filteredList = filteredList.stream()
                    .filter(order -> order.getSellerName() != null && order.getSellerName().contains(sellerName.trim()))
                    .collect(java.util.stream.Collectors.toList());
            }
            
            // 获取总数
            total = filteredList.size();
            
            // 手动分页
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, filteredList.size());
            if (startIndex < filteredList.size()) {
                filteredList = filteredList.subList(startIndex, endIndex);
            } else {
                filteredList = new ArrayList<>();
            }
            
            logger.info("查询到{}条订单记录，过滤后{}条，分页后{}条", allList.size(), total, filteredList.size());
        } else {
            // 不需要过滤的情况：直接使用PageHelper分页
            Page<Order> page = PageHelper.startPage(pageNum, pageSize);
            
            // 执行查询
            List<Order> list = orderMapper.selectList(queryWrapper);
            
            // 批量填充关联信息（优化性能）
            fillOrderInfoBatch(list);
            
            // 获取总数和分页数据
            total = page.getTotal();
            filteredList = list;
            
            logger.info("查询到{}条订单记录，分页后{}条", total, filteredList.size());
        }

        // 构建分页结果
        return new PageResultResponse<>(total, filteredList);
    }

    /**
     * 新增订单
     */
    @Override
    @Transactional
    public AjaxResult addOrder(Order order) {
        logger.info("开始新增订单，买方：{}，卖方：{}，结算方式：{}，约定价格：{}", 
            order.getBuyerId(), order.getSellerId(), order.getSettlementType(), order.getFirmPrice());

        try {
            // 验证结算方式
            if (order.getSettlementType() == null || order.getSettlementType() < 1 || order.getSettlementType() > 3) {
                logger.error("结算方式无效：{}", order.getSettlementType());
                return AjaxResult.error("结算方式无效");
            }

            // 验证约定价格（firm_price 字段是 NOT NULL）
            if (order.getFirmPrice() == null) {
                logger.error("约定价格不能为空");
                return AjaxResult.error("约定价格不能为空");
            }
            // 确保约定价格不为负数
            if (order.getFirmPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                logger.error("约定价格不能小于0：{}", order.getFirmPrice());
                return AjaxResult.error("约定价格不能小于0");
            }

            // 设置创建人和创建时间
            Integer userId = SecurityUtil.getCurrentUserId();
            order.setCreatedBy(userId);
            order.setCreateTime(new Date());

            // 插入数据库
            int result = orderMapper.insert(order);

            if (result > 0) {
                logger.info("新增订单成功，订单ID：{}", order.getId());
                return AjaxResult.success("新增订单成功");
            } else {
                logger.error("新增订单失败");
                return AjaxResult.error("新增订单失败");
            }
        } catch (Exception e) {
            logger.error("新增订单异常：{}", e.getMessage(), e);
            return AjaxResult.error("新增订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单信息
     */
    @Override
    @Transactional
    public AjaxResult updateOrder(Order order) {
        if (order.getId() == null) {
            logger.error("订单ID不能为空");
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("开始更新订单，订单ID：{}，约定价格：{}", order.getId(), order.getFirmPrice());

        try {
            // 验证订单是否存在
            Order existingOrder = orderMapper.selectById(order.getId());
            if (existingOrder == null) {
                logger.error("订单不存在，ID：{}", order.getId());
                return AjaxResult.error("订单不存在");
            }

            // 验证结算方式
            if (order.getSettlementType() != null && (order.getSettlementType() < 1 || order.getSettlementType() > 3)) {
                logger.error("结算方式无效：{}", order.getSettlementType());
                return AjaxResult.error("结算方式无效");
            }

            // 验证约定价格（如果提供了）
            if (order.getFirmPrice() != null) {
                // 确保约定价格不为负数
                if (order.getFirmPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                    logger.error("约定价格不能小于0：{}", order.getFirmPrice());
                    return AjaxResult.error("约定价格不能小于0");
                }
            } else {
                // 如果更新时没有提供 firm_price，保留原有值（因为字段是 NOT NULL）
                order.setFirmPrice(existingOrder.getFirmPrice());
            }

            // 设置更新人和更新时间
            try {
                Integer userId = SecurityUtil.getCurrentUserId();
                order.setUpdatedBy(userId);
            } catch (Exception e) {
                logger.warn("获取当前用户失败，使用订单原有创建人：{}", e.getMessage());
                // 如果无法获取当前用户，使用原订单的 created_by
                if (existingOrder.getCreatedBy() != null) {
                    order.setUpdatedBy(existingOrder.getCreatedBy());
                }
            }
            order.setUpdateTime(new Date());

            // 更新数据库
            int result = orderMapper.updateById(order);

            if (result > 0) {
                logger.info("更新订单成功，订单ID：{}", order.getId());
                return AjaxResult.success("更新订单成功");
            } else {
                logger.error("更新订单失败");
                return AjaxResult.error("更新订单失败");
            }
        } catch (Exception e) {
            logger.error("更新订单异常：{}", e.getMessage(), e);
            return AjaxResult.error("更新订单失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单（逻辑删除）
     */
    @Override
    @Transactional
    public AjaxResult deleteOrder(Integer id) {
        if (id == null) {
            logger.error("订单ID不能为空");
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("开始删除订单，订单ID：{}", id);

        try {
            // 查询订单是否存在
            Order order = orderMapper.selectById(id);
            if (order == null) {
                logger.error("订单不存在，ID：{}", id);
                return AjaxResult.error("订单不存在");
            }

            // 逻辑删除（通过update方法设置is_delete=1）
            // MyBatis-Plus的@TableLogic会自动处理
            int result = orderMapper.deleteById(id);

            if (result > 0) {
                logger.info("删除订单成功，订单ID：{}", id);
                return AjaxResult.success("删除订单成功");
            } else {
                logger.error("删除订单失败");
                return AjaxResult.error("删除订单失败");
            }
        } catch (Exception e) {
            logger.error("删除订单异常：{}", e.getMessage(), e);
            return AjaxResult.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单详情
     */
    @Override
    public AjaxResult getOrderDetail(Integer id) {
        if (id == null) {
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("查询订单详情，订单ID：{}", id);

        Order order = orderMapper.selectById(id);
        if (order == null) {
            logger.error("订单不存在，ID：{}", id);
            return AjaxResult.error("订单不存在");
        }

        // 填充关联信息
        fillOrderInfo(order);

        return AjaxResult.success(order);
    }

    /**
     * 批量填充订单关联信息（优化性能，减少数据库查询次数）
     */
    private void fillOrderInfoBatch(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            return;
        }

        // 收集所有需要查询的ID
        java.util.Set<Integer> buyerIds = new java.util.HashSet<>();
        java.util.Set<Integer> sellerIds = new java.util.HashSet<>();
        java.util.Set<Integer> creatorIds = new java.util.HashSet<>();

        for (Order order : orders) {
            // 收集买方ID
            if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
                Arrays.stream(order.getBuyerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .forEach(id -> {
                        try {
                            buyerIds.add(Integer.parseInt(id));
                        } catch (NumberFormatException e) {
                            logger.warn("无效的买方ID：{}", id);
                        }
                    });
            }
            // 收集卖方ID
            if (order.getSellerId() != null && !order.getSellerId().isEmpty()) {
                Arrays.stream(order.getSellerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .forEach(id -> {
                        try {
                            sellerIds.add(Integer.parseInt(id));
                        } catch (NumberFormatException e) {
                            logger.warn("无效的卖方ID：{}", id);
                        }
                    });
            }
            // 收集创建人ID
            if (order.getCreatedBy() != null) {
                creatorIds.add(order.getCreatedBy());
            }
        }

        // 批量查询买方信息
        java.util.Map<Integer, String> buyerNameMap = new java.util.HashMap<>();
        if (!buyerIds.isEmpty()) {
            List<Map<String, Object>> buyerList = memberMapper.selectMemberUserByIds(new ArrayList<>(buyerIds));
            for (Map<String, Object> buyer : buyerList) {
                Object idObj = buyer.get("id");
                Integer id = null;
                if (idObj != null) {
                    if (idObj instanceof Integer) {
                        id = (Integer) idObj;
                    } else if (idObj instanceof Long) {
                        id = ((Long) idObj).intValue();
                    } else if (idObj instanceof Number) {
                        id = ((Number) idObj).intValue();
                    }
                }
                String username = (String) buyer.get("username");
                if (id != null && username != null) {
                    buyerNameMap.put(id, username);
                }
            }
        }

        // 批量查询卖方信息
        java.util.Map<Integer, String> sellerNameMap = new java.util.HashMap<>();
        if (!sellerIds.isEmpty()) {
            List<Map<String, Object>> sellerList = memberMapper.selectMemberUserByIds(new ArrayList<>(sellerIds));
            for (Map<String, Object> seller : sellerList) {
                Object idObj = seller.get("id");
                Integer id = null;
                if (idObj != null) {
                    if (idObj instanceof Integer) {
                        id = (Integer) idObj;
                    } else if (idObj instanceof Long) {
                        id = ((Long) idObj).intValue();
                    } else if (idObj instanceof Number) {
                        id = ((Number) idObj).intValue();
                    }
                }
                String username = (String) seller.get("username");
                if (id != null && username != null) {
                    sellerNameMap.put(id, username);
                }
            }
        }

        // 批量查询创建人信息
        java.util.Map<Integer, String> creatorNameMap = new java.util.HashMap<>();
        if (!creatorIds.isEmpty()) {
            List<SysUser> creatorList = sysUserMapper.selectBatchIds(creatorIds);
            for (SysUser user : creatorList) {
                if (user != null && user.getId() != null && user.getName() != null) {
                    creatorNameMap.put(user.getId(), user.getName());
                }
            }
        }

        // 批量填充订单信息
        for (Order order : orders) {
            // 填充买方名称
            if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
                String buyerNames = Arrays.stream(order.getBuyerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(id -> {
                        try {
                            Integer buyerId = Integer.parseInt(id);
                            return buyerNameMap.getOrDefault(buyerId, "");
                        } catch (NumberFormatException e) {
                            return "";
                        }
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
                order.setBuyerName(buyerNames);
            }

            // 填充卖方名称
            if (order.getSellerId() != null && !order.getSellerId().isEmpty()) {
                String sellerNames = Arrays.stream(order.getSellerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(id -> {
                        try {
                            Integer sellerId = Integer.parseInt(id);
                            return sellerNameMap.getOrDefault(sellerId, "");
                        } catch (NumberFormatException e) {
                            return "";
                        }
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
                order.setSellerName(sellerNames);
            }

            // 填充创建人名称
            if (order.getCreatedBy() != null) {
                String creatorName = creatorNameMap.get(order.getCreatedBy());
                if (creatorName != null) {
                    order.setCreatedByName(creatorName);
                }
            }

            // 填充结算方式描述
            if (order.getSettlementType() != null) {
                switch (order.getSettlementType()) {
                    case 1:
                        order.setSettlementTypeDesc("上车重量");
                        break;
                    case 2:
                        order.setSettlementTypeDesc("下车重量");
                        break;
                    case 3:
                        order.setSettlementTypeDesc("按肉价结算");
                        break;
                    default:
                        order.setSettlementTypeDesc("未知");
                        break;
                }
            }
        }
    }

    /**
     * 填充订单关联信息（买方名称、卖方名称、创建人名称、结算方式描述）
     * 用于单个订单详情查询
     */
    private void fillOrderInfo(Order order) {
        // 填充买方名称
        if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
            String buyerNames = Arrays.stream(order.getBuyerId().split(","))
                    .map(buyerId -> {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(buyerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                return (String) memberUser.get("username");
                            }
                        } catch (Exception e) {
                            logger.warn("查询买方信息失败，买方ID：{}", buyerId);
                        }
                        return "";
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
            order.setBuyerName(buyerNames);
        }

        // 填充卖方名称
        if (order.getSellerId() != null && !order.getSellerId().isEmpty()) {
            String sellerNames = Arrays.stream(order.getSellerId().split(","))
                    .map(sellerId -> {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(sellerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                return (String) memberUser.get("username");
                            }
                        } catch (Exception e) {
                            logger.warn("查询卖方信息失败，卖方ID：{}", sellerId);
                        }
                        return "";
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
            order.setSellerName(sellerNames);
        }

        // 填充创建人名称
        if (order.getCreatedBy() != null) {
            SysUser user = sysUserMapper.selectById(order.getCreatedBy());
            if (user != null) {
                order.setCreatedByName(user.getName());
            }
        }

        // 填充结算方式描述
        if (order.getSettlementType() != null) {
            switch (order.getSettlementType()) {
                case 1:
                    order.setSettlementTypeDesc("上车重量");
                    break;
                case 2:
                    order.setSettlementTypeDesc("下车重量");
                    break;
                case 3:
                    order.setSettlementTypeDesc("按肉价结算");
                    break;
                default:
                    order.setSettlementTypeDesc("未知");
                    break;
            }
        }
    }

    /**
     * 批量导入订单
     */
    @Override
    @Transactional
    public AjaxResult batchImportOrders(List<Map<String, Object>> orders) {
        logger.info("开始批量导入订单，共{}条", orders.size());

        int successCount = 0;
        int failCount = 0;
        List<String> failMessages = new ArrayList<>();

        for (int i = 0; i < orders.size(); i++) {
            Map<String, Object> orderMap = orders.get(i);
            try {
                // 构建Order对象
                Order order = new Order();
                
                // 设置买方ID
                Object buyerIdObj = orderMap.get("buyerId");
                if (buyerIdObj != null) {
                    order.setBuyerId(String.valueOf(buyerIdObj));
                } else {
                    throw new RuntimeException("买方ID不能为空");
                }

                // 设置卖方ID
                Object sellerIdObj = orderMap.get("sellerId");
                if (sellerIdObj != null) {
                    order.setSellerId(String.valueOf(sellerIdObj));
                } else {
                    throw new RuntimeException("卖方ID不能为空");
                }

                // 设置结算方式（默认为1-上车重量）
                Object settlementTypeObj = orderMap.get("settlementType");
                if (settlementTypeObj != null) {
                    Integer settlementType = null;
                    if (settlementTypeObj instanceof Integer) {
                        settlementType = (Integer) settlementTypeObj;
                    } else if (settlementTypeObj instanceof Number) {
                        settlementType = ((Number) settlementTypeObj).intValue();
                    } else {
                        settlementType = Integer.parseInt(String.valueOf(settlementTypeObj));
                    }
                    if (settlementType < 1 || settlementType > 3) {
                        throw new RuntimeException("结算方式无效，必须为1-3");
                    }
                    order.setSettlementType(settlementType);
                } else {
                    order.setSettlementType(1); // 默认上车重量
                }

                // 设置约定价格
                Object firmPriceObj = orderMap.get("firmPrice");
                if (firmPriceObj != null) {
                    java.math.BigDecimal firmPrice = null;
                    if (firmPriceObj instanceof java.math.BigDecimal) {
                        firmPrice = (java.math.BigDecimal) firmPriceObj;
                    } else if (firmPriceObj instanceof Number) {
                        firmPrice = new java.math.BigDecimal(String.valueOf(firmPriceObj));
                    } else {
                        firmPrice = new java.math.BigDecimal(String.valueOf(firmPriceObj));
                    }
                    if (firmPrice.compareTo(java.math.BigDecimal.ZERO) < 0) {
                        throw new RuntimeException("约定价格不能小于0");
                    }
                    order.setFirmPrice(firmPrice);
                } else {
                    throw new RuntimeException("约定价格不能为空");
                }

                // 设置创建人和创建时间
                Integer userId = SecurityUtil.getCurrentUserId();
                order.setCreatedBy(userId);
                order.setCreateTime(new Date());

                // 插入数据库
                int result = orderMapper.insert(order);
                if (result > 0) {
                    successCount++;
                    logger.info("第{}条订单导入成功，订单ID：{}", i + 1, order.getId());
                } else {
                    failCount++;
                    failMessages.add(String.format("第%d条：插入数据库失败", i + 1));
                    logger.error("第{}条订单导入失败：插入数据库失败", i + 1);
                }
            } catch (Exception e) {
                failCount++;
                String errorMsg = String.format("第%d条：%s", i + 1, e.getMessage());
                failMessages.add(errorMsg);
                logger.error("第{}条订单导入失败：{}", i + 1, e.getMessage(), e);
            }
        }

        logger.info("批量导入完成：成功{}条，失败{}条", successCount, failCount);

        // 构建返回结果
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("failMessages", failMessages);

        if (failCount == 0) {
            return AjaxResult.success("批量导入成功，共导入" + successCount + "条订单", result);
        } else {
            return AjaxResult.success("批量导入完成：成功" + successCount + "条，失败" + failCount + "条", result);
        }
    }
}

