package com.union.ai.api.task;

import com.union.ai.api.consts.RedisKeys;
import com.union.ai.api.dao.mapper.AppApiMapper;
import com.union.ai.api.dao.mapper.ext.AppApiMapperExt;
import com.union.ai.api.dao.model.AppApi;
import com.union.ai.api.util.CheckUtil;
import com.union.ai.api.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2019-06-01
 * Time: 19:22
 */
@Slf4j
@Service("syncTask")
public class SyncTask {

    @Autowired
    private AppApiMapperExt appApiMapperExt;
    @Autowired
    private AppApiMapper appApiMapper;

    public void syncLimitNumTask()
    {
        log.info("同步调用次数数据开始！");
        long start = System.currentTimeMillis();
        List<AppApi> appApis = null;
        try {
            appApis = appApiMapperExt.queryAllApi();
        } catch (Exception e) {
            log.error("查询调用次数错误", e);
        }
        if (CheckUtil.isNull(appApis)) return;
        log.info("同步调用次数查询出数据条数：{}", appApis.size());
        for (AppApi appApi : appApis)
        {
            Integer appId = appApi.getAppId();
            Integer apiId = appApi.getApiId();
            try
            {
                String key = String.format(RedisKeys.CALL_LIMIT_S, appId, apiId);
                String limit = RedisUtil.get(key);
                if (CheckUtil.isNull(limit)) {
//                    log.info("app=" + appId + ",api=" + apiId + " 尚未访问！");
                    continue;
                }
                Long limitNum = Long.valueOf(limit);
                AppApi api = new AppApi();
                api.setAppapiId(appApi.getAppapiId());
                if (limitNum < Long.valueOf(appApi.getCallLimit())) {
                    api.setUsed(limit);
                } else {
                    api.setUsed(appApi.getCallLimit());
                }
                appApiMapper.updateByIdSelective(api);
            } catch (Exception e) {
                log.error("更新app=" + appId + ",api=" + apiId + " 错误", e);
            }
        }
        log.info("同步调用次数数据耗时{}毫秒",(System.currentTimeMillis() - start));
    }
}
