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

import java.nio.file.Path;
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.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.kb.support.KbApiProperties;
import com.ruoyi.web.kb.support.KbMarkdownGenerator;
import com.ruoyi.web.kb.service.KnowledgeBaseClient;
import com.ruoyi.web.modules.architecture.support.WithdrawalPeriodStandardKbMarkdown;
import com.ruoyi.web.modules.architecture.domain.BizWithdrawalPeriodStandard;
import com.ruoyi.web.modules.architecture.mapper.BizWithdrawalPeriodStandardMapper;
import com.ruoyi.web.modules.architecture.service.IBizWithdrawalPeriodStandardService;
import com.ruoyi.web.modules.architecture.support.WithdrawalPeriodStandardRules;
import com.ruoyi.web.modules.architecture.support.WithdrawalPeriodStandardValidation;

/**
 * 休药期标准；同步/移出知识库调用大模型知识库开放 API（方式一：上传生成的 Markdown）。
 */
@Service
public class BizWithdrawalPeriodStandardServiceImpl implements IBizWithdrawalPeriodStandardService
{
    private static final String KB_CATEGORY_WITHDRAWAL_PERIOD = "休药期标准";

    @Autowired
    private BizWithdrawalPeriodStandardMapper bizWithdrawalPeriodStandardMapper;

    @Autowired
    private KnowledgeBaseClient knowledgeBaseClient;

    @Autowired
    private KbApiProperties kbApiProperties;

    @Autowired
    private WithdrawalPeriodStandardKbMarkdown withdrawalPeriodKbMarkdown;

    @Autowired
    private KbMarkdownGenerator kbMarkdownGenerator;

    @Override
    public BizWithdrawalPeriodStandard selectBizWithdrawalPeriodStandardById(Long id)
    {
        return bizWithdrawalPeriodStandardMapper.selectBizWithdrawalPeriodStandardById(id);
    }

    @Override
    public List<BizWithdrawalPeriodStandard> selectBizWithdrawalPeriodStandardList(BizWithdrawalPeriodStandard query)
    {
        return bizWithdrawalPeriodStandardMapper.selectBizWithdrawalPeriodStandardList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizWithdrawalPeriodStandard(BizWithdrawalPeriodStandard row)
    {
        validateRowForSave(row);
        row.setKbSyncStatus(0);
        row.setKbDocId(null);
        return bizWithdrawalPeriodStandardMapper.insertBizWithdrawalPeriodStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizWithdrawalPeriodStandard(BizWithdrawalPeriodStandard row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        validateRowForSave(row);
        BizWithdrawalPeriodStandard db = requireRow(row.getId());
        if (!WithdrawalPeriodStandardRules.canEdit(db.getKbSyncStatus()))
        {
            throw new ServiceException("仅「未同步」状态允许编辑");
        }
        row.setKbSyncStatus(db.getKbSyncStatus());
        row.setKbDocId(db.getKbDocId());
        return bizWithdrawalPeriodStandardMapper.updateBizWithdrawalPeriodStandard(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizWithdrawalPeriodStandardByIds(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)
        {
            BizWithdrawalPeriodStandard row = bizWithdrawalPeriodStandardMapper.selectBizWithdrawalPeriodStandardById(id);
            if (row == null)
            {
                continue;
            }
            if (!WithdrawalPeriodStandardRules.canDelete(row.getKbSyncStatus()))
            {
                throw new ServiceException("已同步的数据不可删除，请先移出知识库");
            }
        }
        return bizWithdrawalPeriodStandardMapper.deleteBizWithdrawalPeriodStandardByIds(cleaned.toArray(new Long[0]));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncKb(Long id)
    {
        BizWithdrawalPeriodStandard row = requireRow(id);
        if (!WithdrawalPeriodStandardRules.canSyncKb(row.getKbSyncStatus()))
        {
            throw new ServiceException("仅「未同步」可操作同步知识库");
        }
        Path mdFile = withdrawalPeriodKbMarkdown.generateForSync(row);
        try
        {
            String fileId = knowledgeBaseClient.uploadFile(
                    mdFile.toFile(),
                    mdFile.getFileName().toString(),
                    kbApiProperties.getDefaultKnowledgeBase(),
                    KB_CATEGORY_WITHDRAWAL_PERIOD);
            row.setKbSyncStatus(1);
            row.setKbDocId(fileId);
            return bizWithdrawalPeriodStandardMapper.updateBizWithdrawalPeriodStandard(row);
        }
        finally
        {
            kbMarkdownGenerator.deleteQuietly(mdFile);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeKb(Long id)
    {
        BizWithdrawalPeriodStandard row = requireRow(id);
        if (!WithdrawalPeriodStandardRules.canRemoveKb(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 bizWithdrawalPeriodStandardMapper.updateBizWithdrawalPeriodStandard(row);
    }

    private void validateRowForSave(BizWithdrawalPeriodStandard row)
    {
        String drugName = row.getDrugName() != null ? row.getDrugName().trim() : null;
        row.setDrugName(drugName);
        WithdrawalPeriodStandardValidation.validateDrugName(drugName);
        assertDrugNameUnique(drugName, row.getId());
        WithdrawalPeriodStandardValidation.validateDrugType(row.getDrugType());
        WithdrawalPeriodStandardValidation.validateWithdrawalDays(row.getWithdrawalDays());
        WithdrawalPeriodStandardValidation.validateUsageGuide(row.getUsageGuide());
        WithdrawalPeriodStandardValidation.validateDrugEffect(row.getDrugEffect());
    }

    private void assertDrugNameUnique(String drugName, Long excludeId)
    {
        if (bizWithdrawalPeriodStandardMapper.countByDrugNameExcludeId(drugName, excludeId) > 0)
        {
            throw new ServiceException("药物名称已存在");
        }
    }

    private BizWithdrawalPeriodStandard requireRow(Long id)
    {
        BizWithdrawalPeriodStandard row = bizWithdrawalPeriodStandardMapper.selectBizWithdrawalPeriodStandardById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在");
        }
        return row;
    }
}
