import datetime
import json
import math
import operator
import os
import random
import string
import time
from functools import reduce

import allure

from config import readConfig

import requests
from PIL import Image


def year_to_minute():
    return time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))


def month_day():
    return time.localtime().tm_mday


def month_not_today(para):
    today = datetime.datetime.today()
    if para >= 0:
        return today + datetime.timedelta(days=para)
    else:
        para = abs(para)
        return today - datetime.timedelta(days=para)


def week_day():
    week_day_name = time.localtime().tm_wday
    return week_day_name


def now_time():
    return int(time.time()*1000)


def year_to_day():
    return time.strftime('%Y-%m-%d', time.localtime(time.time()))


def file_abspath():
    return os.path.abspath(__file__).split('src')[0]


def screenshot_path(module_name):
    screen_path = file_abspath() + "/screenshots/"
    screen_day_path = file_abspath() + "/screenshots/" + year_to_day()
    screenshot_file = file_abspath() + "/screenshots/" + year_to_day() + "/" + module_name
    if not os.path.exists(screen_path):
        os.mkdir(screen_path)
    if not os.path.exists(screen_day_path):
        os.mkdir(screen_day_path)
    if not os.path.exists(screenshot_file):
        os.mkdir(screenshot_file)
    return screenshot_file


# 比较图片差异度，result越大，差异度越大，result=0，图片相同
def compare_pictures(pic1, pic2):
    image1 = Image.open(pic1)
    image2 = Image.open(pic2)
    h1 = image1.histogram()
    h2 = image2.histogram()
    result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))
    return result


# allure测试报告相关
# 添加截图至测试报告中
def get_allure_screenshots(screenshot_path, describe):
    with open(screenshot_path, "rb") as f:
        context = f.read()
        allure.attach(context, describe, allure.attachment_type.PNG)


# 小麦接口相关
# 获取登录token
def get_token(user, Terminal = 'SOW-B'):
    if Terminal == 'SOW-B':
        account = readConfig.test_header(user)['username']
        password = readConfig.test_header(user)['password']
        headers = {"Content-Type": "application/json; charset=UTF-8",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                                 "Chrome/91.0.4472.77 Safari/537.36"}
        params = {"phone": account, "authCode": password, "appTermEnum": "XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN"}
        data = json.dumps(params)
        url = "https://gateway.xiaomai5.com/hades/anon/hades/login?storeId=null&token=null&storeUserId=null&userId=null"
        r = requests.post(url=url, data=data, headers=headers)
        try:
            xmtoken = r.json()["result"]
        except Exception as e:
            return r.json()["message"]
        return xmtoken
    elif Terminal == 'SOW-C':
        enterprise_id = readConfig.test_header(user)['enterpriseId']
        user_id = readConfig.test_header(user)['userId']
        headers = {"Content-Type": "application/json; charset=UTF-8",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                                 "Chrome/91.0.4472.77 Safari/537.36"}
        params = {"enterpriseId": enterprise_id, "userId": user_id, "appTermEnum": "XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN"}
        data = json.dumps(params)
        url = "https://gateway.xiaomai5.com/hades/anon/hades/getWXWorkLoginNoCheck"
        r = requests.post(url=url, data=data, headers=headers)
        try:
            # xmtoken = r.json()["result"]["loginInfo"]
            xmtoken = r.json()["result"]["loginInfo"]["xmToken"]
        except Exception as e:
            return r.json()["message"]
        return xmtoken


# 创建一个直播课，返回课程id和课程名称
def create_a_live(start_time, start_time2=None, user="lgw-b"):
    xmtoken = get_token(user=user, Terminal='SOW-B')["xmToken"]
    basic_information = readConfig.test_header(header_name=user)
    userId = basic_information['userId']
    storeId = basic_information['storeId']
    storeUserId = basic_information['storeUserId']
    enterpriseId = basic_information['enterpriseId']
    while xmtoken == "登录过频繁":
        # 休息15s是因为可能会登录频繁
        time.sleep(15)
        xmtoken = get_token(user=user, Terminal='SOW-B')["xmToken"]
        print(xmtoken)
    dt = year_to_day() + ' 00:00:00'
    calendarTime = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))*1000
    startTime = now_time() + start_time*60*1000
    endTime = calendarTime + 23*60*60*1000
    # endTime = startTime + 5*60*1000
    courseName = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    courseName2 = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    url = "https://gateway.xiaomai5.com/hades/public/courseCloud/createLiveCloudCourse?storeId=" \
          "&token={}&storeUserId={}&userId={}".format(storeId, xmtoken, storeUserId, userId)
    params = {"adminIds": [], "calendarTime": [calendarTime], "categoryId": "1386892090935164929",
              "endTime": endTime, "needRecord": "YES", "startTime": startTime,
              "courseName": courseName, "storeId": storeId, "teacherId": userId,
              "whetherVisitorsJoin": "NO", "scheduleMediaRequests": [], "operatorId": userId}
    data = json.dumps(params)
    headers = {"Content-Type": "application/json; charset=UTF-8",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/91.0.4472.77 Safari/537.36",
               "storeId": storeId,
               "storeUserId": storeUserId,
               "xmtoken": xmtoken,
               "userId": userId,
               "product": "xmCloudClass",
               "enterpriseId": enterpriseId}
    r = requests.post(url=url, data=data, headers=headers)
    if start_time2 is not None:
        time.sleep(2)
        startTime2 = now_time() + start_time2*60*1000
        params2 = {"adminIds": [], "calendarTime": [calendarTime], "categoryId": "1386892090935164929",
                  "endTime": endTime, "needRecord": "YES", "startTime": startTime2,
                  "courseName": courseName2, "storeId": storeId, "teacherId": userId,
                  "whetherVisitorsJoin": "NO", "scheduleMediaRequests": [], "operatorId": userId}
        data2 = json.dumps(params2)
        r2 = requests.post(url=url, data=data2, headers=headers)
        try:
            # 校验result中是否会返回课程id
            assert r.json()["result"] != ''
            assert r2.json()["result"] != ''
            list1 = [courseName, courseName2]
            return list1
        except Exception as e:
            print(e.args)
    else:
        try:
            # 校验result中是否会返回课程id
            assert r.json()["result"] != ''
            return [courseName]
        except Exception as e:
            print(e.args)


def join_live_course(live_id, user='lgw-c'):
    xmtoken = get_token(user=user, Terminal='SOW-C')
    url = "https://heimdall.xiaomai5.com/hades/public/customerHades/getOrRegisterLiveUser"
    basic_imforation = readConfig.test_header(header_name=user)
    userId = basic_imforation['userId']
    storeId = basic_imforation['storeId']
    storeCustomerId = basic_imforation['storeCustomerId']
    enterpriseId = basic_imforation['enterpriseId']
    params = {"courseId": live_id, "customerId": storeCustomerId, "storeId": storeId, "userRole": "USER"}
    data = json.dumps(params)
    headers = {"Content-Type": "application/json; charset=UTF-8",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/91.0.4472.77 Safari/537.36",
               "storeId": storeId,
               "storeCustomerId": storeCustomerId,
               "xmtoken": xmtoken,
               "userId": userId,
               "product": "xmCloudClass",
               "enterpriseId": enterpriseId}

    r = requests.post(url=url, data=data, headers=headers)
    try:
        # 校验result中是否会返回课程id
        assert r.json()["result"] != ''
        return r.json()["result"]
    except Exception as e:
        print(e.args)
