# -*- coding:utf-8 -*-

"""
Author: 罗志鹏
Email: luozhipeng@huohua.cn
Create Date: 2022/07/25 11:25 下午
"""

import requests
import re
import json




class EnvCheck():
    def __init__(self):
        self.container_ip_list = []



    def get_env_container_ip(self,env):
        dis_server =[]
        dis_ip = []
        headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','Accept-Encoding':'gzip, deflate, br'}
        if env =='QA':
            req = requests.get(url="http://eureka.qa.huohua.cn/",headers=headers)
        elif env == 'SIM':
            req = requests.get(url="http://eureka.sim.huohua.cn/", headers=headers)
        else:
            raise RuntimeError("环境选择异常")
        req_list =req.text.split('tbody')
        # print(req_list[1])
        server_str_list = req_list[1].split('<tr>')
        check_list = self.get_check_lsit(env=env)

        for server in check_list:
            if req.text.find(server) ==-1:
                dis_server.append(server)


        for i in check_list:
            for str_ser in server_str_list:
                if str_ser.find(i) != -1:
                    dict_sever = {}
                    # ip_list = []
                    str_sername_start = '<td><b>'
                    str_sername_end = '</b></td>'
                    server_name = str_ser[str_ser.find(str_sername_start) + 7:str_ser.find(str_sername_end)]
                    ip_list = re.findall(r'[a-z]://(.*?):8080', str_ser)
                    dict_sever[server_name] = ip_list
                    # print(dict_sever)
                    for ip_ch in ip_list:
                        url_check = "http://"+ip_ch+':8080/actuator/health'
                        resp = requests.get(url=url_check)
                        # print(resp.json())
                        if resp.json()['status'] != 'UP':
                            dict_ip = {server_name:ip_ch}
                            dis_ip.append(dict_ip)
        return dis_ip,dis_server


        # re_list = []
        # server_list = []
        # for str_ser in server_check_list:
        #     print(str_ser)

            # print(server_name)

            # pattern = re.compile(r'')
            # str_server = pattern.search(str_ser)
            # server_name = str_ser[str_ser.start():str_ser.end()]
            # print(server_name)
        # for server in check_list :
        #     for string_server in server_list:
        #         if string_server.find(server)!= -1:
        #             # print(string_server.find(server))
        #             re_list.append(string_server)

        # print(re_list)
        # ip_list = []
        # for string_server in re_list :
        #     if string_server.find('http://'):
        #         pattern = re.compile(r'[a-zA-z]+://[^\s]*:8080')
        #         str_ip = pattern.search(string_server)
        #         # print(str_ip.start())
        #         url = string_server[str_ip.start():str_ip.end()]
        #         print(url)

    def send_result(self):
        dis_ip,dis_server = self.get_env_container_ip(env='SIM')
        at_user_list = [{"tag": "at", "user_id": "{}".format("7020366259502153730")}]

        message_data_SIM_server = {"msg_type": "text", "content": {'text':'SIM服务未找到部署IP{}'.format(dis_server)}}
        message_data_SIM_IP = {"msg_type": "text", "content": {'text':'SIM服务部署IP不可用{}'.format(dis_ip)}}

        headers = {"Content-Type": "application/json;charset=UTF-8"}
        web_hook = "https://open.feishu.cn/open-apis/bot/v2/hook/28b775e7-a863-4807-b280-c82e09be0a80"
        if len(dis_server) != 0:
            json_data = json.dumps(message_data_SIM_server)
            rsp = requests.post(url=web_hook, json=message_data_SIM_server, headers=headers)

        if len(dis_ip) != 0:
            json_data = json.dumps(message_data_SIM_IP)
            rsp = requests.post(url=web_hook, json=message_data_SIM_IP, headers=headers)
        dis_ip,dis_server = self.get_env_container_ip(env='QA')
        message_data_QA_server = {"msg_type": "text", "content": {'text':'QA服务未找到部署IP{}'.format(dis_server)}}
        message_data_QA_IP = {"msg_type": "text", "content": {'text':'QA服务部署IP不可用{}'.format(dis_ip)}}

        if len(dis_server) != 0:
            json_data = json.dumps(message_data_QA_server)
            rsp = requests.post(url=web_hook, data=json_data, headers=headers)
        if len(dis_ip) != 0:
            json_data = json.dumps(message_data_QA_IP)
            rsp = requests.post(url=web_hook, json=message_data_QA_IP, headers=headers)





    def get_check_lsit(self,env):
        if env == 'QA':
            check_list = ['PEPPA-STUDENT-API','PEPPA-LEARNING-PLAN-LISTENER','PEPPA-LEARNING-PLAN-SERVER','PEPPA-TEACH-BIZ','PEPPA-TEACH-LISTENER','PEPPA-TEACH-TIMETABLE-SERVER','PEPPA-USER-AUTH-API','PEPPA-USER-CENTER-SERVER']
            return check_list
        if env == 'SIM':
            check_list = ['PEPPA-STUDENT-API','PEPPA-LEARNING-PLAN-LISTENER','PEPPA-LEARNING-PLAN-SERVER','PEPPA-TEACH-BIZ','PEPPA-TEACH-LISTENER','PEPPA-TEACH-TIMETABLE-SERVER','PEPPA-USER-AUTH-API','PEPPA-USER-CENTER-SERVER']
            return check_list




if __name__ == '__main__':
    # o ='"http://10.251.187.248:8080/actuator/info"    "http://10.251.187.248:8080/actuator/info"'
    # i =re.findall(r'[a-z]://(.*?):8080',o)
    # print(a)
    A=EnvCheck()
    A.send_result()




