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

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.prosperity.domain.BizCommonProsperityProject;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProjectOpImage;
import com.ruoyi.web.modules.prosperity.mapper.BizCommonProsperityProjectMapper;
import com.ruoyi.web.modules.prosperity.mapper.BizCommonProsperityProjectOpImageMapper;
import com.ruoyi.web.modules.prosperity.service.IBizCommonProsperityProjectService;
import com.ruoyi.web.modules.prosperity.support.CommonProsperityProjectRules;
import com.ruoyi.web.modules.prosperity.support.CommonProsperityProjectValidation;

/**
 * 共同富裕项目服务实现。
 */
@Service
public class BizCommonProsperityProjectServiceImpl implements IBizCommonProsperityProjectService
{
    @Autowired
    private BizCommonProsperityProjectMapper projectMapper;

    @Autowired
    private BizCommonProsperityProjectOpImageMapper opImageMapper;

    @Override
    public BizCommonProsperityProject selectBizCommonProsperityProjectById(Long id)
    {
        BizCommonProsperityProject row = projectMapper.selectBizCommonProsperityProjectById(id);
        if (row != null)
        {
            row.setOperationImages(opImageMapper.selectByProjectId(id));
            if (row.getOperationImages() != null)
            {
                row.setOpImageCount(row.getOperationImages().size());
            }
        }
        return row;
    }

    @Override
    public List<BizCommonProsperityProject> selectBizCommonProsperityProjectList(BizCommonProsperityProject query)
    {
        return projectMapper.selectBizCommonProsperityProjectList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizCommonProsperityProject(BizCommonProsperityProject row)
    {
        CommonProsperityProjectValidation.validateRowForSave(row);
        row.setPublishStatus(0);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        int n = projectMapper.insertBizCommonProsperityProject(row);
        if (n > 0)
        {
            saveOperationImages(row.getId(), row.getOperationImages());
        }
        return n;
    }

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

        List<BizCommonProsperityProjectOpImage> oldImages = opImageMapper.selectByProjectId(row.getId());
        String oldVideoPath = db.getVideoFilePath();
        String oldCoverPath = db.getCoverFilePath();

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

        int n = projectMapper.updateBizCommonProsperityProject(row);
        if (n > 0)
        {
            opImageMapper.deleteByProjectId(row.getId());
            saveOperationImages(row.getId(), row.getOperationImages());
            deleteRemovedImageFiles(oldImages, row.getOperationImages());
            if (!StringUtils.equals(StringUtils.nvl(oldVideoPath, ""), StringUtils.nvl(row.getVideoFilePath(), "")))
            {
                deleteDiskFile(oldVideoPath);
            }
            if (!StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
            {
                deleteDiskFile(oldCoverPath);
            }
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizCommonProsperityProjectByIds(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)
        {
            BizCommonProsperityProject row = projectMapper.selectBizCommonProsperityProjectById(id);
            if (row == null)
            {
                continue;
            }
            if (!CommonProsperityProjectRules.canDelete(row.getPublishStatus()))
            {
                throw new ServiceException("已发布的项目不可删除，请先下架");
            }
            List<BizCommonProsperityProjectOpImage> images = opImageMapper.selectByProjectId(id);
            for (BizCommonProsperityProjectOpImage img : images)
            {
                deleteDiskFile(img.getFilePath());
            }
            deleteDiskFile(row.getVideoFilePath());
            deleteDiskFile(row.getCoverFilePath());
        }
        Long[] idArray = cleaned.toArray(new Long[0]);
        opImageMapper.deleteByProjectIds(idArray);
        return projectMapper.deleteBizCommonProsperityProjectByIds(idArray);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publish(Long id)
    {
        BizCommonProsperityProject row = requireRow(id);
        if (!CommonProsperityProjectRules.canPublish(row.getPublishStatus()))
        {
            throw new ServiceException("仅「未发布」可发布");
        }
        List<BizCommonProsperityProjectOpImage> images = opImageMapper.selectByProjectId(id);
        if (images == null || images.isEmpty())
        {
            throw new ServiceException("发布前须至少上传1张运营图片");
        }
        row.setOperationImages(images);
        CommonProsperityProjectValidation.validateRowForSave(row);
        row.setPublishStatus(1);
        row.setPublishTime(new Date());
        return projectMapper.updateBizCommonProsperityProject(row);
    }

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

    private void saveOperationImages(Long projectId, List<BizCommonProsperityProjectOpImage> images)
    {
        if (images == null || images.isEmpty())
        {
            return;
        }
        for (BizCommonProsperityProjectOpImage img : images)
        {
            img.setProjectId(projectId);
        }
        opImageMapper.insertBatch(images);
    }

    private void deleteRemovedImageFiles(List<BizCommonProsperityProjectOpImage> oldImages,
            List<BizCommonProsperityProjectOpImage> newImages)
    {
        Set<String> newPaths = new HashSet<>();
        if (newImages != null)
        {
            for (BizCommonProsperityProjectOpImage img : newImages)
            {
                if (img != null && StringUtils.isNotEmpty(img.getFilePath()))
                {
                    newPaths.add(img.getFilePath());
                }
            }
        }
        if (oldImages == null)
        {
            return;
        }
        for (BizCommonProsperityProjectOpImage old : oldImages)
        {
            if (old != null && StringUtils.isNotEmpty(old.getFilePath()) && !newPaths.contains(old.getFilePath()))
            {
                deleteDiskFile(old.getFilePath());
            }
        }
    }

    private BizCommonProsperityProject requireRow(Long id)
    {
        BizCommonProsperityProject row = projectMapper.selectBizCommonProsperityProjectById(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);
    }
}
