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

import java.io.File;
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.constant.Constants;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.modules.architecture.domain.BizGrowthSlaughterStandard;
import com.ruoyi.web.modules.architecture.mapper.BizGrowthSlaughterStandardMapper;
import com.ruoyi.web.modules.architecture.service.IBizGrowthSlaughterStandardService;
import com.ruoyi.web.modules.architecture.support.GrowthSlaughterStandardRules;
import com.ruoyi.web.modules.architecture.support.GrowthSlaughterStandardTypeValidator;
import com.ruoyi.web.modules.architecture.support.GrowthSlaughterStandardValidation;
import com.ruoyi.web.kb.support.KbApiProperties;
import com.ruoyi.web.kb.support.KbFileUrlResolver;
import com.ruoyi.web.kb.service.KnowledgeBaseClient;

/**
 * 生长与出栏标准 服务实现；同步/移出知识库调用大模型知识库开放 API。
 */
@Service
public class BizGrowthSlaughterStandardServiceImpl implements IBizGrowthSlaughterStandardService
{
    private static final String KB_CATEGORY_GROWTH_SLAUGHTER_STANDARD = "生长与出栏标准";

    @Autowired
    private BizGrowthSlaughterStandardMapper bizGrowthSlaughterStandardMapper;

    @Autowired
    private GrowthSlaughterStandardTypeValidator growthSlaughterStandardTypeValidator;

    @Autowired
    private KnowledgeBaseClient knowledgeBaseClient;

    @Autowired
    private KbApiProperties kbApiProperties;

    @Override
    public BizGrowthSlaughterStandard selectBizGrowthSlaughterStandardById(Long id)
    {
        return bizGrowthSlaughterStandardMapper.selectBizGrowthSlaughterStandardById(id);
    }

