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

import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.Member;
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.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);

        // 使用PageHelper进行分页
        Page<Order> page = PageHelper.startPage(pageNum, pageSize);

        // 构建查询条件
        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);

        // 执行查询
        List<Order> list = orderMapper.selectList(queryWrapper);

        // 填充关联信息
        list.forEach(this::fillOrderInfo);

        // 如果提供了买方或卖方名称搜索，进行过滤
        List<Order> filteredList = list;
        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());
        }

        // 构建分页结果
        logger.info("查询到{}条订单记录，过滤后{}条", list.size(), filteredList.size());
        return new PageResultResponse<>(filteredList.size(), filteredList);
    }

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

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

            // 设置创建人和创建时间
            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());

        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("结算方式无效");
            }

            // 设置更新人和更新时间
            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 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;
            }
        }
    }
}

