package org.wcs.mapper.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.wcs.mapper.AppRecordApiResponseMapper;
import org.wcs.mapper.intf.AppRecordApiResponseService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.recordApi.QueryRecordApiResponseReq;
import org.wcs.model.po.app.AppRecordApiResponse;
import org.wcs.utils.AppStringUtils;

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

@Service
public class AppRecordApiResponseDao extends ServiceImpl<AppRecordApiResponseMapper, AppRecordApiResponse> implements AppRecordApiResponseService {

    /**
     * 查询接口调用记录
     * @param request 查询参数
     * @param pageSize 每页数量
     * @param pageIndex 页码
     * @return 查询结果
     */
    @Override
    public Tuple2<Long, List<AppRecordApiResponse>> queryByPage(QueryRecordApiResponseReq request, Integer pageSize, Integer pageIndex) {
        if(request == null || pageSize == null || pageIndex == null || pageSize <= 0 || pageIndex <= 0) {
            return null;
        }
        LambdaQueryWrapper<AppRecordApiResponse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(AppStringUtils.isNotEmpty(request.getPath()), AppRecordApiResponse::getPath, request.getPath());
        if(AppStringUtils.isNotEmpty(request.getQueryStr())) {
            queryWrapper.like(AppRecordApiResponse::getUrlParam, request.getQueryStr())
                    .or().like(AppRecordApiResponse::getRequestMsg, request.getQueryStr())
                    .or().like(AppRecordApiResponse::getResponseMsg, request.getQueryStr());
        }
        if(request.getRequestTimes() != null && request.getRequestTimes().length == 2) {
            queryWrapper.between(AppRecordApiResponse::getRequestTime, request.getRequestTimes()[0], request.getRequestTimes()[1]);
        }
        queryWrapper.orderByDesc(AppRecordApiResponse::getRequestTime);
        Page<AppRecordApiResponse> page = new Page<>(pageIndex, pageSize);
        try {
            Page<AppRecordApiResponse> pageResult = super.baseMapper.selectPage(page, queryWrapper);
            return new Tuple2<>(pageResult.getTotal(), pageResult.getRecords());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 插入接口调用记录
     * @param record 记录
     * @return 插入结果
     */
    @Override
    public int insert(AppRecordApiResponse record) {
        try {
            return super.baseMapper.insert(record);
        } catch (Exception e) {
            return 0;
        }
    }
}
