package com.chenyang.nse.bussiness.controller.restfulapi.tools;

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.controller.restfulapi.entity.ResultAPIEnum;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUser;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiInfo;
import com.chenyang.nse.bussiness.service.console.UserService;
import com.chenyang.nse.bussiness.service.core.api.ApiInfoService;
import com.chenyang.nse.bussiness.service.redis.RedisService;
import com.chenyang.nse.bussiness.tools.string.PasswordEncryptTool;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthorizationTool {
   @Autowired
   private UserService userService;
   @Autowired
   private RedisService redisService;
   @Autowired
   private ApiInfoService apiInfoService;
   private static AuthorizationTool authorizationTool;

   @PostConstruct
   public void init() {
      authorizationTool = this;
      authorizationTool.userService = this.userService;
      authorizationTool.redisService = this.redisService;
      authorizationTool.apiInfoService = this.apiInfoService;
   }

   public static Map<String, String> authentication(String authorization) {
      Map<String, String> reFlgMap = new HashMap();
      reFlgMap.put("code", "1");
      reFlgMap.put("msg", "身份验证信息验证失败");

      try {
         if (StringUtils.isBlank(authorization)) {
            reFlgMap.put("code", "1");
            reFlgMap.put("msg", "身份验证信息不能为空");
         } else {
            String[] auth = authorization.split(" ");
            if (auth.length < 2) {
               reFlgMap.put("code", "1");
               reFlgMap.put("msg", "身份验证信息基本格式不正确");
            } else {
               authorization = auth[1];

               try {
                  authorization = URLDecoder.decode(authorization, "utf-8");
                  authorization = Base64Tool.decryptBASE64(authorization);
               } catch (Exception e) {
                  reFlgMap.put("code", "1");
                  reFlgMap.put("msg", e.getMessage());
               }

               Object apiUser = authorizationTool.redisService.get("API_USER" + authorization);
               if (null != apiUser && !"".equals(apiUser.toString())) {
                  reFlgMap.put("code", "0");
                  reFlgMap.put("msg", "SUCCESS");
                  reFlgMap.put("username", apiUser.toString());
               } else {
                  String[] authorizationArr = authorization.split(":");
                  if (null != authorizationArr && authorizationArr.length >= 2) {
                     String usernameStr = authorizationArr[0];
                     String pwdStr = authorizationArr[1];
                     String pwdStr1 = PasswordEncryptTool.generatePassword(pwdStr);
                     List<TBaseUser> tBaseUserList = authorizationTool.userService.queryAll();

                     for(int i = 0; i < tBaseUserList.size(); ++i) {
                        if (usernameStr.equalsIgnoreCase(((TBaseUser)tBaseUserList.get(i)).getUsername()) && (pwdStr.equalsIgnoreCase(((TBaseUser)tBaseUserList.get(i)).getPassword()) || pwdStr1.equalsIgnoreCase(((TBaseUser)tBaseUserList.get(i)).getPassword()))) {
                           reFlgMap.put("code", "0");
                           reFlgMap.put("msg", "SUCCESS");
                           reFlgMap.put("username", usernameStr);
                           String apiLongConnectionFlg = PropertiesLoaderUtils.loadAllProperties("config.properties").getProperty("api_long_connection_flg");
                           String apiLongConnectionTimeout = PropertiesLoaderUtils.loadAllProperties("config.properties").getProperty("api_long_connection_timeout");
                           if ("1".equals(apiLongConnectionFlg)) {
                              authorizationTool.redisService.set("API_USER" + authorization, usernameStr, new Long((long)(3600 * Integer.valueOf(apiLongConnectionTimeout))));
                           }
                        }
                     }
                  } else {
                     reFlgMap.put("code", "1");
                     reFlgMap.put("msg", "身份验证信息格式不正确");
                  }
               }
            }
         }

         return reFlgMap;
      } catch (Exception e) {
         System.out.println(">>>>>>>身份验证抛出异常：" + e.getMessage());
         return reFlgMap;
      } finally {
         ;
      }
   }

   public static Map<String, String> releaseVerification(String reqUrl, String... type) {
      Map<String, String> reFlgMap = new HashMap();
      reFlgMap.put("code", "1");
      reFlgMap.put("msg", ResultAPIEnum.RT_ERROR_CODE_431_STR.getMsg());
      HashMap<String, String> condMap = new HashMap();
      condMap.put("url", reqUrl);
      if (null != type && type.length > 0) {
         condMap.put("type", type[0]);
      }

      List<ApiInfo> apiInfoList = authorizationTool.apiInfoService.queryApiInfoByConditon(condMap);
      if (null != apiInfoList && apiInfoList.size() > 0) {
         if (!"1".equals(((ApiInfo)apiInfoList.get(0)).getState())) {
            reFlgMap.put("msg", ResultAPIEnum.RT_ERROR_CODE_431_STR.getMsg());
         } else {
            reFlgMap.put("code", "0");
            reFlgMap.put("msg", "SUCCESS");
         }
      } else {
         reFlgMap.put("msg", ResultAPIEnum.RT_ERROR_CODE_430_STR.getMsg());
      }

      return reFlgMap;
   }
}
