package com.gxwebsoft.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.ai.entity.AiHistory;
import com.gxwebsoft.ai.mapper.AiHistoryMapper;
import com.gxwebsoft.ai.param.AiHistoryParam;
import com.gxwebsoft.ai.service.AiHistoryService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI审计历史记录表Service实现
 *
 * @author yc
 */
@Service
public class AiHistoryServiceImpl extends ServiceImpl<AiHistoryMapper, AiHistory> implements AiHistoryService {

    @Override
    public PageResult<AiHistory> pageRel(AiHistoryParam param) {
        PageParam<AiHistory, AiHistoryParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<AiHistory> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<AiHistory> listRel(AiHistoryParam param) {
        List<AiHistory> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<AiHistory, AiHistoryParam> page = new PageParam<>();
        page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public AiHistory getByIdRel(Long id) {
        AiHistoryParam param = new AiHistoryParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public AiHistory getValidHistory(String requestHash, String interfaceName, int minutes) {
        LambdaQueryWrapper<AiHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiHistory::getRequestHash, requestHash)
                   .eq(AiHistory::getInterfaceName, interfaceName)
                   .eq(AiHistory::getStatus, 0)
                   .eq(AiHistory::getDeleted, 0)
                   .ge(AiHistory::getCreateTime, LocalDateTime.now().minusMinutes(minutes));
        return getOne(queryWrapper, false);
    }

    @Override
    public void saveHistory(Long projectId, String requestHash, String interfaceName, String requestData, String responseData, Integer userId, String username, Integer tenantId) {
        AiHistory history = new AiHistory();
        history.setProjectId(projectId);
        history.setRequestHash(requestHash);
        history.setInterfaceName(interfaceName);
        history.setRequestData(requestData);
        history.setResponseData(responseData);
        history.setUserId(userId);
        history.setUsername(username);
        history.setStatus(0);
        history.setDeleted(0);
        history.setTenantId(tenantId);
        
        save(history);
    }
}