package com.ruoyi.inventory.service.impl;

import java.util.List;

import com.ruoyi.common.annotation.SerialExecution;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.inventory.domain.Inventory;
import com.ruoyi.inventory.domain.OutboundOrderLog;
import com.ruoyi.inventory.mapper.InventoryMapper;
import com.ruoyi.inventory.mapper.OutboundOrderItemsMapper;
import com.ruoyi.inventory.mapper.OutboundOrderLogMapper;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.UUID;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.inventory.domain.OutboundOrderItems;
import com.ruoyi.inventory.mapper.OutboundOrdersMapper;
import com.ruoyi.inventory.domain.OutboundOrders;
import com.ruoyi.inventory.service.IOutboundOrdersService;

/**
 * 出库单主Service业务层处理
 *
 * @author ruoyi
 * @date 2025-12-03
 */
@Service
public class OutboundOrdersServiceImpl implements IOutboundOrdersService
{
    @Autowired
    private OutboundOrdersMapper outboundOrdersMapper;

    @Autowired
    private OutboundOrderItemsMapper outboundOrderItemsMapper;
    @Autowired
    private OutboundOrderLogMapper outboundOrderLogMapper;

    @Autowired
    private OwnersServiceImpl ownersService;

    @Autowired
    private WarehousesServiceImpl warehousesService;
    @Autowired
    private InventoryServiceImpl inventoryService;
    /**
     * 查询出库单主
     *
     * @param id 出库单主主键
     * @return 出库单主
     */
    @Override
    public OutboundOrders selectOutboundOrdersById(String id)
    {

        return outboundOrdersMapper.selectOutboundOrdersById(id);
    }

    /**
     * 查询出库单主列表
     *
     * @param outboundOrders 出库单主
     * @return 出库单主
     */
    @Override
    public List<OutboundOrders> selectOutboundOrdersList(OutboundOrders outboundOrders)
    {
        List<OutboundOrders> outboundOrders1 = outboundOrdersMapper.selectOutboundOrdersList(outboundOrders);
        return outboundOrders1;
    }

    /**
     * 新增出库单主
     *
     * @param outboundOrders 出库单主
     * @return 结果
     */
    @Transactional
    @Override
    public int insertOutboundOrders(OutboundOrders outboundOrders)
    {
        outboundOrders.setCreateTime(DateUtils.getNowDate());
        outboundOrders.setCreateBy(SystemUtils.getUserName());
        outboundOrders.setId(UUID.randomUUID().toString());

        int rows = outboundOrdersMapper.insertOutboundOrders(outboundOrders);
        insertOutboundOrderItems(outboundOrders);
        return rows;
    }

    /**
     * 修改出库单主
     *
     * @param outboundOrders 出库单主
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOutboundOrders(OutboundOrders outboundOrders)
    {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderId(outboundOrders.getId());
        outboundOrderLogMapper.deleteOutboundOrderLogByOrdersId(outboundOrders.getId());


        outboundOrders.setUpdateBy(SystemUtils.getUserName());
        outboundOrders.setUpdateTime(DateUtils.getNowDate());
        insertOutboundOrderItems(outboundOrders);
        return outboundOrdersMapper.updateOutboundOrders(outboundOrders);
    }

    /**
     * 批量删除出库单主
     *
     * @param ids 需要删除的出库单主主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOutboundOrdersByIds(String[] ids)
    {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderIds(ids);
        outboundOrderLogMapper.deleteOutboundOrderLogByOrdersIds(ids);
        return outboundOrdersMapper.deleteOutboundOrdersByIds(ids);
    }

    /**
     * 删除出库单主信息
     *
     * @param id 出库单主主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOutboundOrdersById(String id)
    {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderId(id);
        return outboundOrdersMapper.deleteOutboundOrdersById(id);
    }
    @SerialExecution(group = "inventoryRefresh", fair = true)
    @Override
    public int ship(OutboundOrders outboundOrders) {
        OutboundOrderItems outboundOrderItems1 = new OutboundOrderItems();
        outboundOrderItems1.setOrderId(outboundOrders.getId());
        List<OutboundOrderItems> outboundOrderItems = outboundOrderItemsMapper.selectOutboundOrderItemsList(outboundOrderItems1);
        List<OutboundOrderItems> outboundOrderItems2 = outboundOrderItems;
        OutboundOrderLog outboundOrderLog = new OutboundOrderLog();

        for (OutboundOrderItems outboundOrderItem : outboundOrderItems) {

            outboundOrderItem.setItemStatus(3l);
            outboundOrderItemsMapper.updateOutboundOrderItems(outboundOrderItem);

            outboundOrderLog.setId(outboundOrderItem.getId());
            outboundOrderLog.setItemStatus(outboundOrderItem.getItemStatus());
            outboundOrderLogMapper.updateOutboundOrderLog(outboundOrderLog);

        }


        outboundOrders.setId(outboundOrders.getId());
        outboundOrders.setOrderStatus(2l);
        outboundOrders.setUpdateTime(DateUtils.getNowDate());
        outboundOrders.setUpdateBy(SystemUtils.getUserName());
        outboundOrdersMapper.updateOutboundOrders(outboundOrders);

        inventoryService.ship(outboundOrderItems2);
        return 1;
    }

    /**
     * 新增出库单明细信息
     *
     * @param outboundOrders 出库单主对象
     */
    public void insertOutboundOrderItems(OutboundOrders outboundOrders) {
        List<OutboundOrderItems> outboundOrderItemsList = outboundOrders.getOutboundOrderItemsList();
        String id = outboundOrders.getId();
        // 1. 先做空列表校验（提前返回，避免无效逻辑）
        if (outboundOrderItemsList == null || outboundOrderItemsList.isEmpty()) {
            return;
        }

        // 2. 库存校验：失败时抛异常（核心修正：! 取反 + 异常抛出后代码立即终止）
        boolean isValid = inventoryService.inventoryLockValidation(outboundOrderItemsList);
        if (!isValid) { // 校验失败（返回false）时抛异常
            throw new RuntimeException("库存被修改请重新确认"); // 抛异常后，方法立即停止运行
        }

        // 2. 为明细设置订单ID和主键ID
        for (OutboundOrderItems items : outboundOrderItemsList) {
            items.setOutboundOrderId(id);
            // 生成无横线的UUID作为主键
            items.setId(UUID.randomUUID().toString().replace("-", ""));
        }

        // 3. 批量插入出库单明细
        outboundOrdersMapper.batchOutboundOrderItems(outboundOrderItemsList);

        // 4. 正确拷贝明细列表到日志列表（修复核心错误：遍历逐个拷贝）
        List<String> inventoryIds = new ArrayList<>();

        List<OutboundOrderLog> outboundOrderLogs = new ArrayList<>();
        for (OutboundOrderItems items : outboundOrderItemsList) {
            OutboundOrderLog log = new OutboundOrderLog();
            BeanUtils.copyProperties(items, log); // 单个对象属性拷贝
            log.setOrderId(items.getId());
            outboundOrderLogs.add(log);
            inventoryIds.add(log.getInventoryId());
            deleteOutboundOrdersById(items.getId());
        }

        // 5. 非空校验后插入日志（避免空列表触发SQL语法错误）
        if (!outboundOrderLogs.isEmpty()) {

            outboundOrderLogMapper.batchOutboundOrderLog(outboundOrderLogs);

        }
        // 7. 非空校验后刷新库存
        if (!inventoryIds.isEmpty()) {
            inventoryService.RefreshInventory(inventoryIds);
        }
    }

}
