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

import java.io.File;
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.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.modules.circulation.domain.BizTradeMarket;
import com.ruoyi.web.modules.circulation.mapper.BizTradeMarketMapper;
import com.ruoyi.web.modules.circulation.service.IBizTradeMarketService;
import com.ruoyi.web.modules.circulation.support.TradeMarketReferenceChecker;
import com.ruoyi.web.modules.circulation.support.TradeMarketRules;
import com.ruoyi.web.modules.circulation.support.TradeMarketValidation;

/**
 * 交易市场管理服务实现。
 */
@Service
public class BizTradeMarketServiceImpl implements IBizTradeMarketService
{
    @Autowired
    private BizTradeMarketMapper bizTradeMarketMapper;

    @Autowired
    private TradeMarketReferenceChecker referenceChecker;

    @Override
    public BizTradeMarket selectBizTradeMarketById(Long id)
    {
        BizTradeMarket row = bizTradeMarketMapper.selectBizTradeMarketById(id);
        enrichOperateStatusName(row);
        return row;
    }

    @Override
    public List<BizTradeMarket> selectBizTradeMarketList(BizTradeMarket query)
    {
        List<BizTradeMarket> list = bizTradeMarketMapper.selectBizTradeMarketList(query);
        if (list != null)
        {
            for (BizTradeMarket row : list)
            {
                enrichOperateStatusName(row);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizTradeMarket(BizTradeMarket row)
    {
        TradeMarketValidation.validateRowForSave(row);
        assertMarketNameUnique(row.getMarketName(), null);
        row.setDelFlag(TradeMarketRules.DEL_FLAG_NORMAL);
        return bizTradeMarketMapper.insertBizTradeMarket(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizTradeMarket(BizTradeMarket row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        TradeMarketValidation.validateRowForSave(row);
        BizTradeMarket db = requireActiveRow(row.getId());
        assertMarketNameUnique(row.getMarketName(), row.getId());

        String oldPhotoPath = db.getPhotoFilePath();
        row.setDelFlag(TradeMarketRules.DEL_FLAG_NORMAL);

        int n = bizTradeMarketMapper.updateBizTradeMarket(row);
        if (n > 0 && !StringUtils.equals(StringUtils.nvl(oldPhotoPath, ""), StringUtils.nvl(row.getPhotoFilePath(), "")))
        {
            deleteDiskFile(oldPhotoPath);
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizTradeMarketByIds(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)
        {
            BizTradeMarket row = bizTradeMarketMapper.selectBizTradeMarketByIdAny(id);
            if (row == null || TradeMarketRules.DEL_FLAG_DELETED.equals(row.getDelFlag()))
            {
                continue;
            }
            if (referenceChecker.hasReference(id))
            {
                throw new ServiceException("存在关联业务，无法删除");
            }
            deleteDiskFile(row.getPhotoFilePath());
        }
        return bizTradeMarketMapper.logicDeleteBizTradeMarketByIds(cleaned.toArray(new Long[0]), updateBy);
    }

    private void assertMarketNameUnique(String marketName, Long excludeId)
    {
        int n = bizTradeMarketMapper.countBizTradeMarketByNameExcludeId(marketName, excludeId);
        if (n > 0)
        {
            throw new ServiceException("市场名称已存在");
        }
    }

    private BizTradeMarket requireActiveRow(Long id)
    {
        BizTradeMarket row = bizTradeMarketMapper.selectBizTradeMarketById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在或已删除");
        }
        return row;
    }

    private static void enrichOperateStatusName(BizTradeMarket row)
    {
        if (row != null)
        {
            row.setOperateStatusName(TradeMarketRules.operateStatusName(row.getOperateStatus()));
        }
    }

    private void deleteDiskFile(String resourcePath)
    {
        if (StringUtils.isEmpty(resourcePath) || !resourcePath.startsWith(Constants.RESOURCE_PREFIX))
        {
            return;
        }
        String relative = FileUtils.stripPrefix(resourcePath);
        while (relative.startsWith("/") || relative.startsWith("\\"))
        {
            relative = relative.substring(1);
        }
        String full = RuoYiConfig.getProfile() + File.separator + relative.replace("/", File.separator);
        FileUtils.deleteFile(full);
    }
}
