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

import java.io.File;
import java.util.ArrayList;
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.kb.support.KbApiProperties;
import com.ruoyi.web.kb.support.KbFileUrlResolver;
import com.ruoyi.web.kb.service.KnowledgeBaseClient;
import com.ruoyi.web.modules.farming.domain.BizLivestockKnowledge;
import com.ruoyi.web.modules.farming.mapper.BizLivestockKnowledgeMapper;
import com.ruoyi.web.modules.farming.service.IBizLivestockKnowledgeService;
import com.ruoyi.web.modules.farming.support.LivestockKnowledgeRules;
import com.ruoyi.web.modules.farming.support.LivestockKnowledgeValidation;

/**
 * 综合牧业知识库；同步/移出知识库调用 KnowledgeBaseClient。
 */
@Service
public class BizLivestockKnowledgeServiceImpl implements IBizLivestockKnowledgeService
{
    private static final String KB_CATEGORY_LIVESTOCK_KNOWLEDGE = "综合牧业知识";

    @Autowired
    private BizLivestockKnowledgeMapper bizLivestockKnowledgeMapper;

    @Autowired
    private KnowledgeBaseClient knowledgeBaseClient;

    @Autowired
    private KbApiProperties kbApiProperties;

    @Override
    public BizLivestockKnowledge selectBizLivestockKnowledgeById(Long id)
    {
        return bizLivestockKnowledgeMapper.selectBizLivestockKnowledgeById(id);
    }

    @Override
    public List<BizLivestockKnowledge> selectBizLivestockKnowledgeList(BizLivestockKnowledge query)
    {
        return bizLivestockKnowledgeMapper.selectBizLivestockKnowledgeList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizLivestockKnowledge(BizLivestockKnowledge row)
    {
        normalizeAndValidate(row);
        row.setKbSyncStatus(LivestockKnowledgeRules.KB_SYNC_NOT_IN);
        row.setKbDocId(null);
        row.setDelFlag(LivestockKnowledgeRules.DEL_FLAG_NORMAL);
        return bizLivestockKnowledgeMapper.insertBizLivestockKnowledge(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizLivestockKnowledge(BizLivestockKnowledge row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        normalizeAndValidate(row);
        BizLivestockKnowledge db = requireRow(row.getId());
        if (!LivestockKnowledgeRules.canEdit(db.getKbSyncStatus()))
        {
            throw new ServiceException("已入库条目请先移出知识库后再编辑");
        }

        String oldContentPath = db.getContentFilePath();
        row.setKbSyncStatus(db.getKbSyncStatus());
        row.setKbDocId(db.getKbDocId());
        row.setDelFlag(db.getDelFlag());

        int n = bizLivestockKnowledgeMapper.updateBizLivestockKnowledge(row);
        if (n > 0 && !StringUtils.equals(oldContentPath, row.getContentFilePath()))
        {
            deleteDiskFile(oldContentPath);
        }
        return n;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizLivestockKnowledgeByIds(Long[] ids, String updateBy)
    {
        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)
        {
            BizLivestockKnowledge row = bizLivestockKnowledgeMapper.selectBizLivestockKnowledgeById(id);
            if (row == null)
            {
                continue;
            }
            if (!LivestockKnowledgeRules.canDelete(row.getKbSyncStatus()))
            {
                throw new ServiceException("已入库条目请先移出知识库后再删除");
            }
            deleteDiskFile(row.getContentFilePath());
        }
        return bizLivestockKnowledgeMapper.logicDeleteBizLivestockKnowledgeByIds(
                cleaned.toArray(new Long[0]), updateBy);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncKb(Long id)
    {
        BizLivestockKnowledge row = requireRow(id);
        if (!LivestockKnowledgeRules.canSyncKb(row.getKbSyncStatus()))
        {
            throw new ServiceException("该条目已入库");
        }
        try
        {
            String fileUrl = KbFileUrlResolver.resolveForKbUpload(
                    row.getContentFileUrl(), kbApiProperties.getFileUrlBase());
            String fileId = knowledgeBaseClient.uploadFileByUrl(
                    fileUrl, KB_CATEGORY_LIVESTOCK_KNOWLEDGE, row.getKnowledgeTitle());
            row.setKbSyncStatus(LivestockKnowledgeRules.KB_SYNC_IN);
            row.setKbDocId(fileId);
            return bizLivestockKnowledgeMapper.updateBizLivestockKnowledge(row);
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("同步知识库失败：" + ex.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeKb(Long id)
    {
        BizLivestockKnowledge row = requireRow(id);
        if (!LivestockKnowledgeRules.canRemoveKb(row.getKbSyncStatus()))
        {
            throw new ServiceException("仅已入库条目可移出知识库");
        }
        try
        {
            String docId = row.getKbDocId();
            if (StringUtils.isNotEmpty(docId) && !docId.startsWith("LOCAL-"))
            {
                knowledgeBaseClient.deleteFile(docId);
            }
            row.setKbSyncStatus(LivestockKnowledgeRules.KB_SYNC_NOT_IN);
            row.setKbDocId(null);
            return bizLivestockKnowledgeMapper.updateBizLivestockKnowledge(row);
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("移出知识库失败：" + ex.getMessage());
        }
    }

    private void normalizeAndValidate(BizLivestockKnowledge row)
    {
        if (row.getKnowledgeTitle() != null)
        {
            row.setKnowledgeTitle(row.getKnowledgeTitle().trim());
        }
        LivestockKnowledgeValidation.validateKnowledgeTitle(row.getKnowledgeTitle());
        LivestockKnowledgeValidation.validateKnowledgeTopic(row.getKnowledgeTopic());
        LivestockKnowledgeValidation.validateIntroduction(row.getIntroduction());
        LivestockKnowledgeValidation.validateContentAttachment(
                row.getContentFileName(), row.getContentFilePath());
    }

    private BizLivestockKnowledge requireRow(Long id)
    {
        BizLivestockKnowledge row = bizLivestockKnowledgeMapper.selectBizLivestockKnowledgeById(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);
    }
}
