# 验证码识别，暂只处理裁判文书网的验证码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.webdriver import WebDriver

import requests
from flask import current_app
from pathlib import Path
import tempfile
import uuid
import hashlib
import os
import json


# selecter: 验证码图片css选择器
def getCaptchaMode1(browser: WebDriver,selecter: str):
    ret = ""
    # 通过requests发送一个get请求到图片地址，返回的响应就是图片内容
    out_path = "./Temp_file"
    try:
        Path(out_path).mkdir(parents=True, exist_ok=True)
        # 将获取到的图片二进制流写入本地文件
        path_name = os.path.join(out_path, str(uuid.uuid4())) + ".png"
        print(path_name)
        # 保存验证码图片
        img = browser.find_element(By.CSS_SELECTOR, selecter)
        img.screenshot(path_name)
        # #url方式下载
        # r = requests.get(imgUrl)
        # with open(path_name, 'wb') as f:
        #     # 对于图片类型的通过r.content方式访问响应内容，将响应内容写入baidu.png中
        #     f.write(r.content)
        ocrUrl = current_app.config['sys.ocrUrl']
        # 调用文字识别服务
        file = open(path_name, "rb")
        response = requests.post(ocrUrl, files={"multiRequest": file})
        file.close()
        os.remove(path_name)
        # 返回：{"code":200,"logs":null,"message":"success","resultData":"2rVK"}
        oRet = json.loads(response.text)
        ret = oRet["resultData"]
        #os.remove(path_name)
        print(ret)
    except Exception as err:
        print('getCaptchaMode1 error:', err)
    return ret

