import json

import requests
from selenium.webdriver.support.wait import WebDriverWait

from common.DButils import DButils
from common.untils import DriverTools
from config import file_path,wechaturl,userid,error_answer


def get_text(loc, time=10, fre=1):
    ele = WebDriverWait(DriverTools.get_driver(), time, fre).until(lambda x: x.find_element(*loc))
    return ele.text


def get_app_text(loc, time=10, fre=1):
    ele = WebDriverWait(DriverTools.get_app_driver(), time, fre).until(lambda x: x.find_element(*loc))
    return ele.text


def get_texts(loc, time=10, fre=1):
    eles = WebDriverWait(DriverTools.get_driver(), time, fre).until(lambda x: x.find_elements(*loc))
    ele_list = []
    for ele in eles:
        ele_list.append(ele.text)
    return ele_list


def get_app_texts(loc, time=10, fre=1):
    eles = WebDriverWait(DriverTools.get_app_driver(), time, fre).until(lambda x: x.find_elements(*loc))
    ele_list = []
    for ele in eles:
        ele_list.append(ele.text)
    return ele_list


def read_json(file_name):
    path = file_path + "/data/" + file_name
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    list1 = []
    for i in data:
        temp = tuple(i.values())
        list1.append(temp)

    return list1

# 发送微信消息
def error_message(text, url=wechaturl):
    data = {
        "msgtype": "text",
        "text": {
            "content": text
        }
    }
    requests.post(url, json=data)

# 发送mkdown格式微信消息
def mk_error_message(error_editor, error_answer, message_id, url=wechaturl):
    data = {
        "msgtype": "markdown",
        "markdown": {
            "content": f"ws推送<font color=\"warning\">异常</font>，请相关同事注意。\n>问题编辑:<font color=\"comment\">{error_editor}</font>\n>消息id:<font color=\"comment\">{message_id}</font>\n>返回消息:<font color=\"comment\">{error_answer}</font> "
        }
    }
    requests.post(url, json=data)

def ws_error(find_count, user_id=userid, error_answer_list=error_answer):
    data = DButils().select_sql(
        f"select emp_id,content,id  from aicaptain.message_record mr where adviser_id ={user_id} and msg_type != 1 "
        f" and msg_code is null  order by create_time desc limit {find_count} ")
    for i in range(len(data)):
        for n in error_answer_list:
            if n in data[i][1]:
                editor = DButils().select_sql(
                    f"select name from aicaptain.job where id= (SELECT job_id  FROM aicaptain.employee  WHERE "
                    f" id= {data[i][0]} ); ")
                mk_error_message(editor[0][0], n, data[i][2])
