package com.sptg.iot.biz.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.iot.api.beans.ApiResultBean;
import com.sptg.iot.api.dto.IotApiLogDto;
import com.sptg.iot.api.entity.IotApiLog;
import com.sptg.iot.api.entity.IotSysConf;
import com.sptg.iot.biz.mapper.IotApiLogMapper;
import com.sptg.iot.biz.service.IotApiLogServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zwx
 * @create 2020/10/21 0:45
 */
@Service
@RequiredArgsConstructor
public class IotApiLogServiceImpl extends ServiceImpl<IotApiLogMapper, IotApiLog> implements IotApiLogServiceInterface {

    /**
     * 生成日志对象
     * @param apiMethod
     * @param urlPrefix
     * @param appId
     * @param reqData
     * @param apiResultBean
     * @return
     */
    @Async
    @Override
    public void recordIotApiLog(String apiMethod, String urlPrefix, String appId, String reqData, ApiResultBean apiResultBean) {
        IotApiLog apiLog = new IotApiLog();
        apiLog.setApiMethod(apiMethod);
        apiLog.setUrlPrefix(urlPrefix);
        apiLog.setCode(apiResultBean.getCode());
        apiLog.setCreateDate(new Date());
        apiLog.setMsg(apiResultBean.getMsg());
        apiLog.setData(JSONUtil.toJsonStr(apiResultBean.getData()));
        apiLog.setReqData(reqData);
        apiLog.setAppId(appId);
        this.insert(apiLog);
    }

    @Override
    public ResultBean<Page<IotApiLog>> pagingQuery(IotApiLogDto iotApiLogDto) {
        Page<IotApiLog> page = iotApiLogDto.getPage();
        Wrapper<IotApiLog> wrapper = new EntityWrapper<>();
        String urlPrefix = iotApiLogDto.getUrlPrefix();
        Integer code = iotApiLogDto.getCode();
        String apiMethod = iotApiLogDto.getApiMethod();
        if(StringUtils.hasText(urlPrefix)){
            wrapper.eq("s_url_prefix", urlPrefix);
        }
        if(StringUtils.hasText(apiMethod)){
            wrapper.eq("s_api_method", apiMethod);
        }
        if(code != null){
            wrapper.eq("s_code", code);
        }
        page.setRecords(this.baseMapper.pagingQuery(wrapper, iotApiLogDto.getPage()));
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    @Override
    public IotApiLog getIotApiLogById(Long id) {
        Wrapper<IotApiLog> wrapper = new EntityWrapper<>();
        wrapper.eq("l_id", id);
        IotApiLog iotApiLog = this.baseMapper.getOne(wrapper);
        return iotApiLog;
    }
}
