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.BizIndustryPolicyPublicity;
import com.ruoyi.web.modules.industrypolicy.mapper.BizIndustryPolicyPublicityMapper;
import com.ruoyi.web.modules.industrypolicy.service.IBizIndustryPolicyPublicityService;
import com.ruoyi.web.modules.industrypolicy.support.IndustryPolicyPublicityRules;
import com.ruoyi.web.modules.industrypolicy.support.IndustryPolicyPublicityValidation;

/**
 * 产业政策宣传服务实现。
 */
@Service
public class BizIndustryPolicyPublicityServiceImpl implements IBizIndustryPolicyPublicityService
{
    @Autowired
    private BizIndustryPolicyPublicityMapper bizIndustryPolicyPublicityMapper;

    @Override
    public BizIndustryPolicyPublicity selectBizIndustryPolicyPublicityById(Long id)
    {
        return bizIndustryPolicyPublicityMapper.selectBizIndustryPolicyPublicityById(id);
    }

    @Override
    public List<BizIndustryPolicyPublicity> selectBizIndustryPolicyPublicityList(BizIndustryPolicyPublicity query)
    {
        return bizIndustryPolicyPublicityMapper.selectBizIndustryPolicyPublicityList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizIndustryPolicyPublicity(BizIndustryPolicyPublicity row)
    {
        IndustryPolicyPublicityValidation.validateRowForSave(row);
        row.setPublishStatus(0);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        return bizIndustryPolicyPublicityMapper.insertBizIndustryPolicyPublicity(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizIndustryPolicyPublicity(BizIndustryPolicyPublicity row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        IndustryPolicyPublicityValidation.validateRowForSave(row);
        BizIndustryPolicyPublicity db = requireRow(row.getId());
        if (!IndustryPolicyPublicityRules.canEdit(db.getPublishStatus()))
        {
            throw new ServiceException("已发布内容请先下架后再编辑");
        }

        String oldPolicyPath = db.getPolicyFilePath();
        String oldCoverPath = db.getCoverFilePath();

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

        int n = bizIndustryPolicyPublicityMapper.updateBizIndustryPolicyPublicity(row);
        if (n > 0)
        {
            if (!StringUtils.equals(StringUtils.nvl(oldPolicyPath, ""), StringUtils.nvl(row.getPolicyFilePath(), "")))
            {
                deleteDiskFile(oldPolicyPath);
            }
            if (!StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
            {
                deleteDiskFile(oldCoverPath);
            }
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizIndustryPolicyPublicityByIds(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)
        {
            BizIndustryPolicyPublicity row = bizIndustryPolicyPublicityMapper.selectBizIndustryPolicyPublicityById(id);
            if (row == null)
            {
                continue;
            }
            if (!IndustryPolicyPublicityRules.canDelete(row.getPublishStatus()))
            {
                throw new ServiceException("已发布的数据不可删除，请先下架");
            }
            deleteDiskFile(row.getPolicyFilePath());
            deleteDiskFile(row.getCoverFilePath());
        }
        return bizIndustryPolicyPublicityMapper.deleteBizIndustryPolicyPublicityByIds(cleaned.toArray(new Long[0]));
    }

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

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

    private BizIndustryPolicyPublicity requireRow(Long id)
    {
        BizIndustryPolicyPublicity row = bizIndustryPolicyPublicityMapper.selectBizIndustryPolicyPublicityById(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);
    }
}
