# -*-coding:utf-8-*-
import requests, time

from base_framework.public_tools import log
from base_framework.public_tools.get_token import LazyProperty
from base_framework.public_tools.read_config import InitConfig

obj_log = log.get_logger()


class Apollo:
    def __init__(self):
        self.server = None
        self.session = None
        self.config = InitConfig()
        self.show_username = self.config.show_username
        self.password = self.config.password
        self.apollo_url = self.config.apollo_url
        self.apollo_host = self.config.apollo_host
        self.current_evn = self.config.current_evn

    # @LazyProperty
    def apollo_login(self):
        post_data = dict()
        post_data['login-submit'] = '登录'
        post_data['username'] = self.show_username
        post_data['password'] = self.password
        req_session = requests.Session()
        resp = req_session.post(url=self.apollo_url, data=post_data)
        return req_session

    def __get_project__(self):
        pass

    def apollo_get_config_value(self, app_id, name_space, key, cluster='default'):
        """
        功能：读取apollo上的配置
        Args:
            app_id: url地址里的appid
            name_space: 页面分组的命名空间，如：application，dict.config，teach.common等
            key: 具体的配置key
            cluster: 集群名，如：default，hhi等
        Returns: 具体的配置值
        """
        return self.get_apollo_config_by_project_key(server=app_id, project=name_space, key=key, cluster=cluster)

    def get_apollo_config_by_project_key(self, project, key, cluster='default', server=""):
        """
        返回{id: 8812, namespaceId: 378, key: "", value: "", comment: "#线上不要此配置", lineNum: 1,…}
        """
        self.session = self.apollo_login()
        if server:
            self.server = server
        req_url = "%s/apps/%s/envs/%s/clusters/%s/namespaces" % (
            self.apollo_host, self.server, self.current_evn, cluster)
        obj_log.info("get apollo url is : %s" % req_url)
        resp = self.session.get(url=req_url).json()
        # obj_log.info("apollo value is : %s" % resp)
        for item in resp:
            base_info = item.get('baseInfo')
            items = item.get('items')
            if not base_info['namespaceName'].lower() == project.lower():
                continue
            for key_info in items:
                item_detail = key_info["item"]
                if item_detail["key"] == key:
                    return key_info["item"]
        else:
            obj_log.info("无法找到key:%s" % key)
            return None

    def set_apollo_config_by_project_key(self, project, key, value, cluster='default', server="", set_type='append',
                                         evn_name=""):
        """
        功能：设置apollo配置项
        Args:
            server: 项目名，也称appid
            project: 属性名
            key: 键值key
            value: 具体要设置的值
            cluster: 集群，如：default，hhi等
            set_type: 设置类型：append-追加，new-重置
        Returns:
        """
        if evn_name:
            self.current_evn = evn_name
        self.session = self.apollo_login()
        if server:
            self.server = server
        req_url = "%s/apps/%s/envs/%s/clusters/%s/namespaces/%s/item" % (
            self.apollo_host, self.server, self.current_evn, cluster, project)
        obj_log.info("set apollo url is : %s" % req_url)
        items = self.get_apollo_config_by_project_key(project, key, cluster)
        if items is None:
            items = dict()
            items["value"] = value
            items["key"] = key
            items["tableViewOperType"] = 'create'
            items["addItemBtnDisabled"] = True

        else:
            if set_type == 'new':
                items["value"] = value
            elif set_type == 'append':
                if str(value) in str(items["value"]):
                    obj_log.info("apollo配置已存在，本次跳过....")
                else:
                    items["value"] = items["value"] + ",{}".format(value)
            items["tableViewOperType"] = 'update'
        obj_log.info("set apollo parameters is : %s" % items)
        update_resp = self.session.put(url=req_url, json=items)
        obj_log.info("set apollo resp is : %s" % update_resp)

        assert update_resp.status_code == 200
        obj_log.info("为key:%s设置value：%s成功" % (key, value))
        release_body = dict()
        release_time_stamp = time.localtime()
        release_time = '%s-release' % time.strftime("%Y%m%d%H%M%S", release_time_stamp)
        release_body["isEmergencyPublish"] = False
        release_body["releaseComment"] = ""
        release_body["releaseTitle"] = release_time
        release_url = "%s/apps/%s/envs/%s/clusters/%s/namespaces/%s/releases" % (
            self.apollo_host, self.server, self.current_evn, cluster, project)
        resp = self.session.post(url=release_url, json=release_body)
        assert resp.status_code == 200
        time.sleep(5)

    def add_new_apollo_config_by_project_key(self, project, key, value, cluster='default', server=""):
        self.session = self.apollo_login()
        if server:
            self.server = server
        items = dict()
        items["value"] = value
        items["key"] = key
        items["tableViewOperType"] = 'create'
        items["addItemBtnDisabled"] = True
        req_url = "%s/apps/%s/envs/%s/clusters/%s/namespaces/%s/item" % (
            self.apollo_host, self.server, self.current_evn, cluster, project)
        update_resp = self.session.put(url=req_url, json=items)
        assert update_resp.status_code == 200
        release_body = dict()
        release_time_stamp = time.localtime()
        release_time = '%s-release' % time.strftime("%Y%m%d%H%M%S", release_time_stamp)
        release_body["isEmergencyPublish"] = False
        release_body["releaseComment"] = ""
        release_body["releaseTitle"] = release_time
        release_url = "%s/apps/%s/envs/%s/clusters/%s/namespaces/%s/releases" % (
            self.apollo_host, self.server, self.current_evn, cluster, project)
        resp = self.session.post(url=release_url, json=release_body)
        assert resp.status_code == 200
        time.sleep(5)


if __name__ == '__main__':
    ap = Apollo()
    print(ap.apollo_get_config_value(app_id='peppa-teach-api', name_space='application',
                                     key='new_ticket_leave_logic_switch'))
