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

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.TCoreEngineServerInfoDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreServerInfoStatusDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreServerStatusDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreEngineServerInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreServerInfoStatus;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreServerInfoVO;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreServiceStatus;
import com.chenyang.nse.bussiness.entity.vo.TCoreServerInfoStatusVo;
import com.chenyang.nse.bussiness.service.core.ServerInfoStatusService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ServerInfoStatusServiceImpl implements ServerInfoStatusService {
   @Autowired
   private TCoreServerInfoStatusDao tCoreServerInfoStatusDao;
   @Autowired
   private TCoreServerStatusDao tCoreServerStatusDao;
   @Autowired
   private TCoreEngineServerInfoDao tCoreEngineServerInfoDao;
   private static String serverStartFlag = "0";
   private static final Logger log = LoggerFactory.getLogger(ServerInfoStatusServiceImpl.class);
   private static String DEFAULTCHART = "UTF-8";

   public void addServerInfoStatus(TCoreServerInfoStatus tCoreServerInfoStatus) {
      this.tCoreServerInfoStatusDao.save(tCoreServerInfoStatus);
   }

   public List<TCoreServerInfoStatus> queryNextPrimaryServer(String prePtid) {
      return this.tCoreServerInfoStatusDao.queryNextPrimaryServer(prePtid);
   }

   public List<TCoreServerInfoStatus> queryPrimaryServer() {
      return this.tCoreServerInfoStatusDao.queryPrimaryServer();
   }

   public void updateServerInfoStatus(TCoreServerInfoStatus tCoreServerInfoStatus) {
      this.tCoreServerInfoStatusDao.update(tCoreServerInfoStatus);
   }

   public List<TCoreServerInfoStatus> queryAllNoPrimaryServer() {
      return this.tCoreServerInfoStatusDao.queryAllNoPrimaryServer();
   }

   public List<TCoreServerInfoStatus> queryServerByCondition(TCoreServerInfoStatusVo cond) {
      return this.tCoreServerInfoStatusDao.queryServerByCondition(cond);
   }

   public List<TCoreServerInfoVO> queryAllServer() {
      List<TCoreServerInfoVO> list = this.tCoreServerInfoStatusDao.queryAllServer();
      return list;
   }

   public List<TCoreServerInfoStatus> queryTask(String servername, PageInfo pageInfo) {
      List<TCoreServerInfoStatus> list = this.tCoreServerInfoStatusDao.queryByPageInfo(pageInfo, Order.desc("updatetime"), new Criterion[]{Restrictions.like("servername", "%" + servername + "%"), Restrictions.eq("delflg", "0")});
      return list;
   }

   public void saveHaServer(Map<String, String> map) {
      String iprimaryserver = "0";
      TCoreServerInfoStatus tCoreServerInfoStatus = new TCoreServerInfoStatus();
      String haid = (String)map.get("haid");
      String serverType = (String)map.get("configuration_type");
      if (!"".equals(haid)) {
         Criterion tidCri = Restrictions.eq("id", haid);
         tCoreServerInfoStatus = (TCoreServerInfoStatus)this.tCoreServerInfoStatusDao.queryUnique(new Criterion[]{tidCri});
      }

      tCoreServerInfoStatus.setServername((String)map.get("servername"));
      tCoreServerInfoStatus.setIp((String)map.get("serverip"));
      tCoreServerInfoStatus.setPort((String)map.get("ha-port"));
      tCoreServerInfoStatus.setIsprimaryserver((String)map.get("iprimaryserver"));
      tCoreServerInfoStatus.setIsactive(!"1".equals(map.get("isactive")) ? "0" : (String)map.get("isactive"));
      tCoreServerInfoStatus.setCreatetime(new Date());
      tCoreServerInfoStatus.setUpdatetime(new Date());
      tCoreServerInfoStatus.setRemarks((String)map.get("ha-note"));
      tCoreServerInfoStatus.setDelflg("0");
      tCoreServerInfoStatus.setServerid((String)map.get("serverid"));
      this.tCoreServerInfoStatusDao.saveOrUpdate(tCoreServerInfoStatus);
   }

   public void updateServerInfo(Map<String, String> map, String username) {
      String serverid = (String)map.get("serverid");
      String servername = (String)map.get("servername");
      String serverip = (String)map.get("serverip");
      TCoreServiceStatus tCoreServiceStatus = (TCoreServiceStatus)this.tCoreServerStatusDao.queryAll(new Criterion[]{Restrictions.eq("id", serverid)}).get(0);
      tCoreServiceStatus.setUpdatetime(new Date());
      tCoreServiceStatus.setServerName(servername);
      tCoreServiceStatus.setCreateserverip(serverip);
      tCoreServiceStatus.setEditUser(username);
      this.tCoreServerStatusDao.update(tCoreServiceStatus);
   }

   public TCoreServerInfoStatus queryServerByName(String servername) {
      List<TCoreServerInfoStatus> tCoreServerInfoStatusLst = this.tCoreServerInfoStatusDao.queryAll(Order.desc("createtime"), new Criterion[]{Restrictions.eq("servername", servername), Restrictions.eq("delflg", "0")});
      return tCoreServerInfoStatusLst != null && tCoreServerInfoStatusLst.size() > 0 ? (TCoreServerInfoStatus)tCoreServerInfoStatusLst.get(0) : null;
   }

   public TCoreServerInfoStatus queryServerById(String serverid) {
      return (TCoreServerInfoStatus)this.tCoreServerInfoStatusDao.queryUnique(new Criterion[]{Restrictions.eq("id", serverid)});
   }

   public void updateHaServer(Map<String, String> map) {
      if (null != map && map.containsKey("serverid") && StringUtils.isNotBlank((String)map.get("serverid"))) {
         TCoreServerInfoStatus updInfo = this.queryServerById((String)map.get("serverid"));
         updInfo.setServername((String)map.get("servername"));
         updInfo.setIp((String)map.get("ip"));
         updInfo.setPort((String)map.get("port"));
         updInfo.setRemarks((String)map.get("remarks"));
         updInfo.setCreatetime(new Date());
         updInfo.setUpdatetime(new Date());
         updInfo.setDelflg("0");
         this.tCoreServerInfoStatusDao.update(updInfo);
      }

   }

   public void updateHaServer(TCoreServerInfoStatus updInfo) {
      if (null != updInfo) {
         this.tCoreServerInfoStatusDao.update(updInfo);
      }

   }

   public void setPrimaryServerById(String serverid) {
      if (StringUtils.isNotBlank(serverid)) {
         List<TCoreServerInfoStatus> primaryServerLst = this.queryPrimaryServers();
         if (null != primaryServerLst && primaryServerLst.size() > 0) {
            for(int i = 0; i < primaryServerLst.size(); ++i) {
               TCoreServerInfoStatus oldPrimaryInfo = (TCoreServerInfoStatus)primaryServerLst.get(i);
               oldPrimaryInfo.setIsprimaryserver("0");
               oldPrimaryInfo.setUpdatetime(new Date());
               this.tCoreServerInfoStatusDao.update(oldPrimaryInfo);
            }
         }

         TCoreServerInfoStatus newPrimaryInfo = this.queryServerById(serverid);
         newPrimaryInfo.setIsprimaryserver("1");
         newPrimaryInfo.setUpdatetime(new Date());
         this.tCoreServerInfoStatusDao.update(newPrimaryInfo);
      }

   }

   public List<TCoreServerInfoStatus> queryPrimaryServers() {
      List<TCoreServerInfoStatus> tCoreServerInfoStatusLst = this.tCoreServerInfoStatusDao.queryAll(new Criterion[]{Restrictions.eq("isprimaryserver", "1"), Restrictions.eq("isactive", "1"), Restrictions.eq("delflg", "0")});
      return tCoreServerInfoStatusLst;
   }

   public String createCase(TCoreServiceStatus tcoreServiceStatus, String username) {
      String serverName = tcoreServiceStatus.getServerName();
      String createserverip = tcoreServiceStatus.getCreateserverip();
      TCoreServiceStatus queryUniqueServername = (TCoreServiceStatus)this.tCoreServerStatusDao.queryUnique(new Criterion[]{Restrictions.eq("delflg", "0"), Restrictions.eq("serverName", serverName)});
      TCoreServiceStatus queryUniqueServerip = (TCoreServiceStatus)this.tCoreServerStatusDao.queryUnique(new Criterion[]{Restrictions.eq("delflg", "0"), Restrictions.eq("createserverip", createserverip)});
      String flag;
      if (queryUniqueServername != null) {
         flag = "0";
      } else if (queryUniqueServerip != null) {
         flag = "1";
      } else {
         tcoreServiceStatus.setCreatetime(new Date());
         tcoreServiceStatus.setUpdatetime(new Date());
         tcoreServiceStatus.setDelflg("0");
         tcoreServiceStatus.setCreateuser(username);
         tcoreServiceStatus.setEditUser(username);
         this.tCoreServerStatusDao.save(tcoreServiceStatus);
         flag = "2";
      }

      return flag;
   }

   public List<TCoreServiceStatus> findServerCase() {
      List<TCoreServiceStatus> caselist = this.tCoreServerStatusDao.queryAll(new Criterion[]{Restrictions.eq("delflg", "0")});
      return caselist;
   }

   public TCoreServiceStatus findBytid(String id) {
      TCoreServiceStatus queryUnique = (TCoreServiceStatus)this.tCoreServerStatusDao.queryUnique(new Criterion[]{Restrictions.eq("id", id), Restrictions.eq("delflg", "0")});
      return queryUnique;
   }

   public TCoreServerInfoStatus findServerStatusByServerid(String id) {
      TCoreServerInfoStatus queryUnique = (TCoreServerInfoStatus)this.tCoreServerInfoStatusDao.queryUnique(new Criterion[]{Restrictions.eq("serverid", id), Restrictions.eq("delflg", "0")});
      return queryUnique;
   }

   public TCoreEngineServerInfo findServerEngineByServerid(String id) {
      TCoreEngineServerInfo queryUnique = (TCoreEngineServerInfo)this.tCoreEngineServerInfoDao.queryUnique(new Criterion[]{Restrictions.eq("serverid", id), Restrictions.eq("delflg", "0")});
      return queryUnique;
   }

   public void del(Map map) {
      if (null != map) {
         TCoreEngineServerInfo tCoreEngineServerInfo = (TCoreEngineServerInfo)map.get("tCoreEngineServerInfo");
         TCoreServerInfoStatus tCoreServerInfoStatus = (TCoreServerInfoStatus)map.get("tCoreServerInfoStatus");
         TCoreServiceStatus tCoreServiceStatus = (TCoreServiceStatus)map.get("tCoreServiceStatus");
         if (tCoreEngineServerInfo != null) {
            this.tCoreEngineServerInfoDao.update(tCoreEngineServerInfo);
         }

         if (tCoreServerInfoStatus != null) {
            this.tCoreServerInfoStatusDao.update(tCoreServerInfoStatus);
         }

         if (tCoreServiceStatus != null) {
            this.tCoreServerStatusDao.update(tCoreServiceStatus);
         }
      }

   }

   public void pingIp() {
      boolean status = false;
      int timeOut = 1000;

      for(TCoreServiceStatus tCoreServiceStatus : this.tCoreServerStatusDao.queryAll(new Criterion[]{Restrictions.eq("delflg", "0")})) {
         String createserverip = tCoreServiceStatus.getCreateserverip();

         try {
            status = InetAddress.getByName(createserverip).isReachable(timeOut);
         } catch (Exception var12) {
            status = false;
         } finally {
            if (status) {
               if (tCoreServiceStatus.getStarttime() == null) {
                  tCoreServiceStatus.setStarttime(new Date());
               }
            } else {
               tCoreServiceStatus.setStarttime((Date)null);
            }

            if (status && "0".equals(serverStartFlag)) {
               Date lastStartDate = this.getServerLastStartTime(createserverip);
               if (null != lastStartDate) {
                  tCoreServiceStatus.setStarttime(lastStartDate);
               }
            }

         }
      }

      serverStartFlag = "1";
   }

   public static Connection login(String ip, String userName, String userPwd) {
      boolean flg = false;
      Connection conn = null;

      try {
         conn = new Connection(ip);
         conn.connect();
         flg = conn.authenticateWithPassword(userName, userPwd);
         if (flg) {
            log.info("=========登录成功=========" + conn);
            return conn;
         }
      } catch (IOException e) {
         log.error("=========登录失败=========" + e.getMessage());
      }

      return conn;
   }

   public static String execute(Connection conn, String cmd) {
      String result = "";

      try {
         if (conn != null) {
            Session session = conn.openSession();
            session.execCommand(cmd);
            result = processStdout(session.getStdout(), DEFAULTCHART);
            if (StringUtils.isBlank(result)) {
               log.info("得到标准输出为空,链接conn:" + conn + ",执行的命令：" + cmd);
               result = processStdout(session.getStderr(), DEFAULTCHART);
            } else {
               log.info("执行命令成功,链接conn:" + conn + ",执行的命令：" + cmd);
            }

            conn.close();
            session.close();
         }

         return result;
      } catch (Exception e) {
         log.info("执行命令失败,链接conn:" + conn + ",执行的命令：" + cmd + "  " + e.getMessage());
         return result;
      } finally {
         ;
      }
   }

   private static String processStdout(InputStream in, String charset) {
      InputStream stdout = new StreamGobbler(in);
      StringBuffer buffer = new StringBuffer();

      try {
         BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
         String line = null;

         while((line = br.readLine()) != null) {
            buffer.append(line + "\n");
         }
      } catch (UnsupportedEncodingException e) {
         log.error("解析脚本出错：" + e.getMessage());
         e.printStackTrace();
      } catch (IOException e) {
         log.error("解析脚本出错：" + e.getMessage());
         e.printStackTrace();
      }

      return buffer.toString();
   }

   public Date getServerLastStartTime(String serverIp) {
      Connection conn = login(serverIp, "infa", "infa");
      String execute = execute(conn, "who -b");
      if (StringUtils.isBlank(execute)) {
         return null;
      } else {
         String[] ss = execute.split("t");
         String time = ss[2];
         String trim = time.trim();
         System.out.println(trim);
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
         Date startDate = null;

         try {
            startDate = sdf.parse(trim);
         } catch (ParseException e) {
            e.printStackTrace();
         }

         return startDate;
      }
   }

   public static void main(String[] args) {
      Connection conn = login("192.168.2.109", "infa", "infa");
      String execute = execute(conn, "who -b");
      String[] ss = execute.split("t");
      String time = ss[2];
      String trim = time.trim();
      System.out.println(trim);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");

      try {
         Date parse = sdf.parse(trim);
         System.out.println(parse.getTime());
      } catch (ParseException e) {
         e.printStackTrace();
      }

   }
}
