package com.seeyon.apps.qrCodeForm.util;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.qrCodeForm.constant.QrCodeFormConstants;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.Constants;
import com.seeyon.ctp.rest.util.TokenUtil;
import com.seeyon.ctp.services.UserToken;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.TextEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginUtil {
    private static Log log = LogFactory.getLog(LoginUtil.class);

    private static ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

    private static TimedCache<String, String> tokenCache = CacheUtil.newTimedCache(14 * 60 * 1000);

    //rest信息
//    public static final String restName = AppContext.getSystemProperty("qrCodeForm.restName");
//    public static final String restPassword = AppContext.getSystemProperty("qrCodeForm.restPassword");


    /**
     * 获取token
     *
     * @param loginName 登录名
     * @return
     */
    public static Map getToken(String memberId, String loginName, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        String tokenId = tokenCache.get(memberId);
        if(null != tokenId) {
            map.put("id", tokenId);
            map.put("success", true);
            return map;
        }
        try {
            ConfigVo config = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId());
            String userName = config.getParamVal(QrCodeFormConstants.restId.name());
            String password = config.getParamVal(QrCodeFormConstants.restPwd.name());
            password = TextEncoder.decode(password);
            Long userId = null;
            if (Strings.isNotBlank(memberId)) {
                userId = Long.parseLong(memberId);
            }
            UserToken token = TokenUtil._getToken(userName, password, userId, loginName, null, Constants.login_useragent_from.wechat.name(), request, response);
            if (token != null) {
                map.put("success", true);
                map.put("id", token.getId());
                tokenCache.put(memberId, token.getId());
            }
        } catch (Exception e) {
            log.error("", e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

}
