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.BizBreedingStandard;
import com.ruoyi.web.modules.architecture.mapper.BizBreedingStandardMapper;
import com.ruoyi.web.modules.architecture.service.IBizBreedingStandardService;
import com.ruoyi.web.modules.architecture.support.BreedingStandardRules;
import com.ruoyi.web.modules.architecture.support.BreedingStandardTypeValidator;
import com.ruoyi.web.modules.architecture.support.BreedingStandardValidation;
import com.ruoyi.web.kb.support.KbApiProperties;
import com.ruoyi.web.kb.support.KbFileUrlResolver;
import com.ruoyi.web.kb.service.KnowledgeBaseClient;

/**
 * 养殖标准 服务实现；同步/移出知识库调用大模型知识库开放 API。
 * <p>下架：未发布 + 已同步，保留 kb_doc_id；下架不等于移出知识库。</p>
 */
@Service
public class BizBreedingStandardServiceImpl implements IBizBreedingStandardService
{
    /** 与上传接口 category 一致 */
    private static final String KB_CATEGORY_BREEDING_STANDARD = "养殖管理标准";

    @Autowired
    private BizBreedingStandardMapper bizBreedingStandardMapper;

    @Autowired
    private BreedingStandardTypeValidator breedingStandardTypeValidator;

    @Autowired
    private KnowledgeBaseClient knowledgeBaseClient;

    @Autowired
    private KbApiProperties kbApiProperties;

    @Override
    public BizBreedingStandard selectBizBreedingStandardById(Long id)
    {
        return bizBreedingStandardMapper.selectBizBreedingStandardById(id);
    }

    @Override
    public List<BizBreedingStandard> selectBizBreedingStandardList(BizBreedingStandard query)
    {
        return bizBreedingStandardMapper.selectBizBreedingStandardList(query);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizBreedingStandard(BizBreedingStandard row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        validateRowForSave(row);
        BizBreedingStandard db = requireRow(row.getId());
        if (!BreedingStandardRules.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 = bizBreedingStandardMapper.updateBizBreedingStandard(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 deleteBizBreedingStandardByIds(Long[] ids)
    {
        for (Long id : ids)
        {
            BizBreedingStandard row = bizBreedingStandardMapper.selectBizBreedingStandardById(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);
                bizBreedingStandardMapper.updateBizBreedingStandard(row);
            }
            deleteDiskFile(row.getContentFilePath());
            deleteDiskFile(row.getCoverFilePath());
            bizBreedingStandardMapper.deleteBizBreedingStandardById(id);
        }
        return ids.length;
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeKb(Long id)
    {
        BizBreedingStandard row = requireRow(id);
        if (!BreedingStandardRules.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 bizBreedingStandardMapper.updateBizBreedingStandard(row);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int offline(Long id)
    {
        BizBreedingStandard row = requireRow(id);
        if (!BreedingStandardRules.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 bizBreedingStandardMapper.updateBizBreedingStandard(row);
    }

    private void validateRowForSave(BizBreedingStandard row)
    {
        breedingStandardTypeValidator.assertAllowed(row.getStandardType());
        BreedingStandardValidation.validateStandardName(row.getStandardName());
        BreedingStandardValidation.validateIntroduction(row.getIntroduction());
        BreedingStandardValidation.validateContentAttachment(row.getContentFileName(), row.getContentFilePath());
        BreedingStandardValidation.validateCoverPath(row.getCoverFilePath());
    }

    private BizBreedingStandard requireRow(Long id)
    {
        BizBreedingStandard row = bizBreedingStandardMapper.selectBizBreedingStandardById(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);
    }
}
