package com.seer.teach.admin.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.admin.convert.AdminAiScenarioConfigConvert;
import com.seer.teach.admin.request.AdminAiScenarioConfigPageReq;
import com.seer.teach.admin.request.AdminAiScenarioConfigReq;
import com.seer.teach.admin.response.AdminAiScenarioConfigResp;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.teacher.module.entity.AiScenarioConfigEntity;
import com.seer.teach.teacher.module.entity.AiScenarioEntity;
import com.seer.teach.teacher.service.IAiScenarioConfigService;
import com.seer.teach.teacher.service.IAiScenarioService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminAiScenarioConfigService {

    private final IAiScenarioConfigService aiScenarioConfigService;

    private final IAiScenarioService aiScenarioService;

    public PageListBean<AdminAiScenarioConfigResp> pageList(AdminAiScenarioConfigPageReq pageRequest) {
        log.info("分页查询AI场景配置列表，请求参数: {}", pageRequest);
        IPage<AiScenarioConfigEntity> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());

        IPage<AiScenarioConfigEntity> result = aiScenarioConfigService.page(page, new LambdaQueryWrapper<AiScenarioConfigEntity>()
                .eq(Objects.nonNull(pageRequest.getId()), AiScenarioConfigEntity::getId, pageRequest.getId())
                .eq(Objects.nonNull(pageRequest.getScenarioId()), AiScenarioConfigEntity::getScenarioId, pageRequest.getScenarioId())
                .eq(Objects.nonNull(pageRequest.getApiKeyId()), AiScenarioConfigEntity::getApiKeyId, pageRequest.getApiKeyId())
                .eq(Objects.nonNull(pageRequest.getModuleId()), AiScenarioConfigEntity::getModuleId, pageRequest.getModuleId())
                .eq(Objects.nonNull(pageRequest.getPriority()), AiScenarioConfigEntity::getPriority, pageRequest.getPriority())
                .eq(Objects.nonNull(pageRequest.getEnabled()), AiScenarioConfigEntity::getEnabled, pageRequest.getEnabled())
        );
        
        log.info("分页查询AI场景配置列表完成，查询到 {} 条记录", result.getRecords().size());
        PageListBean<AdminAiScenarioConfigResp> pageList = PageConverterUtils.convertPageListBean(result, AdminAiScenarioConfigConvert.INSTANCE::entityListToResponseList);
        if(CollectionUtil.isEmpty(pageList.getList())){
            return pageList;
        }
        Set<Integer> scenarioIds = pageList.getList().stream().map(AdminAiScenarioConfigResp::getScenarioId).collect(Collectors.toSet());

        List<AiScenarioEntity> aiScenarioEntities = aiScenarioService.list(new LambdaQueryWrapper<>(AiScenarioEntity.class).in(AiScenarioEntity::getId, scenarioIds));
        Map<Integer, String> map = aiScenarioEntities.stream().collect(Collectors.toMap(AiScenarioEntity::getId, AiScenarioEntity::getScenarioCode));
        pageList.getList().forEach(item -> item.setScenarioCode(map.get(item.getScenarioId())));
        return pageList;
    }

    public List<AdminAiScenarioConfigResp> list(AdminAiScenarioConfigReq queryParam) {
        log.info("查询AI场景配置列表，请求参数: {}", queryParam);
        List<AiScenarioConfigEntity> result = aiScenarioConfigService.list(new LambdaQueryWrapper<AiScenarioConfigEntity>()
                .eq(Objects.nonNull(queryParam.getId()), AiScenarioConfigEntity::getId, queryParam.getId())
                .eq(Objects.nonNull(queryParam.getScenarioId()), AiScenarioConfigEntity::getScenarioId, queryParam.getScenarioId())
                .eq(Objects.nonNull(queryParam.getApiKeyId()), AiScenarioConfigEntity::getApiKeyId, queryParam.getApiKeyId())
                .eq(Objects.nonNull(queryParam.getModuleId()), AiScenarioConfigEntity::getModuleId, queryParam.getModuleId())
                .eq(Objects.nonNull(queryParam.getPriority()), AiScenarioConfigEntity::getPriority, queryParam.getPriority())
                .eq(Objects.nonNull(queryParam.getEnabled()), AiScenarioConfigEntity::getEnabled, queryParam.getEnabled())
        );
        log.info("查询AI场景配置列表完成，查询到 {} 条记录", result.size());
        return AdminAiScenarioConfigConvert.INSTANCE.entityListToResponseList(result);
    }

    public AdminAiScenarioConfigResp getDetail(Long id) {
        log.info("根据ID获取AI场景配置详情，ID: {}", id);
        AiScenarioConfigEntity result = aiScenarioConfigService.getById(id);
        log.info("获取AI场景配置详情完成，ID: {}，结果: {}", id, result);
        return AdminAiScenarioConfigConvert.INSTANCE.entityToResponse(result);
    }

    public boolean save(AdminAiScenarioConfigReq aiScenarioConfig) {
        log.info("保存AI场景配置，请求参数: {}", aiScenarioConfig);
        AiScenarioConfigEntity entity = AdminAiScenarioConfigConvert.INSTANCE.reqToEntity(aiScenarioConfig);
        boolean saved = aiScenarioConfigService.save(entity);
        log.info("保存AI场景配置完成，结果: {}，保存的实体ID: {}", saved, entity.getId());
        return saved;
    }

    public boolean updateById(AdminAiScenarioConfigReq aiScenarioConfig) {
        log.info("根据ID更新AI场景配置，请求参数: {}", aiScenarioConfig);
        AiScenarioConfigEntity entity = AdminAiScenarioConfigConvert.INSTANCE.reqToEntity(aiScenarioConfig);
        boolean updated = aiScenarioConfigService.updateById(entity);
        log.info("根据ID更新AI场景配置完成，结果: {}，更新的实体ID: {}", updated, entity.getId());
        return updated;
    }

    public boolean deleteById(Long id) {
        log.info("根据ID删除AI场景配置，ID: {}", id);
        boolean updated = aiScenarioConfigService.removeById(id);
        log.info("根据ID删除AI场景配置完成，结果: {}，删除的实体ID: {}", updated, id);
        return updated;
    }
}