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.AppRecordApiRequestMapper;
import org.wcs.mapper.intf.AppRecordApiRequestService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.recordApi.QueryRecordApiRequestReq;
import org.wcs.model.po.app.AppRecordApiRequest;
import org.wcs.utils.AppStringUtils;

import java.util.List;

@Service
public class AppRecordApiRequestDao extends ServiceImpl<AppRecordApiRequestMapper, AppRecordApiRequest> implements AppRecordApiRequestService {

    /**
     * 查询数据
     *
     * @param request 查询参数
     * @param pageSize 每页数量
     * @param pageIndex 页码
     * @return 数据
     */
    @Override
    public Tuple2<Long, List<AppRecordApiRequest>> queryByPage(QueryRecordApiRequestReq request, Integer pageSize, Integer pageIndex) {
        if(request == null || pageSize == null || pageIndex == null || pageSize <= 0 || pageIndex <= 0) {
            return null;
        }
        LambdaQueryWrapper<AppRecordApiRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(request.getSuccess() != null, AppRecordApiRequest::getSuccess, request.getSuccess());
        if(AppStringUtils.isNotEmpty(request.getQueryStr())) {
            queryWrapper.like(AppRecordApiRequest::getApiKey, request.getQueryStr())
                    .or().like(AppRecordApiRequest::getRequestMsg, request.getQueryStr())
                    .or().like(AppRecordApiRequest::getResponseMsg, request.getQueryStr());
        }
        if(request.getRequestTimes() != null && request.getRequestTimes().length == 2) {
            queryWrapper.between(AppRecordApiRequest::getRequestTime, request.getRequestTimes()[0], request.getRequestTimes()[1]);
        }
        queryWrapper.orderByDesc(AppRecordApiRequest::getRequestTime);
        Page<AppRecordApiRequest> page = new Page<>(pageIndex, pageSize);
        try {
            Page<AppRecordApiRequest> 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(AppRecordApiRequest record) {
        if(record == null) {
            return 0;
        }
        if(record.getApiKey() == null || record.getApiKey().isEmpty()) {
            record.setApiKey("-");
        }
        try {
            return super.save(record) ? 1 : 0;
        } catch (Exception e) {
            return 0;
        }
    }
}
