package com.chenyang.nse.bussiness.service.core.impl.encryption;

import com.alibaba.fastjson.JSON;
import com.chenyang.nse.bussiness.config.ProxyConfig;
import com.chenyang.nse.bussiness.dao.table.base.TBaseAppUserDao;
import com.chenyang.nse.bussiness.dao.table.base.TBaseUserDao;
import com.chenyang.nse.bussiness.dao.table.core.TEncryptionProxyHostDao;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseAppUser;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUser;
import com.chenyang.nse.bussiness.jar.util.JarClientUtil;
import com.chenyang.nse.bussiness.jar.util.JarSocketCallback;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionProxyService;
import com.chenyang.nse.bussiness.tools.http.ClientUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EncryptionProxyServiceImpl implements EncryptionProxyService {
   private static final Logger log = LoggerFactory.getLogger(EncryptionProxyServiceImpl.class);
   @Autowired
   private TBaseUserDao tBaseUserDao;
   @Autowired
   TEncryptionProxyHostDao proxyHostDao;
   @Autowired
   ProxyConfig proxyConfig;
   @Autowired
   private TBaseAppUserDao tBaseAppUserDao;

   public String sendAppUserOriginalToTargetProxy(String projectId, String mode) {
      final String sendParam = this.buildAppUserOriginalInfosParam();
      if ("push".equals(mode)) {
         List<String> proxyUrlPrefix = this.tBaseAppUserDao.queryProxyUrlPrefixByProjectId(projectId);
         if (proxyUrlPrefix != null && proxyUrlPrefix.size() > 0) {
            for(final String urlPrefix : proxyUrlPrefix) {
               this.sendParams2AllProxy(sendParam, urlPrefix, this.proxyConfig.getSendAppUserOriginalUri(), new JarSocketCallback() {
                  public void isSucc() {
                     JarClientUtil.log(urlPrefix.split(":")[0], Integer.parseInt(urlPrefix.split(":")[1]), "推送应用用户是否明文，推送内容为【" + sendParam + "】，客户端接收成功！");
                  }

                  public void isFail() {
                     JarClientUtil.log(urlPrefix.split(":")[0], Integer.parseInt(urlPrefix.split(":")[1]), "推送应用用户是否明文，推送内容为【" + sendParam + "】，客户端接收失败！");
                  }
               });
            }
         }
      }

      return sendParam;
   }

   public String sendGatewatUserOriginalToTargetProxy(String projectId, String mode) {
      final String sendParam = this.buildGatewayUserOriginalInfosParam();
      if ("push".equals(mode)) {
         List<String> urlPrefixs = this.tBaseAppUserDao.queryProxyUrlPrefixByProjectId(projectId);
         if (urlPrefixs != null && urlPrefixs.size() > 0) {
            for(final String urlPrefix : urlPrefixs) {
               this.sendParams2AllProxy(sendParam, projectId, this.proxyConfig.getSendGatewayUserOriginalUri(), new JarSocketCallback() {
                  public void isSucc() {
                     JarClientUtil.log(urlPrefix.split(":")[0], Integer.parseInt(urlPrefix.split(":")[1]), "收到拉取请求，推送关平台用户“是否明文”配置，推送内容为【" + sendParam + "】，客户端接收成功！");
                  }

                  public void isFail() {
                     JarClientUtil.log(urlPrefix.split(":")[0], Integer.parseInt(urlPrefix.split(":")[1]), "收到拉取请求，推送关平台用户“是否明文”配置，推送内容为【" + sendParam + "】，客户端接收失败！");
                  }
               });
            }
         }
      }

      return sendParam;
   }

   public void noticeProxyFetchEngineAndMaskingInfosByProject(String projectId) {
      for(String ipPort : this.getProxyUrlByProject(projectId)) {
         if (StringUtils.isNotEmpty(ipPort)) {
            this.noticeProxyFetchEngineAndMaskingInfos(ipPort);
         } else {
            log.info("未找到目标插件，无法推送消息。当前projectId=" + projectId + "，目标ipPort=" + ipPort);
         }
      }

   }

   public void noticeProxyFetchEngineAndMaskingInfos(String ipPort) {
      (new Thread(() -> ClientUtil.doPost(ipPort + this.proxyConfig.getNoticeEngineAndMaskingInfoUri(), "{}", new JarSocketCallback() {
            public void isSucc() {
               JarClientUtil.log(ipPort.split(":")[0], Integer.parseInt(ipPort.split(":")[1]), "通知对应代理前来拉取脱敏及加密信息");
            }

            public void isFail() {
               JarClientUtil.log(ipPort.split(":")[0], Integer.parseInt(ipPort.split(":")[1]), "通知对应代理前来拉取脱敏及加密信息");
            }
         }))).start();
   }

   public List<String> getProxyUrlByProject(String projectId) {
      return this.proxyHostDao.getProxyHostByProject(projectId);
   }

   public List<AppUserOriginalVO> getAllAppUsersOriginalVO() {
      List<TBaseAppUser> tBaseAppUsers = this.tBaseAppUserDao.queryAll();
      List<AppUserOriginalVO> sendLists = new ArrayList();
      tBaseAppUsers.forEach((x) -> {
         AppUserOriginalVO sendVO = new AppUserOriginalVO();
         sendVO.setIsOriginal(x.getIsoriginal());
         sendVO.setIsmask(x.getIsmask());
         sendVO.setUsername(x.getUsername());
         sendLists.add(sendVO);
      });
      return sendLists;
   }

   public List<AppUserOriginalVO> getAllGatewayUsersOriginalVO() {
      List<TBaseUser> tBaseAppUsers = this.tBaseUserDao.queryAll();
      List<AppUserOriginalVO> sendLists = new ArrayList();
      tBaseAppUsers.forEach((x) -> {
         AppUserOriginalVO sendVO = new AppUserOriginalVO();
         sendVO.setIsOriginal(x.getPlaintext());
         sendVO.setIsmask(x.getDesensitize());
         sendVO.setUsername(x.getUsername());
         sendLists.add(sendVO);
      });
      return sendLists;
   }

   public void sendParams2AllProxy(String sendParam, String urlPrefix, String uri, JarSocketCallback callback) {
      String url = urlPrefix + uri;
      log.info("向插件发送配置信息：发送地址为=====【" + url + "】，发送信息为：" + sendParam);
      (new Thread(() -> ClientUtil.doPost(url, sendParam, callback))).start();
   }

   public String buildAppUserOriginalInfosParam() {
      new HashMap();
      List<AppUserOriginalVO> allAppUsersOriginalVO = this.getAllAppUsersOriginalVO();
      return JSON.toJSONString(allAppUsersOriginalVO);
   }

   public String buildGatewayUserOriginalInfosParam() {
      new HashMap();
      List<AppUserOriginalVO> allGatewayUsersOriginalVO = this.getAllGatewayUsersOriginalVO();
      return JSON.toJSONString(allGatewayUsersOriginalVO);
   }
}
