package com.friday.custody.service.basicService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.InvokeRecordDao;
import com.friday.custody.dto.ApiDto;
import com.friday.custody.entity.InvokeRecordEntity;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.BasicQueryReq;
import com.friday.custody.service.basicService.InvokeRecordService;
import com.friday.custody.utils.PageUtil;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service("invokeRecordService")
public class InvokeRecordServiceImpl extends ServiceImpl<InvokeRecordDao, InvokeRecordEntity> implements InvokeRecordService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InvokeRecordEntity> page = this.page(
                new Query<InvokeRecordEntity>().getPage(params),
                new QueryWrapper<InvokeRecordEntity>()
        );

        return new PageUtils(page);
    }
    @Override
    public List<ApiDto> queryInvokeType(String admin, String trustNo){
        List<ApiDto> invokeRecordEntities = baseMapper.queryInvokeType(admin, trustNo);
        return invokeRecordEntities;
    }

    @Override
    public boolean saveInvokeRecord(InvokeRecordEntity invokeRecordEntity) {
        return baseMapper.insert(invokeRecordEntity) == 1;
    }

    @Override
    public R queryByType(String tenantName, String type, String trustNo, BasicQueryReq basicQueryReq) {
        String key = tenantName + "::" + trustNo + "::" + type;
        try {
            QueryWrapper<InvokeRecordEntity> qw = new QueryWrapper<>();
            qw.eq("query_key", key);
            Map<String, Object> pageParams = PageUtil.getPageParams(basicQueryReq);
            IPage<InvokeRecordEntity> page = this.page(
                    new Query<InvokeRecordEntity>().getPage(pageParams),
                    qw
            );
            return R.ok("查询成功！").put("data", new PageUtils(page));
        } catch (Exception e) {
            log.error("查询失败: the key is :" + key, e);
            if (e instanceof RRException) {
                throw e;
            }
            return R.error("查询失败！");
        }
    }

    public Integer queryCountByKey(String admin, String api, String trustNo) {

        String queryKey = admin + "::" + trustNo + "::" + api;
        return baseMapper.selectCountByKey(queryKey);
    }
}