package com.storlead.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.result.Result;
import com.storlead.system.mapper.AgentPromptTemplateMapper;
import com.storlead.system.pojo.dto.AgentPromptTemplatePageDTO;
import com.storlead.system.pojo.dto.AgentPromptTemplateQueryDTO;
import com.storlead.system.pojo.entity.AgentPromptTemplateEntity;
import com.storlead.system.service.AgentPromptTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * AI 提示词模板服务实现
 */
@Service
public class AgentPromptTemplateServiceImpl
        extends ServiceImpl<AgentPromptTemplateMapper, AgentPromptTemplateEntity>
        implements AgentPromptTemplateService {

    @Override
    public IPage<AgentPromptTemplateEntity> pageQuery(AgentPromptTemplatePageDTO dto) {
        IPage<AgentPromptTemplateEntity> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        return page(page, buildListWrapper(dto.getTemplateName(), dto.getTemplateCode(), dto.getAppId(), dto.getEnabled()));
    }

    @Override
    public List<AgentPromptTemplateEntity> listQuery(AgentPromptTemplateQueryDTO dto) {
        LambdaQueryWrapper<AgentPromptTemplateEntity> w = buildListWrapper(null, null, dto.getAppId(), null);
        if (StrUtil.isNotBlank(dto.getTemplateCode())) {
            w.eq(AgentPromptTemplateEntity::getTemplateCode, dto.getTemplateCode().trim());
        }
        if (!CollectionUtils.isEmpty(dto.getTemplateCodes())) {
            w.in(AgentPromptTemplateEntity::getTemplateCode, dto.getTemplateCodes());
        }
        w.orderByAsc(AgentPromptTemplateEntity::getSort).orderByDesc(AgentPromptTemplateEntity::getId);
        return list(w);
    }

    @Override
    public AgentPromptTemplateEntity getDetail(Long id) {
        if (id == null) {
            return null;
        }
        return getOne(new LambdaQueryWrapper<AgentPromptTemplateEntity>()
                .eq(AgentPromptTemplateEntity::getId, id)
                .eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
    }

    @Override
    public AgentPromptTemplateEntity getByTemplateCode(String templateCode, Long appId) {
        if (StrUtil.isBlank(templateCode)) {
            return null;
        }
        LambdaQueryWrapper<AgentPromptTemplateEntity> w = new LambdaQueryWrapper<>();
        w.eq(AgentPromptTemplateEntity::getTemplateCode, templateCode.trim());
        w.eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        w.eq(AgentPromptTemplateEntity::getEnabled, true);
        if (appId != null) {
            w.eq(AgentPromptTemplateEntity::getAppId, appId);
        }
        w.last(" limit 1");
        return getOne(w);
    }

    @Override
    public Result<?> getAiPrompt(AgentPromptTemplateQueryDTO dto) {
        if (dto == null || StrUtil.isBlank(dto.getTemplateCode())) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper<AgentPromptTemplateEntity> w = new LambdaQueryWrapper<>();
        w.eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        w.eq(AgentPromptTemplateEntity::getTemplateCode, dto.getTemplateCode().trim());
        if (dto.getAppId() != null) {
            w.eq(AgentPromptTemplateEntity::getAppId, dto.getAppId());
        }
        w.last(" limit 1");
        AgentPromptTemplateEntity entity = getOne(w);
        if (entity == null) {
            return Result.error("参数错误，未找到对应的AI提示词,请联系管理员进行配置!");
        }
        return Result.result(entity);
    }

    @Override
    public Result<?> saveTemplate(AgentPromptTemplateEntity body) {
        if (body == null || StrUtil.isBlank(body.getTemplateCode())) {
            return Result.error("模板编码不能为空");
        }
        if (StrUtil.isBlank(body.getTemplateName())) {
            return Result.error("模板名称不能为空");
        }
        body.setTemplateCode(body.getTemplateCode().trim());
        body.setTemplateName(body.getTemplateName().trim());

        LambdaQueryWrapper<AgentPromptTemplateEntity> codeWrapper = new LambdaQueryWrapper<>();
        codeWrapper.eq(AgentPromptTemplateEntity::getTemplateCode, body.getTemplateCode());
        codeWrapper.eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (body.getAppId() != null) {
            codeWrapper.eq(AgentPromptTemplateEntity::getAppId, body.getAppId());
        }
        if (body.getId() == null) {
            if (count(codeWrapper) > 0) {
                return Result.error("模板编码'" + body.getTemplateCode() + "'已存在");
            }
        } else {
            AgentPromptTemplateEntity exists = getOne(codeWrapper);
            if (exists != null && !exists.getId().equals(body.getId())) {
                return Result.error("模板编码'" + body.getTemplateCode() + "'已存在,无法修改");
            }
        }
        if (body.getIsDelete() == null) {
            body.setIsDelete(CommonConstant.DEL_FLAG_0);
        }
        if (body.getEnabled() == null) {
            body.setEnabled(true);
        }
        if (body.getSort() == null) {
            body.setSort(0);
        }
        saveOrUpdate(body);
        return Result.result(body.getId());
    }

    @Override
    public Result<?> enableTemplate(Long id, Boolean enabled) {
        if (id == null || enabled == null) {
            return Result.error("参数错误");
        }
        boolean ok = update(new LambdaUpdateWrapper<AgentPromptTemplateEntity>()
                .set(AgentPromptTemplateEntity::getEnabled, enabled)
                .eq(AgentPromptTemplateEntity::getId, id)
                .eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
        return ok ? Result.ok() : Result.error("记录不存在或已删除");
    }

    @Override
    public Result<?> deleteTemplate(Long id) {
        if (id == null) {
            return Result.error("参数错误");
        }
        boolean ok = update(new LambdaUpdateWrapper<AgentPromptTemplateEntity>()
                .set(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_1)
                .eq(AgentPromptTemplateEntity::getId, id)
                .eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
        return ok ? Result.ok() : Result.error("记录不存在或已删除");
    }

    @Override
    public Result<?> getPromptContent(AgentPromptTemplateQueryDTO dto) {
        if (dto == null || StrUtil.isBlank(dto.getTemplateCode())) {
            return Result.error("模板编码不能为空");
        }
        AgentPromptTemplateEntity entity = getByTemplateCode(dto.getTemplateCode(), dto.getAppId());
        if (entity == null || StrUtil.isBlank(entity.getPromptContent())) {
            return Result.error("未找到对应的AI提示词,请联系管理员进行配置");
        }
        String content = entity.getPromptContent();
        content = replaceIfPresent(content, "$subject$", dto.getSubject());
        content = replaceIfPresent(content, "$content$", dto.getContent());
        content = replaceIfPresent(content, "$customerName$", dto.getCustomerName());
        content = replaceIfPresent(content, "$liaisonName$", dto.getLiaisonName());
        content = replaceIfPresent(content, "$continent$", dto.getContinent());
        content = replaceIfPresent(content, "$country$", dto.getCountry());
        return Result.result(content);
    }

    private LambdaQueryWrapper<AgentPromptTemplateEntity> buildListWrapper(
            String templateName, String templateCode, Long appId, Integer enabled) {
        LambdaQueryWrapper<AgentPromptTemplateEntity> w = new LambdaQueryWrapper<>();
        w.eq(AgentPromptTemplateEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(templateName)) {
            w.like(AgentPromptTemplateEntity::getTemplateName, templateName.trim());
        }
        if (StrUtil.isNotBlank(templateCode)) {
            w.like(AgentPromptTemplateEntity::getTemplateCode, templateCode.trim());
        }
        if (appId != null) {
            w.eq(AgentPromptTemplateEntity::getAppId, appId);
        }
        if (enabled != null) {
            w.eq(AgentPromptTemplateEntity::getEnabled, Objects.equals(enabled, CommonConstant.STATUS_NORMAL));
        }
        w.orderByAsc(AgentPromptTemplateEntity::getSort).orderByDesc(AgentPromptTemplateEntity::getId);
        return w;
    }

    private String replaceIfPresent(String content, String placeholder, String value) {
        if (StrUtil.isBlank(value)) {
            return content;
        }
        return content.replace(placeholder, value);
    }
}
