package com.ruoyi.web.modules.trading.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.trading.domain.BizEntryIsolation;
import com.ruoyi.web.modules.trading.domain.BizEntryIsolationAlloc;
import com.ruoyi.web.modules.trading.mapper.BizEntryIsolationAllocMapper;
import com.ruoyi.web.modules.trading.mapper.BizEntryIsolationMapper;
import com.ruoyi.web.modules.trading.service.IBizEntryIsolationService;
import com.ruoyi.web.modules.trading.support.EarTagCodec;
import com.ruoyi.web.modules.trading.support.EntryIsolationReferenceChecker;
import com.ruoyi.web.modules.trading.support.EntryIsolationRules;
import com.ruoyi.web.modules.trading.support.EntryIsolationValidation;

/**
 * 入场隔离登记服务实现。
 */
@Service
public class BizEntryIsolationServiceImpl implements IBizEntryIsolationService
{
    @Autowired
    private BizEntryIsolationMapper bizEntryIsolationMapper;

    @Autowired
    private BizEntryIsolationAllocMapper bizEntryIsolationAllocMapper;

    @Autowired
    private EntryIsolationValidation entryIsolationValidation;

    @Autowired
    private EntryIsolationReferenceChecker referenceChecker;

    @Override
    public BizEntryIsolation selectBizEntryIsolationById(Long id)
    {
        BizEntryIsolation row = bizEntryIsolationMapper.selectBizEntryIsolationById(id);
        enrichDetail(row);
        return row;
    }

    @Override
    public List<BizEntryIsolation> selectBizEntryIsolationList(BizEntryIsolation query)
    {
        entryIsolationValidation.validateListQuery(query);
        List<BizEntryIsolation> list = bizEntryIsolationMapper.selectBizEntryIsolationList(query);
        if (list != null)
        {
            for (BizEntryIsolation row : list)
            {
                enrichListRow(row);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizEntryIsolation(BizEntryIsolation row)
    {
        entryIsolationValidation.prepareAndValidateForSave(row);
        row.setDelFlag(EntryIsolationRules.DEL_FLAG_NORMAL);
        int rows = bizEntryIsolationMapper.insertBizEntryIsolation(row);
        saveAllocRows(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizEntryIsolation(BizEntryIsolation row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        requireActiveRow(row.getId());
        entryIsolationValidation.prepareAndValidateForSave(row);
        row.setDelFlag(EntryIsolationRules.DEL_FLAG_NORMAL);
        int rows = bizEntryIsolationMapper.updateBizEntryIsolation(row);
        bizEntryIsolationAllocMapper.deleteAllocByEntryId(row.getId());
        saveAllocRows(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizEntryIsolationByIds(Long[] ids, String updateBy)
    {
        if (ids == null || ids.length == 0)
        {
            return 0;
        }
        List<Long> cleaned = new ArrayList<>();
        for (Long id : ids)
        {
            if (id != null)
            {
                cleaned.add(id);
            }
        }
        if (cleaned.isEmpty())
        {
            return 0;
        }
        for (Long id : cleaned)
        {
            BizEntryIsolation row = bizEntryIsolationMapper.selectBizEntryIsolationByIdAny(id);
            if (row == null || EntryIsolationRules.DEL_FLAG_DELETED.equals(row.getDelFlag()))
            {
                continue;
            }
            if (referenceChecker.hasReference(id))
            {
                throw new ServiceException("存在关联业务，无法删除");
            }
        }
        return bizEntryIsolationMapper.logicDeleteBizEntryIsolationByIds(
                cleaned.toArray(new Long[0]), updateBy);
    }

    private void saveAllocRows(BizEntryIsolation row)
    {
        List<BizEntryIsolationAlloc> allocs = row.getPenAllocList();
        if (allocs == null || allocs.isEmpty())
        {
            return;
        }
        Long entryId = row.getId();
        for (BizEntryIsolationAlloc alloc : allocs)
        {
            alloc.setEntryId(entryId);
        }
        bizEntryIsolationAllocMapper.batchInsertAlloc(allocs);
    }

    private BizEntryIsolation requireActiveRow(Long id)
    {
        BizEntryIsolation row = bizEntryIsolationMapper.selectBizEntryIsolationById(id);
        if (row == null)
        {
            throw new ServiceException("入场隔离登记不存在或已删除");
        }
        return row;
    }

    private void enrichListRow(BizEntryIsolation row)
    {
        if (row == null)
        {
            return;
        }
        Integer count = row.getPenAllocCount();
        if (count != null && count > 0)
        {
            row.setPenAllocSummary(count + " 个圈位");
        }
    }

    private void enrichDetail(BizEntryIsolation row)
    {
        if (row == null)
        {
            return;
        }
        enrichListRow(row);
        row.setEarTagList(EarTagCodec.parse(row.getEarTags()));
        List<BizEntryIsolationAlloc> allocs = bizEntryIsolationAllocMapper.selectAllocListByEntryId(row.getId());
        if (allocs != null)
        {
            for (BizEntryIsolationAlloc alloc : allocs)
            {
                alloc.setEarTagList(EarTagCodec.parse(alloc.getEarTags()));
            }
        }
        row.setPenAllocList(allocs);
    }
}