    @Override
    public List<BizGrowthSlaughterStandard> selectBizGrowthSlaughterStandardList(BizGrowthSlaughterStandard query)
    {
        return bizGrowthSlaughterStandardMapper.selectBizGrowthSlaughterStandardList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizGrowthSlaughterStandard(BizGrowthSlaughterStandard row)
    {
        validateRowForSave(row);
        row.setPublishStatus(0);
        row.setKbSyncStatus(0);
        row.setKbDocId(null);
        row.setPublishTime(null);
        row.setOfflineTime(null);
        return bizGrowthSlaughterStandardMapper.insertBizGrowthSlaughterStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizGrowthSlaughterStandard(BizGrowthSlaughterStandard row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        validateRowForSave(row);
        BizGrowthSlaughterStandard db = requireRow(row.getId());
        if (!GrowthSlaughterStandardRules.canEdit(db.getPublishStatus(), db.getKbSyncStatus()))
        {
            if (db.getKbSyncStatus() != null && db.getKbSyncStatus() == 1)
            {
                throw new ServiceException("知识库已同步状态不允许修改");
            }
            throw new ServiceException("仅「未发布」状态允许编辑");
        }

        String oldContentPath = db.getContentFilePath();
        String oldCoverPath = db.getCoverFilePath();

        row.setPublishStatus(db.getPublishStatus());
        row.setKbSyncStatus(db.getKbSyncStatus());
        row.setKbDocId(db.getKbDocId());
        row.setPublishTime(db.getPublishTime());
        row.setOfflineTime(db.getOfflineTime());

        int n = bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
        if (n > 0)
        {
            if (!StringUtils.equals(oldContentPath, row.getContentFilePath()))
            {
                deleteDiskFile(oldContentPath);
            }
            if (!StringUtils.equals(StringUtils.nvl(oldCoverPath, ""), StringUtils.nvl(row.getCoverFilePath(), "")))
            {
                deleteDiskFile(oldCoverPath);
            }
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizGrowthSlaughterStandardByIds(Long[] ids)
    {
        for (Long id : ids)
        {
            BizGrowthSlaughterStandard row = bizGrowthSlaughterStandardMapper.selectBizGrowthSlaughterStandardById(id);
            if (row == null)
            {
                continue;
            }
            Integer ps = row.getPublishStatus();
            if (ps != null && ps != 0)
            {
                if (ps == 1)
                {
                    throw new ServiceException("已发布的数据不可删除，请先下架");
                }
                throw new ServiceException("仅「未发布」状态允许删除");
            }
            if (ps != null && ps == 0 && row.getKbSyncStatus() != null && row.getKbSyncStatus() == 1)
            {
                row.setKbSyncStatus(0);
                row.setKbDocId(null);
                bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
            }
            deleteDiskFile(row.getContentFilePath());
            deleteDiskFile(row.getCoverFilePath());
            bizGrowthSlaughterStandardMapper.deleteBizGrowthSlaughterStandardById(id);
        }
        return ids.length;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncKb(Long id)
    {
        BizGrowthSlaughterStandard row = requireRow(id);
        if (!GrowthSlaughterStandardRules.canSyncKb(row.getPublishStatus(), row.getKbSyncStatus()))
        {
            throw new ServiceException("仅「未发布且未同步」可操作同步知识库");
        }
        String fileUrl = KbFileUrlResolver.resolveForKbUpload(row.getContentFileUrl(), kbApiProperties.getFileUrlBase());
        String fileId = knowledgeBaseClient.uploadFileByUrl(fileUrl, KB_CATEGORY_GROWTH_SLAUGHTER_STANDARD, row.getStandardName());
        row.setKbSyncStatus(1);
        row.setKbDocId(fileId);
        return bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeKb(Long id)
    {
        BizGrowthSlaughterStandard row = requireRow(id);
        if (!GrowthSlaughterStandardRules.canRemoveKb(row.getPublishStatus(), row.getKbSyncStatus()))
        {
            throw new ServiceException("仅「未发布且已同步」可移出知识库");
        }
        String docId = row.getKbDocId();
        if (StringUtils.isNotEmpty(docId) && !docId.startsWith("LOCAL-"))
        {
            knowledgeBaseClient.deleteFile(docId);
        }
        row.setKbSyncStatus(0);
        row.setKbDocId(null);
        return bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publish(Long id)
    {
        BizGrowthSlaughterStandard row = requireRow(id);
        if (!GrowthSlaughterStandardRules.canPublish(row.getPublishStatus(), row.getKbSyncStatus()))
        {
            throw new ServiceException("仅「未发布且已同步」可发布");
        }
        row.setPublishStatus(1);
        row.setPublishTime(new Date());
        return bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int offline(Long id)
    {
        BizGrowthSlaughterStandard row = requireRow(id);
        if (!GrowthSlaughterStandardRules.canOffline(row.getPublishStatus()))
        {
            throw new ServiceException("仅「已发布」可下架");
        }
        row.setPublishStatus(0);
        row.setKbSyncStatus(1);
        if (StringUtils.isEmpty(row.getKbDocId()))
        {
            row.setKbDocId("LOCAL-" + id);
        }
        row.setOfflineTime(new Date());
        return bizGrowthSlaughterStandardMapper.updateBizGrowthSlaughterStandard(row);
    }

    private void validateRowForSave(BizGrowthSlaughterStandard row)
    {
        growthSlaughterStandardTypeValidator.assertAllowed(row.getStandardType());
        GrowthSlaughterStandardValidation.validateStandardName(row.getStandardName());
        GrowthSlaughterStandardValidation.validateIntroduction(row.getIntroduction());
        GrowthSlaughterStandardValidation.validateContentAttachment(row.getContentFileName(), row.getContentFilePath());
        GrowthSlaughterStandardValidation.validateCoverPath(row.getCoverFilePath());
    }

    private BizGrowthSlaughterStandard requireRow(Long id)
    {
        BizGrowthSlaughterStandard row = bizGrowthSlaughterStandardMapper.selectBizGrowthSlaughterStandardById(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);
    }
}
