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.common.utils.StringUtils;
import com.ruoyi.web.modules.trading.domain.BizMarketEntry;
import com.ruoyi.web.modules.trading.domain.BizMarketEntryEarTag;
import com.ruoyi.web.modules.trading.domain.BizMarketStall;
import com.ruoyi.web.modules.trading.domain.vo.MarketStallOptionVo;
import com.ruoyi.web.modules.trading.mapper.BizMarketEntryEarTagMapper;
import com.ruoyi.web.modules.trading.mapper.BizMarketEntryMapper;
import com.ruoyi.web.modules.trading.mapper.BizMarketStallMapper;
import com.ruoyi.web.modules.trading.service.IBizMarketEntryService;
import com.ruoyi.web.modules.trading.support.EarTagCodec;
import com.ruoyi.web.modules.trading.support.MarketEntryEarTagResolver;
import com.ruoyi.web.modules.trading.support.MarketEntryReferenceChecker;
import com.ruoyi.web.modules.trading.support.MarketEntryRules;
import com.ruoyi.web.modules.trading.support.MarketEntryValidation;

/**
 * 市场进栏登记服务实现。
 */
@Service
public class BizMarketEntryServiceImpl implements IBizMarketEntryService
{
    @Autowired
    private BizMarketEntryMapper bizMarketEntryMapper;

    @Autowired
    private BizMarketEntryEarTagMapper bizMarketEntryEarTagMapper;

    @Autowired
    private BizMarketStallMapper bizMarketStallMapper;

    @Autowired
    private MarketEntryValidation marketEntryValidation;

    @Autowired
    private MarketEntryEarTagResolver marketEntryEarTagResolver;

    @Autowired
    private MarketEntryReferenceChecker referenceChecker;

    @Override
    public BizMarketEntry selectBizMarketEntryById(Long id)
    {
        BizMarketEntry row = bizMarketEntryMapper.selectBizMarketEntryById(id);
        enrichEarTags(row);
        return row;
    }

    @Override
    public List<BizMarketEntry> selectBizMarketEntryList(BizMarketEntry query)
    {
        marketEntryValidation.validateListQuery(query);
        List<BizMarketEntry> list = bizMarketEntryMapper.selectBizMarketEntryList(query);
        if (list != null)
        {
            for (BizMarketEntry row : list)
            {
                enrichEarTags(row);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizMarketEntry(BizMarketEntry row)
    {
        marketEntryValidation.prepareAndValidateForSave(row);
        row.setDelFlag(MarketEntryRules.DEL_FLAG_NORMAL);
        int rows = bizMarketEntryMapper.insertBizMarketEntry(row);
        saveEarTagItems(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizMarketEntry(BizMarketEntry row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        requireActiveRow(row.getId());
        marketEntryValidation.prepareAndValidateForSave(row);
        row.setDelFlag(MarketEntryRules.DEL_FLAG_NORMAL);
        int rows = bizMarketEntryMapper.updateBizMarketEntry(row);
        bizMarketEntryEarTagMapper.deleteEarTagByEntryId(row.getId());
        saveEarTagItems(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizMarketEntryByIds(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)
        {
            BizMarketEntry row = bizMarketEntryMapper.selectBizMarketEntryByIdAny(id);
            if (row == null || MarketEntryRules.DEL_FLAG_DELETED.equals(row.getDelFlag()))
            {
                continue;
            }
            if (referenceChecker.hasReference(id))
            {
                throw new ServiceException(MarketEntryRules.MSG_DELETE_REFERENCED);
            }
        }
        return bizMarketEntryMapper.logicDeleteBizMarketEntryByIds(
                cleaned.toArray(new Long[0]), updateBy);
    }

    @Override
    public List<MarketStallOptionVo> selectStallOptions()
    {
        BizMarketStall query = new BizMarketStall();
        List<BizMarketStall> stalls = bizMarketStallMapper.selectBizMarketStallList(query);
        List<MarketStallOptionVo> options = new ArrayList<>();
        if (stalls == null)
        {
            return options;
        }
        for (BizMarketStall stall : stalls)
        {
            MarketStallOptionVo vo = new MarketStallOptionVo();
            vo.setStallId(stall.getId());
            vo.setStallCode(stall.getStallCode());
            options.add(vo);
        }
        return options;
    }

    @Override
    public List<String> selectSupplierEarTags(Long supplierId)
    {
        marketEntryValidation.assertSupplierActiveForQuery(supplierId);
        return marketEntryEarTagResolver.listSupplierEarTagOptions(supplierId);
    }

    private void saveEarTagItems(BizMarketEntry row)
    {
        List<String> tags = row.getEarTagList();
        if (tags == null || tags.isEmpty())
        {
            return;
        }
        List<BizMarketEntryEarTag> items = new ArrayList<>();
        for (String tag : tags)
        {
            BizMarketEntryEarTag item = new BizMarketEntryEarTag();
            item.setEntryId(row.getId());
            item.setSupplierId(row.getSupplierId());
            item.setEarTag(tag);
            items.add(item);
        }
        bizMarketEntryEarTagMapper.batchInsertEarTag(items);
    }

    private void requireActiveRow(Long id)
    {
        BizMarketEntry row = bizMarketEntryMapper.selectBizMarketEntryById(id);
        if (row == null)
        {
            throw new ServiceException(MarketEntryRules.MSG_NOT_FOUND);
        }
    }

    private void enrichEarTags(BizMarketEntry row)
    {
        if (row == null)
        {
            return;
        }
        if (StringUtils.isNotEmpty(row.getEarTags()))
        {
            row.setEarTagList(EarTagCodec.parse(row.getEarTags()));
            return;
        }
        if (row.getId() == null)
        {
            row.setEarTagList(new ArrayList<>());
            return;
        }
        List<BizMarketEntryEarTag> items = bizMarketEntryEarTagMapper.selectEarTagListByEntryId(row.getId());
        List<String> tags = new ArrayList<>();
        if (items != null)
        {
            for (BizMarketEntryEarTag item : items)
            {
                if (item != null && StringUtils.isNotEmpty(item.getEarTag()))
                {
                    tags.add(item.getEarTag());
                }
            }
        }
        row.setEarTagList(tags);
        row.setEarTags(EarTagCodec.encode(tags));
    }
}
