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 java.util.Objects;
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.BizSubsidyProject;
import com.ruoyi.web.modules.industrypolicy.mapper.BizSubsidyProjectMapper;
import com.ruoyi.web.modules.industrypolicy.service.IBizSubsidyProjectService;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyProjectRules;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyProjectStatusResolver;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyProjectValidation;

/**
 * 项目与补贴-项目服务实现。
 */
@Service
public class BizSubsidyProjectServiceImpl implements IBizSubsidyProjectService
{
    @Autowired
    private BizSubsidyProjectMapper bizSubsidyProjectMapper;

    @Override
    public BizSubsidyProject selectBizSubsidyProjectById(Long id)
    {
        BizSubsidyProject row = bizSubsidyProjectMapper.selectBizSubsidyProjectById(id);
        refreshExecStatusIfNeeded(row);
        return row;
    }

    @Override
    public List<BizSubsidyProject> selectBizSubsidyProjectList(BizSubsidyProject query)
    {
        SubsidyProjectValidation.validateDateRange(query.getStartDate(), query.getEndDate());
        List<BizSubsidyProject> list = bizSubsidyProjectMapper.selectBizSubsidyProjectList(query);
        for (BizSubsidyProject row : list)
        {
            refreshExecStatusIfNeeded(row);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizSubsidyProject(BizSubsidyProject row)
    {
        SubsidyProjectValidation.validateRowForSave(row);
        SubsidyProjectStatusResolver.applySaveExecRules(row);
        row.setPublishStatus(0);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        return bizSubsidyProjectMapper.insertBizSubsidyProject(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizSubsidyProject(BizSubsidyProject row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        SubsidyProjectValidation.validateRowForSave(row);
        BizSubsidyProject db = requireRow(row.getId());
        if (!SubsidyProjectRules.canEdit(db.getPublishStatus()))
        {
            throw new ServiceException("已发布项目请先下架后再编辑");
        }

        String oldCoverPath = db.getCoverFilePath();
        row.setPublishStatus(db.getPublishStatus());
        row.setPublishTime(db.getPublishTime());
        row.setOfflineTime(db.getOfflineTime());

        SubsidyProjectStatusResolver.applySaveExecRules(row);

        int n = bizSubsidyProjectMapper.updateBizSubsidyProject(row);
        if (n > 0 && !StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
        {
            deleteDiskFile(oldCoverPath);
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizSubsidyProjectByIds(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)
        {
            BizSubsidyProject row = bizSubsidyProjectMapper.selectBizSubsidyProjectById(id);
            if (row == null)
            {
                continue;
            }
            if (!SubsidyProjectRules.canDelete(row.getPublishStatus()))
            {
                throw new ServiceException("已发布的项目不可删除，请先下架");
            }
            deleteDiskFile(row.getCoverFilePath());
        }
        return bizSubsidyProjectMapper.deleteBizSubsidyProjectByIds(cleaned.toArray(new Long[0]));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publish(Long id)
    {
        BizSubsidyProject row = requireRow(id);
        if (!SubsidyProjectRules.canPublish(row.getPublishStatus()))
        {
            throw new ServiceException("仅「未发布」可发布");
        }
        refreshExecStatusIfNeeded(row);
        SubsidyProjectValidation.validateRowForSave(row);
        row.setPublishStatus(1);
        row.setPublishTime(new Date());
        return bizSubsidyProjectMapper.updateBizSubsidyProject(row);
    }

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

    private void refreshExecStatusIfNeeded(BizSubsidyProject row)
    {
        if (row == null || row.getId() == null)
        {
            return;
        }
        if (row.getManualCompleteFlag() != null
                && row.getManualCompleteFlag() == SubsidyProjectRules.MANUAL_FLAG_LOCKED)
        {
            return;
        }
        Integer oldStatus = row.getExecStatus();
        Date oldActual = row.getActualEndDate();
        SubsidyProjectStatusResolver.applyAutoResolution(row, new Date());
        if (!Objects.equals(oldStatus, row.getExecStatus()) || !Objects.equals(oldActual, row.getActualEndDate()))
        {
            bizSubsidyProjectMapper.updateBizSubsidyProjectExecStatus(row);
        }
    }

    private BizSubsidyProject requireRow(Long id)
    {
        BizSubsidyProject row = bizSubsidyProjectMapper.selectBizSubsidyProjectById(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);
    }
}
