package com.union.ai.api.service.impl;

import com.union.ai.api.dao.mapper.AppMapper;
import com.union.ai.api.dao.model.App;
import com.union.ai.api.dao.model.AppCondition;
import com.union.ai.api.service.AppService;
import com.union.ai.api.util.CheckUtil;
import com.union.ai.api.util.GsonUtils;
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/3/24
 * Time: 下午1:54
 */
@Slf4j
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;

    /**
     * 查询生效app
     *
     * @param apiKey
     * @param secretKey
     * @return
     */
    @Override
    public App getEnableAppInfo(String apiKey, String secretKey) {
        AppCondition condition = new AppCondition();
        condition.createCriteria().andApiKeyEqualTo(apiKey).andSecretKeyEqualTo(secretKey).andStatusEqualTo(1);
        List<App> apps = appMapper.selectByCondition(condition);
        if (CheckUtil.isNotNull(apps)) {
            return apps.get(0);
        }
        log.info("appId={},userId={}没有查询到有效app信息", apiKey, secretKey);
        return null;
    }

    @Override
    public App getEnableAppInfo(Integer appId)
    {
       try
       {
            App  app = null;

            String  key = "redis_app_id_"+appId;
            String  appJson =  RedisUtil.get(key);
            if(appJson==null || appJson.trim().isEmpty())
            {
                AppCondition condition = new AppCondition();
                condition.createCriteria().andAppIdEqualTo(appId).andStatusEqualTo(1);
                List<App> apps = appMapper.selectByCondition(condition);
                if(apps!=null && apps.size()>0)
                {
                    app =  apps.get(0);
                    if(app!=null && app.getAppId()!=null)
                    {
                        RedisUtil.set(key, GsonUtils.toJson(app),60);
                    }
                }
            }
            else
            {
                app = GsonUtils.fromJson(appJson,App.class);
            }
           return app;
       }
       catch (Exception ee)
       {
           log.info("getEnableAppInfo-error", ee);
           return  null;
       }

    }


}
