package com.ximai.system.service.impl;

import com.ximai.system.domain.SysApiLog;
import com.ximai.system.mapper.SysApiLogMapper;
import com.ximai.system.service.ISysApiLogService;
import org.apache.commons.beanutils.MethodUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

/**
 * 接口日志 服务层处理
 */
@Service
public class SysApiLogServiceImpl implements ISysApiLogService {
    @Autowired
    private SysApiLogMapper operApiMapper;
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 新增操作日志
     *
     * @param operLog 操作日志对象
     */
    @Override
    public void insertApiLog(SysApiLog operLog) {
        operLog.setCreateTime(new Date());
        operApiMapper.insertApiLog(operLog);
    }

    /**
     * 查询系统操作日志集合
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysApiLog> selectApiLogList(SysApiLog operLog) {
        return operApiMapper.selectApiLogList(operLog);
    }

    /**
     * 批量删除系统操作日志
     *
     * @param operIds 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int deleteApiLogByIds(Long[] operIds) {
        return operApiMapper.deleteApiLogByIds(operIds);
    }

    /**
     * 查询操作日志详细
     *
     * @param operId 操作ID
     * @return 操作日志对象
     */
    @Override
    public SysApiLog selectApiLogById(Long operId) {
        return operApiMapper.selectApiLogById(operId);
    }

    /**
     * 清空操作日志
     */
    @Override
    public void cleanApiLog() {
        operApiMapper.cleanApiLog();
    }

    @Override
    public void executeByIds(Long[] logIds) throws Exception {
        for(Long logid : logIds){
            SysApiLog log = this.selectApiLogById(logid);
            String clzStr = log.getMethod();
            String clz = clzStr.substring(0,clzStr.lastIndexOf("."));
            String methodStr = clzStr.substring(clzStr.lastIndexOf(".")+1);
            Object obj = applicationContext.getBean(Class.forName(clz));
            //参数转换
            Object[] params = log.parseParamObject();
            MethodUtils.invokeMethod(obj, methodStr.replace("()",""), params);
        }
    }

}
