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

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
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.industrypolicy.domain.BizSubsidyMatter;
import com.ruoyi.web.modules.industrypolicy.mapper.BizSubsidyMatterMapper;
import com.ruoyi.web.modules.industrypolicy.service.IBizSubsidyMatterService;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyMatterRules;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyMatterValidation;

/**
 * 项目与补贴-补贴服务实现。
 */
@Service
public class BizSubsidyMatterServiceImpl implements IBizSubsidyMatterService
{
    @Autowired
    private BizSubsidyMatterMapper bizSubsidyMatterMapper;

    @Override
    public BizSubsidyMatter selectBizSubsidyMatterById(Long id)
    {
        return bizSubsidyMatterMapper.selectBizSubsidyMatterById(id);
    }

    @Override
    public List<BizSubsidyMatter> selectBizSubsidyMatterList(BizSubsidyMatter query)
    {
        return bizSubsidyMatterMapper.selectBizSubsidyMatterList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizSubsidyMatter(BizSubsidyMatter row)
    {
        SubsidyMatterValidation.validateRowForSave(row);
        row.setPublishStatus(0);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        return bizSubsidyMatterMapper.insertBizSubsidyMatter(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizSubsidyMatter(BizSubsidyMatter row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        SubsidyMatterValidation.validateRowForSave(row);
        BizSubsidyMatter db = requireRow(row.getId());
        if (!SubsidyMatterRules.canEdit(db.getPublishStatus()))
        {
            throw new ServiceException("已发布补贴请先下架后再编辑");
        }

        String oldDetailPath = db.getDetailFilePath();
        String oldCoverPath = db.getCoverFilePath();

        row.setPublishStatus(db.getPublishStatus());
        row.setPublishTime(db.getPublishTime());
        row.setOfflineTime(db.getOfflineTime());

        int n = bizSubsidyMatterMapper.updateBizSubsidyMatter(row);
        if (n > 0)
        {
            if (!StringUtils.equals(StringUtils.nvl(oldDetailPath, ""), StringUtils.nvl(row.getDetailFilePath(), "")))
            {
                deleteDiskFile(oldDetailPath);
            }
            if (!StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
            {
                deleteDiskFile(oldCoverPath);
            }
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizSubsidyMatterByIds(Long[] ids)
    {
        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)
        {
            BizSubsidyMatter row = bizSubsidyMatterMapper.selectBizSubsidyMatterById(id);
            if (row == null)
            {
                continue;
            }
            if (!SubsidyMatterRules.canDelete(row.getPublishStatus()))
            {
                throw new ServiceException("已发布的补贴不可删除，请先下架");
            }
            deleteDiskFile(row.getDetailFilePath());
            deleteDiskFile(row.getCoverFilePath());
        }
        return bizSubsidyMatterMapper.deleteBizSubsidyMatterByIds(cleaned.toArray(new Long[0]));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publish(Long id)
    {
        BizSubsidyMatter row = requireRow(id);
        if (!SubsidyMatterRules.canPublish(row.getPublishStatus()))
        {
            throw new ServiceException("仅「未发布」可发布");
        }
        SubsidyMatterValidation.validateRowForSave(row);
        row.setPublishStatus(1);
        row.setPublishTime(new Date());
        return bizSubsidyMatterMapper.updateBizSubsidyMatter(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int offline(Long id)
    {
        BizSubsidyMatter row = requireRow(id);
        if (!SubsidyMatterRules.canOffline(row.getPublishStatus()))
        {
            throw new ServiceException("仅「已发布」可下架");
        }
        row.setPublishStatus(0);
        row.setOfflineTime(new Date());
        return bizSubsidyMatterMapper.updateBizSubsidyMatter(row);
    }

    private BizSubsidyMatter requireRow(Long id)
    {
        BizSubsidyMatter row = bizSubsidyMatterMapper.selectBizSubsidyMatterById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在");
        }
        return row;
    }

    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);
    }
}
