package com.zhongshu.card.server.core.service.oss;

import com.github.microservice.core.util.net.IPUtil;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.server.core.dao.upload.InterfaceUseRecordDao;
import com.zhongshu.card.server.core.domain.upload.InterfaceUseRecord;
import com.zhongshu.card.server.core.service.base.SuperService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 上传文件记录
 *
 * @author TRX
 * @date 2025/2/18
 */
@Slf4j
@Service
public class InterfaceUseRecordService extends SuperService {

    @Autowired
    private InterfaceUseRecordDao interfaceUseRecordDao;

    @Autowired
    private HttpServletRequest request;

    /**
     * 接口访问频率判断
     *
     * @param key
     * @return
     */
    public ResultContent judge(String key, String faceName) {
        if (ObjectUtils.isNotEmpty(key)) {
            InterfaceUseRecord fileRecord = interfaceUseRecordDao.findTopByKeyAndInterfaceNameOrderByCreateTimeDesc(key, faceName);
            if (ObjectUtils.isNotEmpty(fileRecord)) {
                if ((System.currentTimeMillis() - fileRecord.getCreateTime()) <= 1000) {
                    return ResultContent.buildFail("上传太频繁，请稍后再试");
                }
            }
        }
        return ResultContent.buildSuccess();
    }

    public ResultContent judge(String key) {
        String faceName = request.getRequestURL().toString();
        return judge(key, faceName);
    }

    public ResultContent saveRecord(String key, String projectOid, Map<String, Object> metaInfo) {
        String faceName = request.getRequestURL().toString();
        return saveRecord(key, projectOid, faceName, metaInfo);
    }

    /**
     * 保存上传记录
     *
     * @param key
     * @return
     */
    public ResultContent saveRecord(String key, String projectOid, String faceName, Map<String, Object> metaInfo) {
        InterfaceUseRecord interfaceUseRecord = new InterfaceUseRecord();
        interfaceUseRecord.setKey(key);
        interfaceUseRecord.setProjectOid(projectOid);
        interfaceUseRecord.setMetaInfo(metaInfo);
        interfaceUseRecord.setInterfaceName(faceName);
        initEntityNoCheckOid(interfaceUseRecord);
        try {
            interfaceUseRecord.setUa(request.getHeader("User-Agent"));
            interfaceUseRecord.setIp(IPUtil.getRemoteIp(request));
            interfaceUseRecord.setUrl(request.getRequestURI());
        } catch (Exception e) {
            log.error("initLog error {}", e.getMessage());
        }
        interfaceUseRecordDao.save(interfaceUseRecord);
        return ResultContent.buildSuccess();
    }
}
