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.BizQuarantineStation;
import com.ruoyi.web.modules.circulation.mapper.BizQuarantineStationMapper;
import com.ruoyi.web.modules.circulation.service.IBizQuarantineStationService;
import com.ruoyi.web.modules.circulation.support.QuarantineStationReferenceChecker;
import com.ruoyi.web.modules.circulation.support.QuarantineStationRules;
import com.ruoyi.web.modules.circulation.support.QuarantineStationValidation;

/**
 * 检疫站管理服务实现。
 */
@Service
public class BizQuarantineStationServiceImpl implements IBizQuarantineStationService
{
    @Autowired
    private BizQuarantineStationMapper bizQuarantineStationMapper;

    @Autowired
    private QuarantineStationReferenceChecker referenceChecker;

    @Override
    public BizQuarantineStation selectBizQuarantineStationById(Long id)
    {
        BizQuarantineStation row = bizQuarantineStationMapper.selectBizQuarantineStationById(id);
        enrichOperateStatusName(row);
        return row;
    }

    @Override
    public List<BizQuarantineStation> selectBizQuarantineStationList(BizQuarantineStation query)
    {
        List<BizQuarantineStation> list = bizQuarantineStationMapper.selectBizQuarantineStationList(query);
        if (list != null)
        {
            for (BizQuarantineStation row : list)
            {
                enrichOperateStatusName(row);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizQuarantineStation(BizQuarantineStation row)
    {
        QuarantineStationValidation.validateRowForSave(row);
        assertStationNameUnique(row.getStationName(), null);
        row.setDelFlag(QuarantineStationRules.DEL_FLAG_NORMAL);
        return bizQuarantineStationMapper.insertBizQuarantineStation(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizQuarantineStation(BizQuarantineStation row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        QuarantineStationValidation.validateRowForSave(row);
        BizQuarantineStation db = requireActiveRow(row.getId());
        assertStationNameUnique(row.getStationName(), row.getId());

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

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

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

    private void assertStationNameUnique(String stationName, Long excludeId)
    {
        int n = bizQuarantineStationMapper.countBizQuarantineStationByNameExcludeId(stationName, excludeId);
        if (n > 0)
        {
            throw new ServiceException("检疫站名称已存在");
        }
    }

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

    private static void enrichOperateStatusName(BizQuarantineStation row)
    {
        if (row != null)
        {
            row.setOperateStatusName(QuarantineStationRules.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);
    }
}
