# -*- encoding=utf8 -*-

import base64
import requests
import json
from common.confop import confOP

class sqlByIdb:

    # 登录
    def login(self):
        url = "http://docp.plt.babytree-inc.com/api/v1/passport/login/"
        header = {
            'Content-Type': 'application/json'
        }
        username = "dGVzdF9jbG91ZA=="
        password = "eDZpbkRITnJVRWRl"
        postdata = json.dumps({
            "username": base64.b64decode(username.encode('utf-8')).decode("utf-8"),
            "password": base64.b64decode(password.encode('utf-8')).decode("utf-8")
        })
        response = requests.request("POST", url, headers=header, data=postdata)
        result = json.loads(response.text.encode('utf8'))
        return result

    def selectSql(self, database, sql, param, env):
        login_result = sqlByIdb().login()
        sql = sql.replace('%d', '%s')
        for pa in param:
            pa = "'" + str(pa) + "'"
            sql = sql.replace('%s', pa, 1)
        print(sql)
        value = confOP().getYamlValue("idbSet")
        if env == "on":
            env = "live"
        instance_id = value[database][env]
        url = "http://docp.plt.babytree-inc.com/api/v1/sql/mysql/query/query/"
        payload = json.dumps({
            "instance_id": instance_id,
            "db_name": database,
            "tb_name": database,
            "limit_num": 3000,
            "sqlContent": sql
        })
        headers = {
            'Authorization': login_result["sid"],
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        result = json.loads(response.text.encode('utf8'))
        return result["results"][0]["rows"]
