package com.ruoyi.web.modules.innovation.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.innovation.domain.BizTechProjectGuide;
import com.ruoyi.web.modules.innovation.mapper.BizTechProjectGuideMapper;
import com.ruoyi.web.modules.innovation.service.IBizTechProjectGuideService;
import com.ruoyi.web.modules.innovation.support.TechProjectGuideRules;
import com.ruoyi.web.modules.innovation.support.TechProjectGuideTypeValidator;
import com.ruoyi.web.modules.innovation.support.TechProjectGuideValidation;

/**
 * 科技项目指南服务实现。
 */
@Service
public class BizTechProjectGuideServiceImpl implements IBizTechProjectGuideService
{
    @Autowired
    private BizTechProjectGuideMapper techProjectGuideMapper;

    @Autowired
    private TechProjectGuideTypeValidator techProjectGuideTypeValidator;

    @Override
    public BizTechProjectGuide selectBizTechProjectGuideById(Long id)
    {
        return techProjectGuideMapper.selectBizTechProjectGuideById(id);
    }

    @Override
    public List<BizTechProjectGuide> selectBizTechProjectGuideList(BizTechProjectGuide query)
    {
        return techProjectGuideMapper.selectBizTechProjectGuideList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizTechProjectGuide(BizTechProjectGuide row)
    {
        techProjectGuideTypeValidator.assertAllowed(row.getProjectType());
        TechProjectGuideValidation.validateRowForSave(row);
        boolean saveAndPublish = Boolean.TRUE.equals(row.getSaveAndPublish());
        row.setSaveAndPublish(null);
        row.setPublishStatus(0);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        int n = techProjectGuideMapper.insertBizTechProjectGuide(row);
        if (n > 0 && saveAndPublish)
        {
            publish(row.getId());
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizTechProjectGuide(BizTechProjectGuide row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        techProjectGuideTypeValidator.assertAllowed(row.getProjectType());
        TechProjectGuideValidation.validateRowForSave(row);
        BizTechProjectGuide db = requireRow(row.getId());
        if (!TechProjectGuideRules.canEdit(db.getPublishStatus()))
        {
            throw new ServiceException("已发布指南请先下架后再编辑");
        }

        String oldAttachmentPath = db.getAttachmentFilePath();
        String oldCoverPath = db.getCoverFilePath();

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

        int n = techProjectGuideMapper.updateBizTechProjectGuide(row);
        if (n > 0)
        {
            if (!StringUtils.equals(StringUtils.nvl(oldAttachmentPath, ""), StringUtils.nvl(row.getAttachmentFilePath(), "")))
            {
                deleteDiskFile(oldAttachmentPath);
            }
            if (!StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
            {
                deleteDiskFile(oldCoverPath);
            }
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizTechProjectGuideByIds(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)
        {
            BizTechProjectGuide row = techProjectGuideMapper.selectBizTechProjectGuideById(id);
            if (row == null)
            {
                continue;
            }
            if (!TechProjectGuideRules.canDelete(row.getPublishStatus()))
            {
                throw new ServiceException("已发布的指南不可删除，请先下架");
            }
            deleteDiskFile(row.getAttachmentFilePath());
            deleteDiskFile(row.getCoverFilePath());
        }
        return techProjectGuideMapper.deleteBizTechProjectGuideByIds(cleaned.toArray(new Long[0]));
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int offline(Long id)
    {
        BizTechProjectGuide row = requireRow(id);
        if (!TechProjectGuideRules.canOffline(row.getPublishStatus()))
        {
            throw new ServiceException("仅「已发布」可下架");
        }
        Date publishTime = row.getPublishTime();
        row.setPublishStatus(0);
        row.setOfflineTime(new Date());
        row.setPublishTime(publishTime);
        return techProjectGuideMapper.updateBizTechProjectGuide(row);
    }

    private BizTechProjectGuide requireRow(Long id)
    {
        BizTechProjectGuide row = techProjectGuideMapper.selectBizTechProjectGuideById(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);
    }
}
