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.BizFeedingStandard;
import com.ruoyi.web.modules.architecture.mapper.BizFeedingStandardMapper;
import com.ruoyi.web.modules.architecture.service.IBizFeedingStandardService;
import com.ruoyi.web.modules.architecture.support.FeedingStandardRules;
import com.ruoyi.web.modules.architecture.support.FeedingStandardTypeValidator;
import com.ruoyi.web.modules.architecture.support.FeedingStandardValidation;
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 BizFeedingStandardServiceImpl implements IBizFeedingStandardService
{
    private static final String KB_CATEGORY_FEEDING_STANDARD = "饲喂标准";

    @Autowired
    private BizFeedingStandardMapper bizFeedingStandardMapper;

    @Autowired
    private FeedingStandardTypeValidator feedingStandardTypeValidator;

    @Autowired
    private KnowledgeBaseClient knowledgeBaseClient;

    @Autowired
    private KbApiProperties kbApiProperties;

    @Override
    public BizFeedingStandard selectBizFeedingStandardById(Long id)
    {
        return bizFeedingStandardMapper.selectBizFeedingStandardById(id);
    }

    @Override
    public List<BizFeedingStandard> selectBizFeedingStandardList(BizFeedingStandard query)
    {
        return bizFeedingStandardMapper.selectBizFeedingStandardList(query);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizFeedingStandard(BizFeedingStandard row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        validateRowForSave(row);
        BizFeedingStandard db = requireRow(row.getId());
        if (!FeedingStandardRules.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 = bizFeedingStandardMapper.updateBizFeedingStandard(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 deleteBizFeedingStandardByIds(Long[] ids)
    {
        for (Long id : ids)
        {
            BizFeedingStandard row = bizFeedingStandardMapper.selectBizFeedingStandardById(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);
                bizFeedingStandardMapper.updateBizFeedingStandard(row);
            }
            deleteDiskFile(row.getContentFilePath());
            deleteDiskFile(row.getCoverFilePath());
            bizFeedingStandardMapper.deleteBizFeedingStandardById(id);
        }
        return ids.length;
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeKb(Long id)
    {
        BizFeedingStandard row = requireRow(id);
        if (!FeedingStandardRules.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 bizFeedingStandardMapper.updateBizFeedingStandard(row);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int offline(Long id)
    {
        BizFeedingStandard row = requireRow(id);
        if (!FeedingStandardRules.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 bizFeedingStandardMapper.updateBizFeedingStandard(row);
    }

    private void validateRowForSave(BizFeedingStandard row)
    {
        feedingStandardTypeValidator.assertAllowed(row.getStandardType());
        FeedingStandardValidation.validateStandardName(row.getStandardName());
        FeedingStandardValidation.validateIntroduction(row.getIntroduction());
        FeedingStandardValidation.validateContentAttachment(row.getContentFileName(), row.getContentFilePath());
        FeedingStandardValidation.validateCoverPath(row.getCoverFilePath());
    }

    private BizFeedingStandard requireRow(Long id)
    {
        BizFeedingStandard row = bizFeedingStandardMapper.selectBizFeedingStandardById(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);
    }
}
