#!/usr/bin/env python
# coding=utf-8

import requests
import json
from time import sleep
from logger.logrecord import LogRecord

# from logger.logrecord import LogRecord
# from requests.exceptions import ConnectTimeout

class UserPasswd(object):
    def __init__(self, usrInfo, ip_port, httpStyle="http"):
        self.__userInfo = usrInfo
        self.__url = httpStyle + "://" + ip_port

    # 获取密码等级
    def getPasswdLevel(self, ):

        url = "%s/api/users/getPwdRate" % self.__url
        print "url ==:", url
        recv = None
        try:
            recv = requests.get(url, timeout=4)
            recv.raise_for_status()  # 如果响应状态码不是 200，就主动抛出异常

            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                print recv.headers['content-type']
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])
            # print recv.text
            recvInfo = recv.json()
            if recvInfo == None:
                return False, "获取密码等级异常:  None"

            dict_tmp = recvInfo["result"]
            if dict_tmp == None:
                return False, "获取密码等级异常: result == None"

            status = dict_tmp["status"]  # 状态
            # info    = dict_tmp["info"]
            info    = str(dict_tmp["info"].encode('utf-8'))
            # print type(status)
            # print type(info)

            if status != "y":
                return False, "获取密码等级异常: %s" % info

            if dict_tmp["result"] == None:
                return False, "获取密码等级异常: result_result == None"

            if dict_tmp["result"]["configValue"] == None:
                return False, "获取密码等级异常: result_result_configValue == None"

            PasswdLevel = str(dict_tmp["result"]["configValue"])

            return True, PasswdLevel

        # except requests.packages.urllib3.exceptions.MaxRetryError as e:
        #
        #     print "+++ %s ++" % type(str(e.message)),e.message
        #

        except requests.exceptions.ConnectionError as e:
            #print "链接错误"
            return False,"网络连接错误"

        except requests.exceptions.Timeout as e:
            return False,"网络超时"

        except Exception as e:
            LogRecord.instance().logger.exception("获取密码等级异常")
            return False, "获取密码等级异常"

    # -----------------------------------
    # 功能  ：  修改 密码
    # ----------------------------------
    def changeVMPasswd(self, oldPasswd, newPasswd):
        try:
            url = '%s/api/users/changePwd' % self.__url

            print url
            payload = {
                "login": self.__userInfo["userName"],
                "displayName": "null",
                "password": "null",
                "operateType": "null",
                "currPwd": oldPasswd,
                "newPwd": newPasswd,
                "inDomain": "true"
            }
            print "------------------", json.dumps(payload)
            headers = {'content-type': 'application/json'}
            recv = requests.post(url, data=json.dumps(payload), headers=headers, timeout=15)
            recv.raise_for_status()  # 如果响应状态码不是 200，就主动抛出异常
            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                print recv.headers['content-type']
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])


            recvInfo = recv.json()
            if recvInfo == None:
                return False, "修改密码异常:  None"
            dict_tmp = recvInfo["result"]
            if dict_tmp == None:
                return False, "修改密码异常: result == None"


            status = dict_tmp["status"]  # 状态
            # info    = dict_tmp["info"]
            info    = str(dict_tmp["info"].encode('utf-8'))

            # print type(status)
            # print type(info)

            if status != "y":
                return False, "修改密码异常: %s" % info
            return True, "修改密码成功"

        # except requests.packages.urllib3.exceptions.MaxRetryError as e:
        #
        #     print "+++ %s ++" % type(str(e.message)),e.message
        #
        # except requests.exceptions.ConnectionError as e:
        #
        #     print "--- %s ---" % type(str(e.message)),e.message

        except requests.exceptions.ConnectionError as e:
            return False,"网络连接错误"

        except requests.exceptions.Timeout as e:
            return False,"网络超时"

        except Exception as e:
            LogRecord.instance().logger.exception("修改密码异常")
            return False, "修改密码异常"


if __name__ == "__main__":
    import os, sys

    _dirs = os.path.abspath(__file__)  # 当前文件路径
    _dirs = os.path.dirname(_dirs)  # 当前文件目录
    _dirs = os.path.dirname(_dirs)  # 上级文件路径
    _dirs = os.path.dirname(_dirs)  # 上级文件路径
    sys.path.append(_dirs)  #

    from des import Des

    from os import environ

    environ["LOG_STDOUT"] = "stdout"  #
    en_str = Des.Encrypt("Pass1234")  # 加密
    print en_str
    # dec_str = Des.Decrypt(en_str)
    # print dec_str

    userInfo = {
        "userName": "jxm",
        "userPassword": en_str,  # "Pass1234",
    }

    usrPasswd = UserPasswd(userInfo, "192.168.102.33:8080")

    res = usrPasswd.getPasswdLevel()
    print res[1]

    # oldpasswd = Des.Encrypt("Pass1234")  # 加密
    # newpasswd = Des.Encrypt("Pass12345")  # 加密
    # print "oldpasswd = [%s]     newpasswd = [%s] " % (oldpasswd,newpasswd)
    #
    # # res = usrPasswd.changeVMPasswd(oldpasswd,newpasswd)
    # res = usrPasswd.changeVMPasswd(newpasswd,oldpasswd)
    # print res[1]
