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

import com.aiotagro.cattletrade.business.dto.SlaughterEntryCreateDto;
import com.aiotagro.cattletrade.business.dto.SlaughterEntryDto;
import com.aiotagro.cattletrade.business.dto.SlaughterEntryEditDto;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.SlaughterEntry;
import com.aiotagro.cattletrade.business.entity.SlaughterHouse;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.MemberMapper;
import com.aiotagro.cattletrade.business.mapper.OrderMapper;
import com.aiotagro.cattletrade.business.mapper.SlaughterEntryMapper;
import com.aiotagro.cattletrade.business.mapper.SlaughterHouseMapper;
import com.aiotagro.cattletrade.business.service.ISlaughterEntryService;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.utils.bean.BeanUtils;
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.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
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-12-09
 */
@Service
public class SlaughterEntryServiceImpl extends ServiceImpl<SlaughterEntryMapper, SlaughterEntry> implements ISlaughterEntryService {

    @Autowired
    private SlaughterEntryMapper slaughterEntryMapper;
    @Autowired
    private SlaughterHouseMapper slaughterHouseMapper;
    @Autowired
    private DeliveryMapper deliveryMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public PageResultResponse<SlaughterEntry> pageQuery(SlaughterEntryDto dto) {
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;

        Page<SlaughterEntry> page = PageHelper.startPage(pageNum, pageSize);

        LambdaQueryWrapper<SlaughterEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(q -> q.eq(SlaughterEntry::getIsDelete, 0).or().isNull(SlaughterEntry::getIsDelete));

        if (dto.getSlaughterHouseId() != null) {
            wrapper.eq(SlaughterEntry::getSlaughterHouseId, dto.getSlaughterHouseId());
        }
        if (dto.getDeliveryId() != null) {
            wrapper.eq(SlaughterEntry::getDeliveryId, dto.getDeliveryId());
        }
        if (dto.getOrderId() != null) {
            wrapper.eq(SlaughterEntry::getOrderId, dto.getOrderId());
        }
        
        // 运送清单号模糊查询
        if (StringUtils.hasText(dto.getDeliveryNumber())) {
            // 先查询符合条件的运送清单ID
            LambdaQueryWrapper<Delivery> deliveryWrapper = new LambdaQueryWrapper<>();
            deliveryWrapper.like(Delivery::getDeliveryNumber, dto.getDeliveryNumber());
            List<Delivery> deliveries = deliveryMapper.selectList(deliveryWrapper);
            if (deliveries != null && !deliveries.isEmpty()) {
                List<Integer> deliveryIds = deliveries.stream()
                        .map(Delivery::getId)
                        .collect(java.util.stream.Collectors.toList());
                wrapper.in(SlaughterEntry::getDeliveryId, deliveryIds);
            } else {
                // 如果没有匹配的运送清单，返回空结果
                wrapper.eq(SlaughterEntry::getId, -1);
            }
        }
        
        // 订单关键词查询（买方或卖方公司名称）
        if (StringUtils.hasText(dto.getOrderKeyword())) {
            // 先查询符合条件的订单ID
            // 需要关联查询 Order 表和 Member 表
            // 由于需要查询 Member 表的用户名，这里先查询所有订单，然后在内存中过滤
            List<Order> allOrders = orderMapper.selectList(null);
            List<Integer> matchedOrderIds = new java.util.ArrayList<>();
            String keyword = dto.getOrderKeyword().trim();
            
            for (Order order : allOrders) {
                boolean matched = false;
                // 检查买方
                if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
                    String[] buyerIds = order.getBuyerId().split(",");
                    for (String buyerId : buyerIds) {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(buyerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                String username = (String) memberUser.get("username");
                                if (username != null && username.contains(keyword)) {
                                    matched = true;
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            // 忽略错误
                        }
                    }
                }
                // 检查卖方
                if (!matched && order.getSellerId() != null && !order.getSellerId().isEmpty()) {
                    String[] sellerIds = order.getSellerId().split(",");
                    for (String sellerId : sellerIds) {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(sellerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                String username = (String) memberUser.get("username");
                                if (username != null && username.contains(keyword)) {
                                    matched = true;
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            // 忽略错误
                        }
                    }
                }
                if (matched) {
                    matchedOrderIds.add(order.getId());
                }
            }
            
            if (!matchedOrderIds.isEmpty()) {
                wrapper.in(SlaughterEntry::getOrderId, matchedOrderIds);
            } else {
                // 如果没有匹配的订单，返回空结果
                wrapper.eq(SlaughterEntry::getId, -1);
            }
        }

        wrapper.orderByDesc(SlaughterEntry::getCreateTime);

        List<SlaughterEntry> list = slaughterEntryMapper.selectList(wrapper);
        
        // 填充关联信息：运送清单号和订单买卖双方
        fillRelatedInfo(list);
        
        return new PageResultResponse<>(page.getTotal(), list);
    }
    
    /**
     * 填充关联信息：运送清单号和订单买卖双方
     */
    private void fillRelatedInfo(List<SlaughterEntry> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        
        for (SlaughterEntry entry : list) {
            // 填充运送清单号
            if (entry.getDeliveryId() != null) {
                Delivery delivery = deliveryMapper.selectById(entry.getDeliveryId());
                if (delivery != null) {
                    entry.setDeliveryNumber(delivery.getDeliveryNumber());
                }
            }
            
            // 填充订单买卖双方信息
            if (entry.getOrderId() != null) {
                Order order = orderMapper.selectById(entry.getOrderId());
                if (order != null) {
                    // 填充买方名称
                    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) {
                                        // 忽略错误
                                    }
                                    return "";
                                })
                                .filter(name -> !name.isEmpty())
                                .collect(Collectors.joining(", "));
                        entry.setOrderBuyerName(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) {
                                        // 忽略错误
                                    }
                                    return "";
                                })
                                .filter(name -> !name.isEmpty())
                                .collect(Collectors.joining(", "));
                        entry.setOrderSellerName(sellerNames);
                    }
                }
            }
        }
    }

    @Override
    @Transactional
    public AjaxResult addEntry(SlaughterEntryCreateDto dto) {
        AjaxResult validateResult = validateRelation(dto.getSlaughterHouseId(), dto.getDeliveryId(), dto.getOrderId());
        if (validateResult != null) {
            return validateResult;
        }

        SlaughterEntry entry = new SlaughterEntry();
        BeanUtils.copyProperties(dto, entry);

        // 如果编码为空，自动生成
        if (!StringUtils.hasText(entry.getEntryCode())) {
            entry.setEntryCode(generateEntryCode());
        }

        Integer userId = SecurityUtil.getCurrentUserId();
        entry.setCreatedBy(userId);
        entry.setCreateTime(new Date());

        int inserted = slaughterEntryMapper.insert(entry);
        return inserted > 0 ? AjaxResult.success("新增进场记录成功") : AjaxResult.error("新增进场记录失败");
    }

    @Override
    @Transactional
    public AjaxResult updateEntry(SlaughterEntryEditDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry existing = slaughterEntryMapper.selectById(dto.getId());
        if (existing == null || (existing.getIsDelete() != null && existing.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }

        AjaxResult validateResult = validateRelation(dto.getSlaughterHouseId(), dto.getDeliveryId(), dto.getOrderId());
        if (validateResult != null) {
            return validateResult;
        }

        SlaughterEntry entry = new SlaughterEntry();
        BeanUtils.copyProperties(dto, entry);

        Integer userId = SecurityUtil.getCurrentUserId();
        entry.setUpdatedBy(userId);
        entry.setUpdateTime(new Date());

        int updated = slaughterEntryMapper.updateById(entry);
        return updated > 0 ? AjaxResult.success("更新进场记录成功") : AjaxResult.error("更新进场记录失败");
    }

    @Override
    @Transactional
    public AjaxResult deleteEntry(Integer id) {
        if (id == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry entry = slaughterEntryMapper.selectById(id);
        if (entry == null || (entry.getIsDelete() != null && entry.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }

        Integer userId = SecurityUtil.getCurrentUserId();
        UpdateWrapper<SlaughterEntry> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id).eq("is_delete", 0)
                .set("is_delete", 1)
                .set("updated_by", userId)
                .set("update_time", new Date());

        int result = slaughterEntryMapper.update(null, wrapper);
        return result > 0 ? AjaxResult.success("删除进场记录成功") : AjaxResult.error("删除进场记录失败");
    }

    @Override
    public AjaxResult detail(Integer id) {
        if (id == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry entry = slaughterEntryMapper.selectById(id);
        if (entry == null || (entry.getIsDelete() != null && entry.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }
        
        // 填充关联信息
        fillRelatedInfo(Arrays.asList(entry));
        
        return AjaxResult.success("查询成功", entry);
    }

    /**
     * 校验关联的屠宰场、运送清单、订单是否存在
     */
    private AjaxResult validateRelation(Integer houseId, Integer deliveryId, Integer orderId) {
        SlaughterHouse house = slaughterHouseMapper.selectById(houseId);
        if (house == null || (house.getIsDelete() != null && house.getIsDelete() == 1)) {
            return AjaxResult.error("屠宰场不存在");
        }

        Delivery delivery = deliveryMapper.selectById(deliveryId);
        if (delivery == null) {
            return AjaxResult.error("运送清单不存在");
        }

        if (orderId != null) {
            Order order = orderMapper.selectById(orderId);
            if (order == null || (order.getIsDelete() != null && order.getIsDelete() == 1)) {
                return AjaxResult.error("订单不存在");
            }
        }
        return null;
    }

    /**
     * 生成进场编码：SE + yyyyMMdd + 4位流水号
     */
    private String generateEntryCode() {
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String prefix = "SE" + dateStr;
        SlaughterEntry last = slaughterEntryMapper.selectLastCode(prefix + "%");
        int next = 1;
        if (last != null && StringUtils.hasText(last.getEntryCode())) {
            String lastCode = last.getEntryCode();
            if (lastCode.startsWith(prefix)) {
                String seq = lastCode.substring(prefix.length());
                try {
                    next = Integer.parseInt(seq) + 1;
                } catch (NumberFormatException ignored) {
                    next = 1;
                }
            }
        }
        return String.format("%s%04d", prefix, next);
    }
}

