# -*- encoding=utf8 -*-

__author__ = "liguangyu"

"""
case_tag:api,cmdc-dologin,运营后台管理系统登录,sit,bs
"""
from common.common_func import commonFuc
import requests
import uuid
from common.verification_code_ocr import VerificationCodeOcr
import json
import os
import hashlib


module = "cmdc_login"


class CmdcDoLogin():

    """国药运营后台管理系统登录"""

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def get_token(self):
        # 获取唯一识别码
        uuid_handle = uuid.uuid4()
        # 获取验证码报文
        param = {"uuid": uuid_handle}
        # 获取登录页面获取验证码地址
        code_url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "getVerifyCode_url")
        # code_url = "https://service-slb.cmic.com.cn/sso/getVerifyCode"
        # 发送请求获取验证码
        result = requests.get(code_url, params=param)
        # print(result.content)
        # 获取当前文件路径
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        code_path = BASE_DIR + "/后台管理系统登录/verifycode.png"
        # 获取到验证码存入本地文件
        with open(code_path, 'wb') as f:
            f.write(result.content)
        # 识别并获取验证码
        code = VerificationCodeOcr(code_path, "rainbow123","rainbow123").base64_api()
        # 获取登录地址
        cmdc_url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "do_login_url")
        # cmdc_url = "https://service-slb.cmic.com.cn/sso/doLogin"
        md = hashlib.md5(self.password.encode())  # 创建md5对象
        EncryptPassword = md.hexdigest()  # 登录密码进行md5加密
        print('加密后的密码', EncryptPassword)  # 加密后的密码
        # 组装请求报文
        request_body = {"userName": self.username, "password": EncryptPassword, "validateCode": code, "uuid": uuid_handle}
        # print(request_body)
        # 发送请求
        result = requests.post(cmdc_url, params=request_body)
        # 获取预期结果
        # check_dict = commonFuc().get_business_data(module, "checkDict")
        # print(check_dict)
        # # 断言实际结果中是否包含预期结果的内容
        # commonFuc().check_result(check_dict, result)
        result = json.loads(result.content)
        print(result)
        access_token = commonFuc().analysis_json('accessToken', result)
        return access_token


if __name__ == "__main__":
    cmdc_access_token = CmdcDoLogin("Admin00111", "Aa123456").get_token()
    print(cmdc_access_token)

